repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
glentregoning/BotTest
BotTest/AppDelegate.swift
1
6093
// // AppDelegate.swift // BotTest // // Created by Glen Tregoning on 7/18/15. // Copyright © 2015 Glen Tregoning. 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. 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 "info.gtbox.BotTest" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() 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("BotTest", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns 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 let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // 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 as NSError let wrappedError = 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 \(wrappedError), \(wrappedError.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 var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
3a4b836dbfe4264c183c34414a7f5643
53.882883
291
0.719468
5.86333
false
false
false
false
FCiottoli/eCalendar
eCalendar/ViewController.swift
1
2671
// // ViewController.swift // eCalendar // // Created by Federico Giuntoli on 11/08/16. // Copyright © 2016 Federico Giuntoli. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var monthLabel: UILabel! @IBOutlet weak var CalendarView: eCalendar! @IBOutlet weak var daySelectedLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() CalendarView.addObserver(self, forKeyPath: "dateSelected", options: .new, context: nil) } override func viewDidAppear(_ animated : Bool){ monthLabel.text? = self.getMonthString() } override func observeValue(forKeyPath keyPath: String?, of object: AnyObject?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutablePointer<Void>?) { //Add any method to perform each day selected setLabel() } ///Load and Display next month @IBAction func nextMonth(_ sender: AnyObject) { self.CalendarView.offset = self.CalendarView.offset + 1 self.CalendarView.setNeedsDisplay() DispatchQueue.global(qos: .background).async { DispatchQueue.main.async { self.monthLabel.text? = self.getMonthString() } } } ///Load and Display previous month @IBAction func previousMonth(_ sender: AnyObject) { self.CalendarView.offset = self.CalendarView.offset - 1 self.CalendarView.setNeedsDisplay() DispatchQueue.global(qos: .background).async { DispatchQueue.main.async { self.monthLabel.text? = self.getMonthString() } } } func getMonthString()->String{ let formatter = DateFormatter() let DateFormat = DateFormatter.dateFormat(fromTemplate: "MMMM yyy", options: 0, locale: Locale.autoupdatingCurrent) formatter.dateFormat = DateFormat var components = Calendar.current.dateComponents([.day, .year, .month], from: Date()) components.month = CalendarView.monthSelected components.year = CalendarView.yearSelected let printString = formatter.string(from: Calendar.current.date(from: components)!) return printString } func setLabel(){ let formatter = DateFormatter() let DateFormat = DateFormatter.dateFormat(fromTemplate: "EEEE dd MMMM yyy", options: 0, locale: Locale.autoupdatingCurrent) formatter.dateFormat = DateFormat let printString = formatter.string(from: CalendarView.dateSelected) daySelectedLabel.text = String(printString) } }
apache-2.0
cd8cfdcd784f58c60d6f86450bbe83df
33.675325
166
0.648689
5.009381
false
false
false
false
sschiau/swift
test/SILGen/default_arguments_local.swift
5
5279
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF : $@convention(thin) <T> (Int, @guaranteed AnyObject, @in_guaranteed Any, @in_guaranteed T) -> () func outer<T>(x: Int, y: AnyObject, z: Any, w: T) { func local1(x: Int = x) {} func local2(y: AnyObject = y) {} func local3(z: Any = z) {} func local4(w: T = w) {} func local5<U>(u: U, w: T = w) {} // CHECK: [[FN:%.*]] = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local1L_ACySi_tlFfA_ : $@convention(thin) (Int) -> Int // CHECK: [[ARG:%.*]] = apply [[FN]](%0) : $@convention(thin) (Int) -> Int // CHECK: [[LOCAL1:%.*]] = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local1L_ACySi_tlF : $@convention(thin) (Int, Int) -> () // CHECK: apply [[LOCAL1]]([[ARG]], %0) : $@convention(thin) (Int, Int) -> () local1() // CHECK: [[FN:%.*]] = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local2L_ADyyXl_tlFfA_ : $@convention(thin) (@guaranteed AnyObject) -> @owned AnyObject // CHECK: [[ARG:%.*]] = apply [[FN]](%1) : $@convention(thin) (@guaranteed AnyObject) -> @owned AnyObject // CHECK: [[LOCAL2:%.*]] = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local2L_ADyyXl_tlF : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> () // CHECK: apply [[LOCAL2]]([[ARG]], %1) : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> () // CHECK: destroy_value [[ARG]] : $AnyObject local2() // CHECK: [[BOX:%.*]] = alloc_box ${ var Any } // CHECK: [[BOX_ADDR:%.*]] = project_box [[BOX]] : ${ var Any }, 0 // CHECK: copy_addr %2 to [initialization] [[BOX_ADDR]] : $*Any // CHECK: [[BOX_BORROW:%.*]] = begin_borrow [[BOX]] : ${ var Any } // CHECK: [[FN:%.*]] = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local3L_AEyyp_tlFfA_ : $@convention(thin) (@guaranteed { var Any }) -> @out Any // CHECK: [[STACK:%.*]] = alloc_stack $Any // CHECK: [[BOX2:%.*]] = alloc_box ${ var Any } // CHECK: [[BOX2_ADDR:%.*]] = project_box [[BOX2]] : ${ var Any }, 0 // CHECK: copy_addr %2 to [initialization] [[BOX2_ADDR]] : $*Any // CHECK: [[BOX2_BORROW:%.*]] = begin_borrow [[BOX2]] : ${ var Any } // CHECK: apply [[FN]]([[STACK]], [[BOX2_BORROW]]) : $@convention(thin) (@guaranteed { var Any }) -> @out Any // CHECK: end_borrow [[BOX2_BORROW]] : ${ var Any } // CHECK: destroy_value [[BOX2]] : ${ var Any } // CHECK: %30 = function_ref @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local3L_AEyyp_tlF : $@convention(thin) (@in_guaranteed Any, @guaranteed { var Any }) -> () // CHECK: apply %30([[STACK]], [[BOX_BORROW]]) : $@convention(thin) (@in_guaranteed Any, @guaranteed { var Any }) -> () // CHECK: destroy_addr [[STACK]] : $*Any // CHECK: dealloc_stack [[STACK]] : $*Any // CHECK: end_borrow [[BOX_BORROW]] : ${ var Any } // CHECK: destroy_value [[BOX]] : ${ var Any } local3() local4() local5(u: "hi") } // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local1L_ACySi_tlFfA_ : $@convention(thin) (Int) -> Int // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local1L_ACySi_tlF : $@convention(thin) (Int, Int) -> () // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local2L_ADyyXl_tlFfA_ : $@convention(thin) (@guaranteed AnyObject) -> @owned AnyObject // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local2L_ADyyXl_tlF : $@convention(thin) (@guaranteed AnyObject, @guaranteed AnyObject) -> () // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local3L_AEyyp_tlFfA_ : $@convention(thin) (@guaranteed { var Any }) -> @out Any // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local3L_AEyyp_tlF : $@convention(thin) (@in_guaranteed Any, @guaranteed { var Any }) -> () // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local4L_AFyx_tlF : $@convention(thin) <T> (@in_guaranteed T, @guaranteed <τ_0_0> { var τ_0_0 } <T>) -> () // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local5outer1x1y1z1wySi_yXlypxtlF6local5L_1uAFyqd___xtr__lFfA0_ : $@convention(thin) <T><U> (@guaranteed <τ_0_0> { var τ_0_0 } <T>) -> @out T class ArtClass<T> { // CHECK-LABEL: sil hidden [ossa] @$s23default_arguments_local8ArtClassC10selfMethod1uyqd___tlF : $@convention(method) <T><U> (@in_guaranteed U, @guaranteed ArtClass<T>) -> () func selfMethod<U>(u: U) { // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local8ArtClassC10selfMethod1uyqd___tlF0C0L_1vAE1syqd0___qd__Sitr___lFfA1_ : $@convention(thin) <T><U><V> (@thick @dynamic_self ArtClass<T>.Type) -> Int // CHECK-LABEL: sil private [ossa] @$s23default_arguments_local8ArtClassC10selfMethod1uyqd___tlF0C0L_1vAE1syqd0___qd__Sitr___lF : $@convention(thin) <T><U><V> (@in_guaranteed V, @in_guaranteed U, Int, @thick @dynamic_self ArtClass<T>.Type) -> () func local<V>(v: V, u: U, s: Int = Self.intMethod()) {} } static func intMethod() -> Int { return 0 } }
apache-2.0
d98659b5f482978b89f999b15f4fe09a
73.295775
249
0.656493
2.907938
false
false
false
false
Acidburn0zzz/firefox-ios
Client/Frontend/Theme/ThemedWidgets.swift
1
5909
/* 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 UIKit class ThemedTableViewCell: UITableViewCell, Themeable { var detailTextColor = UIColor.theme.tableView.disabledRowText override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { textLabel?.textColor = UIColor.theme.tableView.rowText detailTextLabel?.textColor = detailTextColor backgroundColor = UIColor.theme.tableView.rowBackground tintColor = UIColor.theme.general.controlTint } } class ThemedTableViewController: UITableViewController, Themeable { override init(style: UITableView.Style = .grouped) { super.init(style: style) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: nil) return cell } override func viewDidLoad() { super.viewDidLoad() applyTheme() } func applyTheme() { tableView.separatorColor = UIColor.theme.tableView.separator tableView.backgroundColor = UIColor.theme.tableView.headerBackground tableView.reloadData() (tableView.tableHeaderView as? Themeable)?.applyTheme() } } class ThemedTableSectionHeaderFooterView: UITableViewHeaderFooterView, Themeable { private struct UX { static let titleHorizontalPadding: CGFloat = 15 static let titleVerticalPadding: CGFloat = 6 static let titleVerticalLongPadding: CGFloat = 20 } enum TitleAlignment { case top case bottom } var titleAlignment: TitleAlignment = .bottom { didSet { remakeTitleAlignmentConstraints() } } lazy var titleLabel: UILabel = { var headerLabel = UILabel() headerLabel.font = UIFont.systemFont(ofSize: 12.0, weight: UIFont.Weight.regular) headerLabel.numberOfLines = 0 return headerLabel }() fileprivate lazy var bordersHelper = ThemedHeaderFooterViewBordersHelper() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) contentView.addSubview(titleLabel) bordersHelper.initBorders(view: self.contentView) setDefaultBordersValues() setupInitialConstraints() applyTheme() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func applyTheme() { bordersHelper.applyTheme() contentView.backgroundColor = UIColor.theme.tableView.headerBackground titleLabel.textColor = UIColor.theme.tableView.headerTextLight } func setupInitialConstraints() { remakeTitleAlignmentConstraints() } func showBorder(for location: ThemedHeaderFooterViewBordersHelper.BorderLocation, _ show: Bool) { bordersHelper.showBorder(for: location, show) } func setDefaultBordersValues() { bordersHelper.showBorder(for: .top, false) bordersHelper.showBorder(for: .bottom, false) } override func prepareForReuse() { super.prepareForReuse() setDefaultBordersValues() titleLabel.text = nil titleAlignment = .bottom applyTheme() } fileprivate func remakeTitleAlignmentConstraints() { switch titleAlignment { case .top: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding) make.top.equalTo(self.contentView).offset(UX.titleVerticalPadding) make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalLongPadding) } case .bottom: titleLabel.snp.remakeConstraints { make in make.left.right.equalTo(self.contentView).inset(UX.titleHorizontalPadding) make.bottom.equalTo(self.contentView).offset(-UX.titleVerticalPadding) make.top.equalTo(self.contentView).offset(UX.titleVerticalLongPadding) } } } } class ThemedHeaderFooterViewBordersHelper: Themeable { enum BorderLocation { case top case bottom } fileprivate lazy var topBorder: UIView = { let topBorder = UIView() return topBorder }() fileprivate lazy var bottomBorder: UIView = { let bottomBorder = UIView() return bottomBorder }() func showBorder(for location: BorderLocation, _ show: Bool) { switch location { case .top: topBorder.isHidden = !show case .bottom: bottomBorder.isHidden = !show } } func initBorders(view: UIView) { view.addSubview(topBorder) view.addSubview(bottomBorder) topBorder.snp.makeConstraints { make in make.left.right.top.equalTo(view) make.height.equalTo(0.25) } bottomBorder.snp.makeConstraints { make in make.left.right.bottom.equalTo(view) make.height.equalTo(0.5) } } func applyTheme() { topBorder.backgroundColor = UIColor.theme.tableView.separator bottomBorder.backgroundColor = UIColor.theme.tableView.separator } } class UISwitchThemed: UISwitch { override func layoutSubviews() { super.layoutSubviews() onTintColor = UIColor.theme.general.controlTint } }
mpl-2.0
5030861336c14de89c78c38cc0acae7f
29.937173
109
0.66221
5.072103
false
false
false
false
Bygo/BGChatBotMessaging-iOS
Example/Pods/BGMessaging/BGMessaging/Classes/Layouts/BGMessagingCollectionViewFlowLayout.swift
2
6090
// // BGMessagingCollectionViewFlowLayout.swift // Pods // // Created by Nicholas Garfield on 13/6/16. // // import UIKit public class BGMessagingCollectionViewFlowLayout: UICollectionViewFlowLayout { /** * This object calculates bubble sizes for messages. */ private var bubbleSizeCalculator: BGMessagingBubbleSizeCalculator = BGMessagingBubbleSizeCalculator() private var cache: NSCache = NSCache() /** * The width of items in the layout */ var itemWidth: CGFloat { get { return collectionView!.frame.size.width } } // MARK: - Object Life Cycle public override init() { super.init() configure() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } // MARK: - Configuration private func configure() { scrollDirection = .Vertical sectionInset = UIEdgeInsetsMake(8.0, 0.0, 4.0, 0.0) minimumLineSpacing = 4.0 } public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { guard let oldBounds = collectionView?.bounds else { return false } return oldBounds.width != newBounds.width || oldBounds.height != newBounds.height } public override func prepareLayout() { super.prepareLayout() cache.removeAllObjects() for section in 0..<collectionView!.numberOfSections() { for item in 0..<collectionView!.numberOfItemsInSection(section) { let indexPath = NSIndexPath(forItem: item, inSection: section) if let attributes = layoutAttributesForItemAtIndexPath(indexPath) { cache.setObject(attributes, forKey: indexPath) } } } } // MARK: - Content Size public override func collectionViewContentSize() -> CGSize { let numCells = collectionView!.numberOfItemsInSection(0) if numCells > 0 { if let lastCellFrame = (cache.objectForKey(NSIndexPath(forItem: numCells-1, inSection: 0)) as? UICollectionViewLayoutAttributes)?.frame { let width = collectionView!.bounds.width let height = lastCellFrame.origin.y + lastCellFrame.size.height + 4.0 return CGSizeMake(width, height) } } return collectionView!.bounds.size } // MARK: - IndexPaths private func indexPathsOfItems(inRect rect: CGRect) -> [NSIndexPath] { var indexPaths: [NSIndexPath] = [] for section in 0..<collectionView!.numberOfSections() { for item in 0..<collectionView!.numberOfItemsInSection(section) { let indexPath = NSIndexPath(forItem: item, inSection: section) if let attributes = cache.objectForKey(indexPath) as? UICollectionViewLayoutAttributes { if CGRectIntersectsRect(attributes.frame, rect) { indexPaths.append(indexPath) } } } } return indexPaths } private func indexPathsOfTypingIndicatorFooterViews(inRect rect: CGRect) -> [NSIndexPath] { if let showTypingIndicator = (collectionView as? BGMessagingCollectionView)?.showTypingIndicator { if showTypingIndicator { return [NSIndexPath(index: 0)] } } return [] } private func indexPathsOfLoadEarlierHeaderViews(inRect rect: CGRect) -> [NSIndexPath] { return [] } // MARK: - Layout Attributes public override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var layoutAttributes: [UICollectionViewLayoutAttributes] = [] let visibleIndexPaths = indexPathsOfItems(inRect: rect) for indexPath in visibleIndexPaths { if let attributes = layoutAttributesForItemAtIndexPath(indexPath) { layoutAttributes.append(attributes) } } let footerIndexPaths = indexPathsOfTypingIndicatorFooterViews(inRect: rect) for indexPath in footerIndexPaths { if let attributes = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionFooter, atIndexPath: indexPath) { layoutAttributes.append(attributes) } } let headerIndexPaths = indexPathsOfLoadEarlierHeaderViews(inRect: rect) for indexPath in headerIndexPaths { if let attributes = layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: indexPath) { layoutAttributes.append(attributes) } } return layoutAttributes } public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = cache.objectForKey(indexPath) as? UICollectionViewLayoutAttributes { return attributes } let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) if let data = (collectionView?.dataSource as? BGMessagingCollectionViewDataSource)?.collectionView(collectionView as! BGMessagingCollectionView, messageDataForItemAtIndexPath: indexPath) { let size = bubbleSizeCalculator.messageBubbleSizeForMessageData(data, atIndexPath: indexPath, withLayout: self) attributes.frame.size = CGSizeMake(itemWidth, size.height) if indexPath.row > 0 { if let previousCellFrame = layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: indexPath.item-1, inSection: indexPath.section))?.frame { attributes.frame.origin.y = previousCellFrame.origin.y + previousCellFrame.size.height + 4.0 } } } cache.setObject(attributes, forKey: indexPath) return attributes } }
mit
575368fbac0a74af6e3e2a12fe0fe9e0
36.826087
196
0.637438
5.941463
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureCardPayment/Sources/FeatureCardPaymentDomain/Model/ActivateCardResponse.swift
1
3713
// Copyright © Blockchain Luxembourg S.A. All rights reserved. public struct ActivateCardResponse: Decodable { public enum Partner { public struct EveryPayData: Decodable { public init(apiUsername: String, mobileToken: String, paymentLink: String, paymentState: String) { self.apiUsername = apiUsername self.mobileToken = mobileToken self.paymentLink = paymentLink self.paymentState = paymentState } public let apiUsername: String public let mobileToken: String public let paymentLink: String public let paymentState: String } case everypay(EveryPayData) case cardAcquirer(CardAcquirer) case unknown public var isKnown: Bool { switch self { case .unknown: return false default: return true } } } private enum CodingKeys: String, CodingKey { case everypay case cardProvider } public enum PaymentState: String, Decodable { /// Should never happen. It means a case was forgotten by backend case initial = "INITIAL" /// We have to display a 3DS verification popup case waitingFor3DS = "WAITING_FOR_3DS_RESPONSE" /// 3DS valid case confirmed3DS = "CONFIRMED_3DS" /// Ready for capture, no need for 3DS case settled = "SETTLED" /// Payment voided case voided = "VOIDED" /// Payment abandonned case abandoned = "ABANDONED" /// Payment failed case failed = "FAILED" /// Just in case case unknown } public struct CardAcquirer: Decodable { public let cardAcquirerName: CardPayload.Acquirer public let cardAcquirerAccountCode: String public let apiUserID: String? public let apiToken: String? public let paymentLink: String? public let paymentState: PaymentState public let paymentReference: String? public let orderReference: String? public let clientSecret: String? public let publishableApiKey: String? public init( cardAcquirerName: CardPayload.Acquirer, cardAcquirerAccountCode: String, apiUserID: String?, apiToken: String?, paymentLink: String?, paymentState: String, paymentReference: String?, orderReference: String?, clientSecret: String?, publishableApiKey: String? ) { self.cardAcquirerName = cardAcquirerName self.cardAcquirerAccountCode = cardAcquirerAccountCode self.apiUserID = apiUserID self.apiToken = apiToken self.paymentLink = paymentLink self.paymentState = .init(rawValue: paymentState) ?? .unknown self.paymentReference = paymentReference self.orderReference = orderReference self.clientSecret = clientSecret self.publishableApiKey = publishableApiKey } } public let partner: Partner public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let acquirer = try values.decodeIfPresent(CardAcquirer.self, forKey: .cardProvider) if let data = try values.decodeIfPresent(Partner.EveryPayData.self, forKey: .everypay) { partner = .everypay(data) } else if let acquirer = acquirer { partner = .cardAcquirer(acquirer) } else { partner = .unknown } } }
lgpl-3.0
319a632d1f03bb23fa6380a95f16dff3
31
110
0.601563
4.858639
false
false
false
false
hanzhuzi/XRVideoPlayer-master
XRPlayer/PlayViewController.swift
1
3113
// // PlayViewController.swift // XRPlayer // // Created by xuran on 2019/11/12. // Copyright © 2019 xuran. All rights reserved. // import UIKit class PlayViewController: UIViewController, XRPlayerPlaybackDelegate { private var playerView: XRPlayer! private var isHiddenStatusBar: Bool = false override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white self.setupPlayer() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) playerView.addRemoteControlEvents() playerView.setAVAudioSessionActive(isActive: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.playerView.shutDown() self.playerView.setAVAudioSessionActive(isActive: false) } override var prefersStatusBarHidden: Bool { return isHiddenStatusBar } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } func setupPlayer() { guard let url = URL(string: "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else { return } playerView = XRPlayer(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.width / 16.0 * 10.0), url: url) self.view.addSubview(playerView) playerView.isAutoToPlay = false playerView.title = "测试标题" playerView.coverImageURL = "" playerView.delegate = self playerView.playerOrientationDidChangedClosure = { [weak self](isFullScreenPlay) in if let weakSelf = self { weakSelf.isHiddenStatusBar = isFullScreenPlay weakSelf.setNeedsStatusBarAppearanceUpdate() } } playerView.playerBackButtonActionClosure = { [weak self] in if let weakSelf = self { if weakSelf.playerView.isFullScreenPlay { weakSelf.playerView.exitFullScreenPlayWithOrientationPortraint() } else { weakSelf.navigationController?.popViewController(animated: true) } } } } // MARK: - 屏幕旋转控制 (默认是竖屏) override var shouldAutorotate: Bool { return false } // MARK: - XRPlayerPlaybackDelegate func playerPlaybackProgressDidChaned(progress: Double) { } func playerPlayStatusDidPlaying() { } }
mit
4ce27798c2e445331b7dac28d3aff618
26.274336
161
0.603829
5.341421
false
false
false
false
to4iki/OctavKit
OctavKit/Extension/Date+components.swift
1
1510
import Foundation extension Date { var year: Int { return components.year! } var month: Int { return components.month! } var weekday: Int { return components.weekday! } var day: Int { return components.day! } var hour: Int { return components.hour! } var minute: Int { return components.minute! } var second: Int { return components.second! } func add(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) -> Date! { var components = self.components components.year = year ?? self.year components.month = month ?? self.month components.day = day ?? self.day components.hour = hour ?? self.hour components.minute = minute ?? self.minute components.second = second ?? self.second return calendar.date(from: components) } static func date(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) -> Date { let now = Date() return now.add(year: year, month: month, day: day, hour: hour, minute: minute, second: second) } } extension Date { private var components: DateComponents { return calendar.dateComponents([.year, .month, .weekday, .day, .hour, .minute, .second], from: self) } private var calendar: Calendar { return Calendar(identifier: Calendar.Identifier.gregorian) } }
mit
9a6cc31a9942280f9fc98881c3386c56
25.491228
135
0.592715
3.973684
false
false
false
false
naokits/bluemix-swift-demo-ios
Pods/BMSSecurity/Source/mca/internal/certificate/SecurityUtils.swift
2
15803
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import Foundation import RNCryptor internal class SecurityUtils { private static func savePublicKeyToKeyChain(key:SecKey,tag:String) throws { let publicKeyAttr : [NSString:AnyObject] = [ kSecValueRef: key, kSecAttrIsPermanent : true, kSecAttrApplicationTag : tag, kSecAttrKeyClass : kSecAttrKeyClassPublic ] let addStatus:OSStatus = SecItemAdd(publicKeyAttr, nil) guard addStatus == errSecSuccess else { throw BMSSecurityError.generalError } } private static func getKeyBitsFromKeyChain(tag:String) throws -> NSData { let keyAttr : [NSString:AnyObject] = [ kSecClass : kSecClassKey, kSecAttrApplicationTag: tag, kSecAttrKeyType : kSecAttrKeyTypeRSA, kSecReturnData : true ] var result: AnyObject? let status = SecItemCopyMatching(keyAttr, &result) guard status == errSecSuccess else { throw BMSSecurityError.generalError } return result as! NSData } internal static func generateKeyPair(keySize:Int, publicTag:String, privateTag:String)throws -> (publicKey: SecKey, privateKey: SecKey) { //make sure keys are deleted SecurityUtils.deleteKeyFromKeyChain(publicTag) SecurityUtils.deleteKeyFromKeyChain(privateTag) var status:OSStatus = noErr var privateKey:SecKey? var publicKey:SecKey? let privateKeyAttr : [NSString:AnyObject] = [ kSecAttrIsPermanent : true, kSecAttrApplicationTag : privateTag, kSecAttrKeyClass : kSecAttrKeyClassPrivate ] let publicKeyAttr : [NSString:AnyObject] = [ kSecAttrIsPermanent : true, kSecAttrApplicationTag : publicTag, kSecAttrKeyClass : kSecAttrKeyClassPublic, ] let keyPairAttr : [NSString:AnyObject] = [ kSecAttrKeyType : kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits : keySize, kSecPublicKeyAttrs : publicKeyAttr, kSecPrivateKeyAttrs : privateKeyAttr ] status = SecKeyGeneratePair(keyPairAttr, &publicKey, &privateKey) if (status != errSecSuccess) { throw BMSSecurityError.generalError } else { return (publicKey!, privateKey!) } } private static func getKeyPairBitsFromKeyChain(publicTag:String, privateTag:String) throws -> (publicKey: NSData, privateKey: NSData) { return try (getKeyBitsFromKeyChain(publicTag),getKeyBitsFromKeyChain(privateTag)) } private static func getKeyPairRefFromKeyChain(publicTag:String, privateTag:String) throws -> (publicKey: SecKey, privateKey: SecKey) { return try (getKeyRefFromKeyChain(publicTag),getKeyRefFromKeyChain(privateTag)) } private static func getKeyRefFromKeyChain(tag:String) throws -> SecKey { let keyAttr : [NSString:AnyObject] = [ kSecClass : kSecClassKey, kSecAttrApplicationTag: tag, kSecAttrKeyType : kSecAttrKeyTypeRSA, kSecReturnRef : kCFBooleanTrue ] var result: AnyObject? let status = SecItemCopyMatching(keyAttr, &result) guard status == errSecSuccess else { throw BMSSecurityError.generalError } return result as! SecKey } internal static func getCertificateFromKeyChain(certificateLabel:String) throws -> SecCertificate { let getQuery : [NSString: AnyObject] = [ kSecClass : kSecClassCertificate, kSecReturnRef : true, kSecAttrLabel : certificateLabel ] var result: AnyObject? let getStatus = SecItemCopyMatching(getQuery, &result) guard getStatus == errSecSuccess else { throw BMSSecurityError.generalError } return result as! SecCertificate } internal static func getItemFromKeyChain(label:String) -> String? { let query: [NSString: AnyObject] = [ kSecClass: kSecClassGenericPassword, kSecAttrService: label, kSecReturnData: kCFBooleanTrue ] var results: AnyObject? let status = SecItemCopyMatching(query, &results) if status == errSecSuccess { let data = results as! NSData let password = String(data: data, encoding: NSUTF8StringEncoding)! return password } return nil } internal static func signCsr(payloadJSON:[String : AnyObject], keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String { do { let strPayloadJSON = try Utils.JSONStringify(payloadJSON) let keys = try getKeyPairBitsFromKeyChain(ids.publicKey, privateTag: ids.privateKey) let publicKey = keys.publicKey let privateKeySec = try getKeyPairRefFromKeyChain(ids.publicKey, privateTag: ids.privateKey).privateKey let strJwsHeaderJSON = try Utils.JSONStringify(getJWSHeaderForPublicKey(publicKey)) guard let jwsHeaderData : NSData = strJwsHeaderJSON.dataUsingEncoding(NSUTF8StringEncoding), payloadJSONData : NSData = strPayloadJSON.dataUsingEncoding(NSUTF8StringEncoding) else { throw BMSSecurityError.generalError } let jwsHeaderBase64 = Utils.base64StringFromData(jwsHeaderData, isSafeUrl: true) let payloadJSONBase64 = Utils.base64StringFromData(payloadJSONData, isSafeUrl: true) let jwsHeaderAndPayload = jwsHeaderBase64.stringByAppendingString(".".stringByAppendingString(payloadJSONBase64)) let signedData = try signData(jwsHeaderAndPayload, privateKey:privateKeySec) let signedDataBase64 = Utils.base64StringFromData(signedData, isSafeUrl: true) return jwsHeaderAndPayload.stringByAppendingString(".".stringByAppendingString(signedDataBase64)) } catch { throw BMSSecurityError.generalError } } private static func getJWSHeaderForPublicKey(publicKey: NSData) throws ->[String:AnyObject] { let base64Options = NSDataBase64EncodingOptions(rawValue:0) guard let pkModulus : NSData = getPublicKeyMod(publicKey), let pkExponent : NSData = getPublicKeyExp(publicKey) else { throw BMSSecurityError.generalError } let mod:String = pkModulus.base64EncodedStringWithOptions(base64Options) let exp:String = pkExponent.base64EncodedStringWithOptions(base64Options) let publicKeyJSON : [String:AnyObject] = [ BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RSA_VALUE, BMSSecurityConstants.JSON_MOD_KEY : mod, BMSSecurityConstants.JSON_EXP_KEY : exp ] let jwsHeaderJSON :[String:AnyObject] = [ BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RS256_VALUE, BMSSecurityConstants.JSON_JPK_KEY : publicKeyJSON ] return jwsHeaderJSON } private static func getPublicKeyMod(publicKeyBits: NSData) -> NSData? { var iterator : Int = 0 iterator++ // TYPE - bit stream - mod + exp derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size iterator++ // TYPE - bit stream mod let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) if(mod_size == -1) { return nil } return publicKeyBits.subdataWithRange(NSMakeRange(iterator, mod_size)) } //Return public key exponent private static func getPublicKeyExp(publicKeyBits: NSData) -> NSData? { var iterator : Int = 0 iterator++ // TYPE - bit stream - mod + exp derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size iterator++// TYPE - bit stream mod let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) iterator += mod_size iterator++ // TYPE - bit stream exp let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator) //Ensure we got an exponent size if(exp_size == -1) { return nil } return publicKeyBits.subdataWithRange(NSMakeRange(iterator, exp_size)) } private static func derEncodingGetSizeFrom(buf : NSData, inout at iterator: Int) -> Int{ // Have to cast the pointer to the right size let pointer = UnsafePointer<UInt8>(buf.bytes) let count = buf.length // Get our buffer pointer and make an array out of it let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count) let data = [UInt8](buffer) var itr : Int = iterator var num_bytes :UInt8 = 1 var ret : Int = 0 if (data[itr] > 0x80) { num_bytes = data[itr] - 0x80 itr++ } for var i = 0; i < Int(num_bytes); i++ { ret = (ret * 0x100) + Int(data[itr + i]) } iterator = itr + Int(num_bytes) return ret } private static func signData(payload:String, privateKey:SecKey) throws -> NSData { guard let data:NSData = payload.dataUsingEncoding(NSUTF8StringEncoding) else { throw BMSSecurityError.generalError } func doSha256(dataIn:NSData) throws -> NSData { guard let shaOut: NSMutableData = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) else { throw BMSSecurityError.generalError } CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(shaOut.mutableBytes)) return shaOut } guard let digest:NSData = try? doSha256(data), signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else { throw BMSSecurityError.generalError } var signedDataLength: Int = signedData.length let digestBytes = UnsafePointer<UInt8>(digest.bytes) let digestlen = digest.length let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen, UnsafeMutablePointer<UInt8>(signedData.mutableBytes), &signedDataLength) guard signStatus == errSecSuccess else { throw BMSSecurityError.generalError } return signedData } internal static func saveItemToKeyChain(data:String, label: String) -> Bool{ guard let stringData = data.dataUsingEncoding(NSUTF8StringEncoding) else { return false } let key: [NSString: AnyObject] = [ kSecClass: kSecClassGenericPassword, kSecAttrService: label, kSecValueData: stringData ] let status = SecItemAdd(key, nil) return status == errSecSuccess } internal static func removeItemFromKeyChain(label: String) -> Bool{ let delQuery : [NSString:AnyObject] = [ kSecClass: kSecClassGenericPassword, kSecAttrService: label ] let delStatus:OSStatus = SecItemDelete(delQuery) return delStatus == errSecSuccess } internal static func getCertificateFromString(stringData:String) throws -> SecCertificate{ if let data:NSData = NSData(base64EncodedString: stringData, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) { if let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, data) { return certificate } } throw BMSSecurityError.generalError } internal static func deleteCertificateFromKeyChain(certificateLabel:String) -> Bool{ let delQuery : [NSString:AnyObject] = [ kSecClass: kSecClassCertificate, kSecAttrLabel: certificateLabel ] let delStatus:OSStatus = SecItemDelete(delQuery) return delStatus == errSecSuccess } private static func deleteKeyFromKeyChain(tag:String) -> Bool{ let delQuery : [NSString:AnyObject] = [ kSecClass : kSecClassKey, kSecAttrApplicationTag : tag ] let delStatus:OSStatus = SecItemDelete(delQuery) return delStatus == errSecSuccess } internal static func saveCertificateToKeyChain(certificate:SecCertificate, certificateLabel:String) throws { //make sure certificate is deleted deleteCertificateFromKeyChain(certificateLabel) //set certificate in key chain let setQuery: [NSString: AnyObject] = [ kSecClass: kSecClassCertificate, kSecValueRef: certificate, kSecAttrLabel: certificateLabel, kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, ] let addStatus:OSStatus = SecItemAdd(setQuery, nil) guard addStatus == errSecSuccess else { throw BMSSecurityError.generalError } } internal static func checkCertificatePublicKeyValidity(certificate:SecCertificate, publicKeyTag:String) throws -> Bool{ let certificatePublicKeyTag = "checkCertificatePublicKeyValidity : publicKeyFromCertificate" var publicKeyBits = try getKeyBitsFromKeyChain(publicKeyTag) let policy = SecPolicyCreateBasicX509() var trust: SecTrust? var status = SecTrustCreateWithCertificates(certificate, policy, &trust) if let unWrappedTrust = trust where status == errSecSuccess { if let certificatePublicKey = SecTrustCopyPublicKey(unWrappedTrust) { defer { SecurityUtils.deleteKeyFromKeyChain(certificatePublicKeyTag) } try savePublicKeyToKeyChain(certificatePublicKey, tag: certificatePublicKeyTag) let ceritificatePublicKeyBits = try getKeyBitsFromKeyChain(certificatePublicKeyTag) if(ceritificatePublicKeyBits == publicKeyBits){ return true } } } throw BMSSecurityError.generalError } internal static func clearDictValuesFromKeyChain(dict : [String : NSString]) { for (tag, kSecClassName) in dict { if kSecClassName == kSecClassCertificate { deleteCertificateFromKeyChain(tag) } else if kSecClassName == kSecClassKey { deleteKeyFromKeyChain(tag) } else if kSecClassName == kSecClassGenericPassword { removeItemFromKeyChain(tag) } } } }
mit
63c2b6608173aca822bdec2d6f060f85
38.141439
193
0.62905
5.534386
false
false
false
false
mozilla-magnet/magnet-client
ios/ApiSubscriptions.swift
1
1151
// // ApiSubscriptions.swift // Magnet // // Created by Francisco Jordano on 02/11/2016. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import SwiftyJSON class ApiSubscriptions: ApiBase { private static let PATH = "content://subscriptions" private var subscriptions: Subscriptions! override init() { super.init() subscriptions = Subscriptions() } override func get(path: String, callback: ApiCallback) { let all = subscriptions.get() var jsonObject = JSON([:]) all.forEach { (record) in let jsonRecord: JSON = ["channel_id": record.channel_name, "notifications_enabled": true] jsonObject[record.channel_name] = jsonRecord } callback.onSuccess(jsonObject) } override func post(path: String, data: NSDictionary, callback: ApiCallback) { subscriptions.add(data["channel_id"] as! String) let json = JSON(data) callback.onSuccess(json) } override func delete(path: String, data: NSDictionary, callback: ApiCallback) { subscriptions.remove(data["channel_id"] as! String) let json = JSON(data) callback.onSuccess(json) } }
mpl-2.0
f3e39ff0e5e4b0dcaf479ae92739b3d6
25.136364
95
0.684348
4.035088
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/SpeedTesting/ScatterSpeedTestSciChart.swift
1
2708
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // ScatterSpeedTestSciChart.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class ScatterSpeedTestSciChart: SingleChartLayout { let PointsCount: Int32 = 20000 var _timer: Timer! let _scatterDataSeries = SCIXyDataSeries(xType: .double, yType: .double) override func initExample() { let xAxis = SCINumericAxis() xAxis.autoRange = .always let yAxis = SCINumericAxis() yAxis.autoRange = .always let doubleSeries = BrownianMotionGenerator.getRandomData(withMin: -50, max: 50, count: PointsCount) _scatterDataSeries.acceptUnsortedData = true _scatterDataSeries.appendRangeX(doubleSeries!.xValues, y: doubleSeries!.yValues, count: doubleSeries!.size) let marker = SCICoreGraphicsPointMarker() marker.width = 6 marker.height = 6 let rSeries = SCIXyScatterRenderableSeries() rSeries.dataSeries = _scatterDataSeries rSeries.pointMarker = marker SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(rSeries) } _timer = Timer.scheduledTimer(timeInterval: 0.002, target: self, selector: #selector(updateData), userInfo: nil, repeats: true) } @objc fileprivate func updateData(_ timer: Timer) { for i in 0..<_scatterDataSeries.count() { let x = _scatterDataSeries.xValues().value(at: i) let y = _scatterDataSeries.yValues().value(at: i) _scatterDataSeries.update(at: i, x: SCIGeneric(SCIGenericDouble(x) + randf(-1.0, 1.0)), y: SCIGeneric(SCIGenericDouble(y) + randf(-0.5, 0.5))) } } override func willMove(toWindow newWindow: UIWindow?) { super.willMove(toWindow: newWindow) if (newWindow == nil) { _timer.invalidate() _timer = nil } } }
mit
33364763a455a256da7eceab1f1de736
38.779412
154
0.610721
4.584746
false
false
false
false
ibm-bluemix-mobile-services/bms-samples-ios-bluelist
bluelist-swift/bluelist-swift/PushViewController.swift
1
8706
// Copyright 2014, 2015 IBM Corp. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation class PushViewController: UITableViewController { var availableTags: [String] = [] var subscribedTags: [String] = [] let logger = IMFLogger(forName: "BlueList") let push = IMFPushClient.sharedInstance() let theSwitch = UISwitch() override func viewDidLoad() { super.viewDidLoad() getAvailableTags() theSwitch.addTarget(self, action: "notificationsSwitchChanged:", forControlEvents: UIControlEvents.ValueChanged) } @IBAction func performDone(sender: UIBarButtonItem) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: { () -> Void in }) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows return section == 0 ? 1 : availableTags.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell if indexPath.section == 0 { //define cell cell = tableView.dequeueReusableCellWithIdentifier("PushCell", forIndexPath: indexPath) cell.accessoryView = theSwitch //see if device is subscribed for all push notifications if isPushEnabled() { theSwitch.on = true } else { theSwitch.on = false } } else { //define cell cell = tableView.dequeueReusableCellWithIdentifier("TagCell", forIndexPath: indexPath) //add label to cell let subscriptionTag = self.availableTags[indexPath.row] cell.textLabel?.text = subscriptionTag cell.accessoryView?.hidden = false //show checkmark is subscribed if isTagSubscribed(subscriptionTag) { cell.accessoryType = UITableViewCellAccessoryType.Checkmark } else { cell.accessoryType = UITableViewCellAccessoryType.None } } return cell } //if the push notifications switch changed, this gets called func notificationsSwitchChanged(sender:UISwitch) { let application = UIApplication.sharedApplication() if (sender.on == true) { registerForPushNotification(application) } else { unregisterForPushNotifications(application) } } //on selection of subscription notifications override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section != 0 && theSwitch.on { tableView.deselectRowAtIndexPath(tableView.indexPathForSelectedRow!, animated: false) let cell = tableView.cellForRowAtIndexPath(indexPath) //toggle the checkmark, subscribe or unsubscribe from tags, set user defaults if (cell?.accessoryType == UITableViewCellAccessoryType.None) { subscribeTag(availableTags[indexPath.row]) cell?.accessoryType = UITableViewCellAccessoryType.Checkmark } else { unsubscribeTag(availableTags[indexPath.row]) cell?.accessoryType = UITableViewCellAccessoryType.None } } } func subscribeTag(theTag: String) { let tagArray = [theTag] push.subscribeToTags(tagArray, completionHandler: { (response: IMFResponse!, error: NSError!) -> Void in if error != nil { self.logger?.logErrorWithMessages("Error push subscribeToTags \(error.description)") } }) } func unsubscribeTag(theTag: String) { let tagArray = [theTag] push.unsubscribeFromTags(tagArray, completionHandler: { (response: IMFResponse!, error: NSError!) -> Void in if error != nil { self.logger?.logErrorWithMessages("Error in unsubscribing to tags \(error.description)") } }) } func getAvailableTags() { push.retrieveAvailableTagsWithCompletionHandler { (response: IMFResponse!, error: NSError!) -> Void in if error != nil { self.logger?.logErrorWithMessages("Error push retrieveAvailableTagsWithCompletionHandler \(error.description)") } else { self.availableTags = response.availableTags() as! [String] self.getSubscribedTags() } } } func getSubscribedTags() { push.retrieveSubscriptionsWithCompletionHandler { (response: IMFResponse!, error: NSError!) -> Void in if error != nil { self.logger?.logErrorWithMessages("Error push retrieveSubscriptionsWithCompletionHandler \(error.description)") } else { let subscriptions = response.subscriptions() self.subscribedTags = subscriptions["subscriptions"] as! [String] self.tableView?.reloadData() } } } func isTagSubscribed(tag: String) -> Bool { for subscribedTag in self.subscribedTags { if subscribedTag == tag { return true } } return false; } func isPushEnabled() -> Bool { return isTagSubscribed("Push.ALL") } func registerForPushNotification(application:UIApplication) { //Registering for remote Notifications must be done after User is Authenticated //setup push with interactive notifications let acceptAction = UIMutableUserNotificationAction() acceptAction.identifier = "ACCEPT_ACTION" acceptAction.title = "Accept" acceptAction.destructive = false acceptAction.authenticationRequired = false acceptAction.activationMode = UIUserNotificationActivationMode.Foreground let declineAction = UIMutableUserNotificationAction() declineAction.identifier = "DECLINE_ACTION" declineAction.title = "Decline" declineAction.destructive = true declineAction.authenticationRequired = false declineAction.activationMode = UIUserNotificationActivationMode.Background let pushCategory = UIMutableUserNotificationCategory() pushCategory.identifier = "TODO_CATEGORY" pushCategory.setActions([acceptAction, declineAction], forContext: UIUserNotificationActionContext.Default) let notificationTypes: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Alert, UIUserNotificationType.Sound] let notificationSettings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: Set(arrayLiteral: pushCategory)); application.registerUserNotificationSettings(notificationSettings) if UIDevice.currentDevice().model.hasSuffix("Simulator") { logger?.logInfoWithMessages("Running on Simulator skiping remote push notifications") } else { logger?.logInfoWithMessages("Running on Device registering for push notifications") application.registerForRemoteNotifications() } } func unregisterForPushNotifications(application: UIApplication) { //unregister the application for push notifications let push = IMFPushClient.sharedInstance() push.unregisterDevice { (response: IMFResponse!, error: NSError!) -> Void in if error != nil { self.logger?.logErrorWithMessages("Error during device unregistration \(error.description)") return } else { self.logger?.logInfoWithMessages("Succesfully Unregistered Device") application.unregisterForRemoteNotifications() self.getAvailableTags() } } } }
apache-2.0
921ee6ab7503dcb79faa0b96b8d7781e
41.891626
172
0.648978
5.792415
false
false
false
false
Pacific3/PNetworkKit
PNetworkKit/Extensions/UIUserNotificationSettings.swift
1
1204
extension UIUserNotificationSettings { public func contains(settings: UIUserNotificationSettings) -> Bool { if !types.contains(settings.types) { return false } let otherCategories = settings.categories ?? [] let myCategories = categories ?? [] return myCategories.isSupersetOf(otherCategories) } public func settingsByMerging(settings: UIUserNotificationSettings) -> UIUserNotificationSettings { let mergedTypes = types.union(settings.types) let myCategories = categories ?? [] var existingCategoriesByIdentifiers = Dictionary(sequence: myCategories) { $0.identifier } let newCategories = settings.categories ?? [] let newCategoriesByIdentifiers = Dictionary(sequence: newCategories) { $0.identifier } for (newIdentifier, newCategory) in newCategoriesByIdentifiers { existingCategoriesByIdentifiers[newIdentifier] = newCategory } let mergedCategories = Set(existingCategoriesByIdentifiers.values) return UIUserNotificationSettings(forTypes: mergedTypes, categories: mergedCategories) } }
mit
5486d9cab4d455775a191b08e29ba994
37.870968
103
0.673588
6.111675
false
false
false
false
blinker13/Geometry
Sources/Primitives/Size.swift
1
916
public struct Size : Codable, Geometry { public var storage: SIMD2<Scalar> } // MARK: - public extension Size { @inlinable var width: Scalar { get { storage.x } set { storage.x = newValue } } @inlinable var height: Scalar { get { storage.y } set { storage.y = newValue } } @inlinable var isEmpty: Bool { width == .zero || height == .zero } @inlinable init(_ value: SIMD2<Scalar>) { storage = value } @inlinable init(width: Scalar, height: Scalar) { storage = .init(width, height) } @inlinable init(sides: Scalar) { storage = .init(repeating: sides) } @inlinable func inseted(by space: Space) -> Self { .init(storage - space.storage.highHalf - space.storage.lowHalf) } @inlinable func applying(_ transform: Transform) -> Self { let w = transform.a * width + transform.c * height let h = transform.b * width + transform.d * height return .init(width: w, height: h) } }
mit
07ed4d84712928173cb4d65d1fb9059d
20.302326
67
0.655022
3.105085
false
false
false
false
yl-github/YLDYZB
YLDouYuZB/YLDouYuZB/Classes/Tools/YLNetWorkTools.swift
1
1003
// // YLNetWorkTools.swift // YLDouYuZB // // Created by yl on 16/10/10. // Copyright © 2016年 yl. All rights reserved. // // --------- 封装Alamofire网络请求 ------------ import UIKit import Alamofire enum MethodType { case get case post } class YLNetWorkTools { class func requestData(_ type : MethodType, URLString : String, parameters : [String : NSString]? = nil, finishedCallback : @escaping (_ request : Any) -> ()){ // 1.获取类型 let methods = type == .get ? HTTPMethod.get : HTTPMethod.post; // 2.发送网络请求 Alamofire.request(URLString, method: methods, parameters: parameters).responseJSON { (response) in // 3.获取结果 guard let result = response.result.value else{ print(response.result.error); return; } // 4.将结果回调出去 finishedCallback(result); } } }
mit
197bd4850a0c2bf64b81ec6796efb248
25.277778
163
0.546512
4.33945
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/StudyNote/StudyNote/SHRoute/Base/SNRouteParamsSchemeAnalysisService.swift
1
1705
// // SNRouteParamsSchemeAnalysisService.swift // StudyNote // // Created by wuyp on 2020/3/16. // Copyright © 2020 Raymond. All rights reserved. // import UIKit class SNRouteParamsSchemeAnalysisService: NSObject { @objc private dynamic var routeParamKey = "" // MARK: - Constructor init(keyName: String) { super.init() self.routeParamKey = keyName } } // MARK: - SNRouteAnalysisRouteServiceProtocol extension SNRouteParamsSchemeAnalysisService: SNRouteAnalysisRouteServiceProtocol { func getRouteResult(url: URL) -> Result<SNRouteEntity, SNRouteError> { return .success(getRouteEntity(url: url)) } } // MARK: - Private Method extension SNRouteParamsSchemeAnalysisService { @objc private dynamic func getRouteEntity(url: URL) -> SNRouteEntity { let entity = SNRouteEntity() entity.href = url.absoluteString let paramsArr = url.query?.componentsSeparatedByString("&") ?? [] for item in paramsArr { let temp = item.componentsSeparatedByString("=") if temp.count == 2 { entity.params[temp[0]] = temp[1] } } entity.module = "" entity.page = ((entity.params[routeParamKey] as? String) ?? "").uppercased() entity.params.removeValue(forKey: routeParamKey) return entity } @objc private dynamic func deleteRedundancyInfo(href: String) -> String { var result = "" // # if let endIndex = href.index(of: "#") { let start = href.startIndex result = String(href[start..<endIndex]) } return result } }
apache-2.0
9d1275d2352e051737e3bb6d30113d91
26.934426
84
0.612089
4.425974
false
false
false
false
nodes-ios/NStackSDK
NStackSDK/NStackSDK/Classes/Other/UITextView+NStackLocalizable.swift
1
2293
// // UITextView+NStackLocalizable.swift // NStackSDK // // Created by Nicolai Harbo on 30/07/2019. // Copyright © 2019 Nodes ApS. All rights reserved. // import Foundation import UIKit extension UITextView: NStackLocalizable { private static var _backgroundColor = [String: UIColor?]() private static var _userInteractionEnabled = [String: Bool]() private static var _translationIdentifier = [String: TranslationIdentifier]() @objc public func localize(for stringIdentifier: String) { guard let identifier = SectionKeyHelper.transform(stringIdentifier) else { return } NStack.sharedInstance.translationsManager?.localize(component: self, for: identifier) } @objc public func setLocalizedValue(_ localizedValue: String) { text = localizedValue } public var translatableValue: String? { get { return text } set { text = newValue } } public var translationIdentifier: TranslationIdentifier? { get { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) return UITextView._translationIdentifier[tmpAddress] } set { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) UITextView._translationIdentifier[tmpAddress] = newValue } } public var originalBackgroundColor: UIColor? { get { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) return UITextView._backgroundColor[tmpAddress] ?? .clear } set { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) UITextView._backgroundColor[tmpAddress] = newValue } } public var originalIsUserInteractionEnabled: Bool { get { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) return UITextView._userInteractionEnabled[tmpAddress] ?? false } set { let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self)) UITextView._userInteractionEnabled[tmpAddress] = newValue } } public var backgroundViewToColor: UIView? { return self } }
mit
555a61785fc996333979a9134f08cc44
30.39726
93
0.63089
4.907923
false
false
false
false
STShenZhaoliang/Swift2Guide
Swift2Guide/Swift100Tips/Swift100Tips/EqualController.swift
1
670
// // EqualController.swift // Swift100Tips // // Created by 沈兆良 on 16/5/30. // Copyright © 2016年 ST. All rights reserved. // import UIKit class EqualController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } class TodoItem { let uuid: String var title: String init(uuid: String, title: String) { self.uuid = uuid self.title = title } } extension TodoItem: Equatable { } func ==(lhs: TodoItem, rhs: TodoItem) -> Bool { return lhs.uuid == rhs.uuid } /* func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool 它用来判断两个 AnyObject 是否是同一个引用。 */
mit
ffb3d4808b5035057605f655dfa6cbed
14.365854
51
0.624801
3.475138
false
false
false
false
peymanmortazavi/Hangout
Frontend2/Frontend2/HangoutAPIClient.swift
1
1282
// // HangoutClient.swift // Hangout // // Created by Vahid Mazdeh on 11/7/14. // Copyright (c) 2014 Peyman Mortazavi. All rights reserved. // import Foundation public class HangoutClient { public class var ApiUrl: String{ get{ return "http://chil.cloudapp.net/" } } /*init(apiUrl: String) { //ApiUrl = apiUrl }*/ /*func testGet () -> String { let urlPath: String = ApiUrl + "accounts/test" var url: NSURL = NSURL(string: urlPath)! var request1: NSURLRequest = NSURLRequest(URL: url) var response: AutoreleasingUnsafeMutablePointer <NSURLResponse? >=nil var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil var dataVal: NSData? = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:error) if let data = dataVal { var err: NSError? = nil var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary println("Synchronous\(jsonResult)") return jsonResult["firstName"] as NSString; } return "Failed to acquire server data"; }*/ }
mit
0b195ee01fc95a303be7291a688fcb6c
30.292683
165
0.628705
4.661818
false
false
false
false
qvacua/vimr
NvimView/Sources/NvimView/NvimView+TouchBar.swift
1
4682
/** * Greg Omelaenko - http://omelaen.co * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import RxPack import RxSwift import RxNeovim extension NvimView: NSTouchBarDelegate, NSScrubberDataSource, NSScrubberDelegate { override public func makeTouchBar() -> NSTouchBar? { let bar = NSTouchBar() bar.delegate = self bar.customizationIdentifier = touchBarIdentifier bar.defaultItemIdentifiers = [touchBarTabSwitcherIdentifier] bar.customizationRequiredItemIdentifiers = [touchBarTabSwitcherIdentifier] return bar } public func touchBar( _: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier ) -> NSTouchBarItem? { switch identifier { case touchBarTabSwitcherIdentifier: let item = NSCustomTouchBarItem(identifier: identifier) item.customizationLabel = "Tab Switcher" let tabsControl = NSScrubber() tabsControl.register( NSScrubberTextItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(touchBarTabSwitcherItem) ) tabsControl.mode = .fixed tabsControl.dataSource = self tabsControl.delegate = self tabsControl.selectionOverlayStyle = .outlineOverlay tabsControl.selectedIndex = self.selectedTabIndex() let layout = NSScrubberProportionalLayout() layout.numberOfVisibleItems = 1 tabsControl.scrubberLayout = layout item.view = tabsControl return item default: return nil } } private func selectedTabIndex() -> Int { tabsCache.firstIndex { $0.isCurrent } ?? -1 } private func getTabsControl() -> NSScrubber? { let item = self .touchBar? .item(forIdentifier: touchBarTabSwitcherIdentifier) as? NSCustomTouchBarItem return item?.view as? NSScrubber } func updateTouchBarCurrentBuffer() { self .allTabs() .observe(on: MainScheduler.instance) .subscribe(onSuccess: { [weak self] in self?.tabsCache = $0 guard let tabsControl = self?.getTabsControl() else { return } tabsControl.reloadData() let scrubberProportionalLayout = tabsControl.scrubberLayout as! NSScrubberProportionalLayout scrubberProportionalLayout.numberOfVisibleItems = tabsControl .numberOfItems > 0 ? tabsControl.numberOfItems : 1 tabsControl.selectedIndex = self?.selectedTabIndex() ?? tabsControl.selectedIndex }, onFailure: { [weak self] error in self?.eventsSubject.onNext(.apiError(msg: "Could not get all tabpages.", cause: error)) }) .disposed(by: self.disposeBag) } func updateTouchBarTab() { self .allTabs() .observe(on: MainScheduler.instance) .subscribe(onSuccess: { [weak self] in self?.tabsCache = $0 guard let tabsControl = self?.getTabsControl() else { return } tabsControl.reloadData() tabsControl.selectedIndex = self?.selectedTabIndex() ?? tabsControl.selectedIndex }, onFailure: { error in self.eventsSubject.onNext(.apiError(msg: "Could not get all tabpages.", cause: error)) }) .disposed(by: self.disposeBag) } public func numberOfItems(for _: NSScrubber) -> Int { tabsCache.count } public func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView { let item = scrubber.makeItem( withIdentifier: NSUserInterfaceItemIdentifier(touchBarTabSwitcherItem), owner: nil ) guard let itemView = item as? NSScrubberTextItemView else { return NSScrubberTextItemView() } guard tabsCache.count > index else { return itemView } let tab = self.tabsCache[index] itemView.title = tab.currentWindow?.buffer.name ?? "[No Name]" return itemView } public func scrubber(_: NSScrubber, didSelectItemAt selectedIndex: Int) { let tab = self.tabsCache[selectedIndex] guard tab.windows.count > 0 else { return } let window = tab.currentWindow ?? tab.windows[0] self.api .setCurrentWin(window: RxNeovimApi.Window(window.handle)) .subscribe(on: self.scheduler) .subscribe(onError: { [weak self] error in self?.eventsSubject .onNext(.apiError(msg: "Could not set current window to \(window.handle).", cause: error)) }) .disposed(by: self.disposeBag) } } private let touchBarIdentifier = NSTouchBar .CustomizationIdentifier("com.qvacua.VimR.NvimView.touchBar") private let touchBarTabSwitcherIdentifier = NSTouchBarItem .Identifier("com.qvacua.VimR.NvimView.touchBar.tabSwitcher") private let touchBarTabSwitcherItem = "com.qvacua.VimR.NvimView.touchBar.tabSwitcher.item"
mit
6e40ba4dd78f3543e07c6310d5b5745f
32.442857
100
0.696924
4.581213
false
false
false
false
apple/swift
test/IRGen/ptrauth-global.swift
5
1960
// RUN: %swift-frontend -swift-version 4 -target arm64e-apple-ios12.0 -primary-file %s -emit-ir -module-name A | %FileCheck %s --check-prefix=CHECK // RUN: %swift-frontend -swift-version 4 -target arm64e-apple-ios12.0 %s -primary-file %S/Inputs/ptrauth-global-2.swift -emit-ir -module-name A | %FileCheck %s --check-prefix=CHECK2 // REQUIRES: CPU=arm64e // REQUIRES: OS=ios // Make sure that the key at the definition of the global matches call sites. // CHECK-DAG: @"$s1A9ContainerV3AllAA1GVySiGycAA1VVySiGcycvpZ" = global %swift.function { {{.*}} @"$s1A9ContainerV3AllAA1GVySiGycAA1VVySiGcycvpZfiAGycAJcycfU_.ptrauth" // CHECK-DAG: @"$s1A9ContainerV3AllAA1GVySiGycAA1VVySiGcycvpZfiAGycAJcycfU_.ptrauth" = {{.*}} @"$s1A9ContainerV3AllAA1GVySiGycAA1VVySiGcycvpZfiAGycAJcycfU_" {{.*}} i64 58141 }, section "llvm.ptrauth" // CHECK2: define {{.*}}swiftcc void @"$s1A4testyyF"() // CHECK2: [[T:%.*]] = call swiftcc i8* @"$s1A9ContainerV3AllAA1GVySiGycAA1VVySiGcycvau"() // CHECK2: [[T2:%.*]] = bitcast i8* [[T]] to %swift.function* // CHECK2: [[T3:%.*]] = getelementptr inbounds %swift.function, %swift.function* [[T2]], i32 0, i32 0 // CHECK2: [[T4:%.*]] = load i8*, i8** [[T3]] // CHECK2: [[T5:%.*]] = bitcast i8* [[T4]] to { i8*, %swift.refcounted* } (%swift.refcounted*)* // CHECK2: call swiftcc { i8*, %swift.refcounted* } [[T5]]({{.*}}) [ "ptrauth"(i32 0, i64 58141) ] public struct G<T> { init(_ t: T) {} } public struct V<T> { var str: String = "" var str1: String = "" var str2: String = "" var str3: String = "" var str4: String = "" var str5: String = "" var str6: String = "" var str7: String = "" var str8: String = "" init(_ t: T) {} } // Because of the large parameter type the signature gets transformed by the // large loadable pass. The types in the global initializer need to follow. public struct Container { public static let All = { return { (_ v: V<Int>) in { return G(5) } } } }
apache-2.0
271e17e0419615675cb2f660981f87df
44.581395
199
0.653061
2.929746
false
false
false
false
jairoeli/Habit
Zero/Sources/Networking/Networking.swift
1
2252
// // Networking.swift // Zero // // Created by Jairo Eli de Leon on 7/3/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import Moya import MoyaSugar import RxSwift final class Networking<Target: SugarTargetType>: MoyaSugarProvider<Target> { init(plugins: [PluginType] = []) { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = Manager.defaultHTTPHeaders configuration.timeoutIntervalForRequest = 10 let manager = Manager(configuration: configuration) manager.startRequestsImmediately = false super.init(manager: manager, plugins: plugins) } func request(_ target: Target, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) -> Single<Response> { let requestString = "\(target.method) \(target.path)" return self.rx.request(target) .filterSuccessfulStatusCodes() .do( onNext: { value in let message = "SUCCESS: \(requestString) (\(value.statusCode))" log.debug(message, file: file, function: function, line: line) }, onError: { error in if let response = (error as? MoyaError)?.response { if let jsonObject = try? response.mapJSON(failsOnEmptyData: false) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(jsonObject)" log.warning(message, file: file, function: function, line: line) } else if let rawString = String(data: response.data, encoding: .utf8) { let message = "FAILURE: \(requestString) (\(response.statusCode))\n\(rawString)" log.warning(message, file: file, function: function, line: line) } else { let message = "FAILURE: \(requestString) (\(response.statusCode))" log.warning(message, file: file, function: function, line: line) } } else { let message = "FAILURE: \(requestString)\n\(error)" log.warning(message, file: file, function: function, line: line) } }, onSubscribed: { let message = "REQUEST: \(requestString)" log.debug(message, file: file, function: function, line: line) } ) } }
mit
9c453b9f373e42f3c62febab469d2ecc
38.473684
138
0.631556
4.44664
false
true
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Colormap renderer/ColormapRendererViewController.swift
1
2398
// // Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class ColormapRendererViewController: UIViewController { @IBOutlet var mapView: AGSMapView! { didSet { // Assign map to the map view. mapView.map = AGSMap(basemapStyle: .arcGISImageryStandard) // Create and add the raster layer to the operational layers of the map. mapView.map?.operationalLayers.add(makeRasterLayer()) } } private func makeRasterLayer() -> AGSRasterLayer { let raster = AGSRaster(name: "ShastaBW", extension: "tif") // Create raster layer using raster. let rasterLayer = AGSRasterLayer(raster: raster) // Make two arrays to represent two different colors then appened them together. let colors = Array(repeating: UIColor.red, count: 150) + Array(repeating: UIColor.yellow, count: 151) // Render the colormap using the array of colors. let colormapRenderer = AGSColormapRenderer(colors: colors) rasterLayer.renderer = colormapRenderer // Set map view's viewpoint to the raster layer's full extent. rasterLayer.load { [weak self] (error) in if let error = error { self?.presentAlert(error: error) } else { if let center = rasterLayer.fullExtent?.center { self?.mapView.setViewpoint(AGSViewpoint(center: center, scale: 80000)) } } } return rasterLayer } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ColormapRendererViewController"] } }
apache-2.0
2555c4df6e887ab75a2eec65f8682e3d
37.677419
123
0.646372
4.638298
false
false
false
false
BluechipSystems/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Libraries/Swifter/Swifter/SwifterAppOnlyClient.swift
4
4105
// // SwifterAppOnlyClient.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation internal class SwifterAppOnlyClient: SwifterClientProtocol { var consumerKey: String var consumerSecret: String var credential: SwifterCredential? var dataEncoding: NSStringEncoding init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.dataEncoding = NSUTF8StringEncoding } func get(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let url = NSURL(string: path, relativeToURL: baseURL) let method = "GET" let request = SwifterHTTPRequest(URL: url!, method: method, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } request.start() } func post(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let url = NSURL(string: path, relativeToURL: baseURL) let method = "POST" let request = SwifterHTTPRequest(URL: url!, method: method, parameters: parameters) request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding if let bearerToken = self.credential?.accessToken?.key { request.headers = ["Authorization": "Bearer \(bearerToken)"]; } else { let basicCredentials = SwifterAppOnlyClient.base64EncodedCredentialsWithKey(self.consumerKey, secret: self.consumerSecret) request.headers = ["Authorization": "Basic \(basicCredentials)"]; request.encodeParameters = true } request.start() } class func base64EncodedCredentialsWithKey(key: String, secret: String) -> String { let encodedKey = key.urlEncodedStringWithEncoding(NSUTF8StringEncoding) let encodedSecret = secret.urlEncodedStringWithEncoding(NSUTF8StringEncoding) let bearerTokenCredentials = "\(encodedKey):\(encodedSecret)" if let data = bearerTokenCredentials.dataUsingEncoding(NSUTF8StringEncoding) { return data.base64EncodedStringWithOptions(nil) } return String() } }
mit
58b2f6c36a52572991cab282d055878f
43.619565
300
0.723752
5.209391
false
false
false
false
CoderJason1992/iOS-9-Sampler
iOS9Sampler/RootViewController.swift
9
6504
// // RootViewController.swift // iOS9Sampler // // Created by Shuichi Tsutsumi on 2015/06/10. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import UIKit let kItemKeyTitle = "title" let kItemKeyDetail = "detail" let kItemKeyClassPrefix = "prefix" class RootViewController: UITableViewController { var items: [Dictionary<String, String>]! override func viewDidLoad() { super.viewDidLoad() items = [ [ kItemKeyTitle: "Map Customizations", kItemKeyDetail: "Flyover can be selected with new map types, and Traffic, Scale and Compass can be shown.", kItemKeyClassPrefix: "MapCustomizations" ], [ kItemKeyTitle: "Text Detector", kItemKeyDetail: "Text detection using new detector type \"CIDetectorTypeText\".", kItemKeyClassPrefix: "TextDetect" ], [ kItemKeyTitle: "New Image Filters", kItemKeyDetail: "New filters of CIFilter which can be used for Still Images.", kItemKeyClassPrefix: "StillImageFilters", ], [ kItemKeyTitle: "Audio Unit Component Manager", kItemKeyDetail: "Retrieve available audio units using AudioUnitComponentManager and apply them to a sound. If there are some Audio Unit Extensions, they will be also shown.", kItemKeyClassPrefix: "AudioUnitComponentManager", ], [ kItemKeyTitle: "Speech Voices", kItemKeyDetail: "Example for new properties which are added to AVSpeechSynthesisVoice such as language, name, quality...", kItemKeyClassPrefix: "Speech", ], [ kItemKeyTitle: "CASpringAnimation", kItemKeyDetail: "Animation example using CASpringAnimation.", kItemKeyClassPrefix: "Spring" ], [ kItemKeyTitle: "UIStackView", kItemKeyDetail: "Auto Layout example using UIStackView.", kItemKeyClassPrefix: "StackView" ], [ kItemKeyTitle: "Selfies & Screenshots", kItemKeyDetail: "Fetch photos filtered with new subtypes \"SelfPortraits\" and \"Screenshot\" which are added to Photos framework.", kItemKeyClassPrefix: "Photos" ], [ kItemKeyTitle: "String Transform", kItemKeyDetail: "String transliteration examples using new APIs of Foundation framework.", kItemKeyClassPrefix: "StringTransform" ], [ kItemKeyTitle: "Search APIs", kItemKeyDetail: "Example for Search APIs using NSUserActivity and Core Spotlight.", kItemKeyClassPrefix: "SearchAPIs" ], [ kItemKeyTitle: "Content Blockers", kItemKeyDetail: "Example for Content Blocker Extension.", kItemKeyClassPrefix: "ContentBlocker" ], [ kItemKeyTitle: "SFSafariViewController", kItemKeyDetail: "Open web pages with SFSafariViewController.", kItemKeyClassPrefix: "Safari" ], [ kItemKeyTitle: "Attributes of New Filters", kItemKeyDetail: "Extract new filters of CIFilter using \"kCIAttributeFilterAvailable_iOS\".", kItemKeyClassPrefix: "Filters" ], [ kItemKeyTitle: "Low Power Mode", kItemKeyDetail: "Detect changes of \"Low Power Mode\" setting.", kItemKeyClassPrefix: "LowPowerMode" ], [ kItemKeyTitle: "New Fonts", kItemKeyDetail: "Gallery of new fonts.", kItemKeyClassPrefix: "Fonts" ], [ kItemKeyTitle: "Contacts", kItemKeyDetail: "Contacts framework sample.", kItemKeyClassPrefix: "Contacts" ], [ kItemKeyTitle: "Quick Actions", kItemKeyDetail: "Access the shortcut menu on the Home screen using 3D Touch.", kItemKeyClassPrefix: "QuickActions" ], [ kItemKeyTitle: "Force Touch", kItemKeyDetail: "Visualize the forces of touches using new properties of UITouch.", kItemKeyClassPrefix: "ForceTouch" ], ] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // ========================================================================= // MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! RootViewCell let item = items[indexPath.row] cell.titleLabel!.text = item[kItemKeyTitle] cell.detailLabel!.text = item[kItemKeyDetail] return cell } // ========================================================================= // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = items[indexPath.row] let prefix = item[kItemKeyClassPrefix] let storyboard = UIStoryboard(name: prefix!, bundle: nil) let controller = storyboard.instantiateInitialViewController() self.navigationController?.pushViewController(controller!, animated: true) controller!.title = item[kItemKeyTitle] tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
fcb16d13ca4037dcb4830decfc2ba656
37.252941
190
0.570352
5.927985
false
false
false
false
zitao0322/ShopCar
Shoping_Car/Shoping_Car/Class/ShopingCar/View/ZTShopCarPushView.swift
1
3253
// // ZTShopCarPushView.swift // Shoping_Car // // Created by venusource on 16/8/18. // Copyright © 2016年 venusource.com. All rights reserved. // import UIKit let kPushViewH: CGFloat = 44 class ZTShopCarPushView: UIView { var isEdit: Bool?{ didSet{ allPriceLab.hidden = isEdit! allSeleButton.selected = !isEdit! let title = isEdit! ? "删除" : "结算" pushButton.setTitle(title, forState: .Normal) } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ addSubview(lineView) addSubview(allSeleButton) addSubview(allPriceLab) addSubview(pushButton) } private lazy var lineView: UIView = { let view = UIView() view.backgroundColor = UIColor.colorWithString("#e2e2e2") return view }() lazy var allSeleButton: UIButton = { let button = UIButton() button.selected = true button.titleLabel?.font = kFont_14 button.setTitleColor(UIColor.colorWithString("#666666"), forState: .Normal) button.setTitle("全选", forState: .Normal) button.setTitle("取消全选", forState: .Selected) button.setImage(UIImage(named:"Unselected"), forState: .Normal) button.setImage(UIImage(named:"Selected"), forState: .Selected) return button }() lazy var allPriceLab: UILabel = { let label = UILabel() label.font = kFont_15 label.textColor = UIColor.colorWithString("#666666") label.text = "合计: ¥ 0" return label }() lazy var pushButton: UIButton = { let button = UIButton() button.hidden = false button.backgroundColor = UIColor.colorWithString("fb5d5d") button.titleLabel?.font = kFont_14 button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.setTitle("结算", forState: .Normal) button.layer.cornerRadius = 3 return button }() override func layoutSubviews() { super.layoutSubviews() lineView.ff_AlignInner(type: .TopLeft, referView: self, size: CGSizeMake(kSCREENW, 0.5)) allSeleButton.ff_AlignInner(type: .CenterLeft, referView: self, size: CGSizeMake(84, 24), offset: CGPointMake(5, 0)) allPriceLab.ff_AlignHorizontal(type: .CenterRight, referView: allSeleButton, size: CGSizeMake(150, height), offset: CGPointMake(10, 0)) pushButton.ff_AlignInner(type: .CenterRight, referView: self, size: CGSizeMake(80, 30), offset: CGPointMake(-15, 0)) } }
mit
a87de8eaef859f3a0deea202de7356b6
27.495575
83
0.53882
4.791667
false
false
false
false
Ataluer/ASRoam
ASRoam/ASRoam/Class/Profile/Controller/VLCollect/BMPlayerCustomControlView.swift
1
4471
// // BMPlayerCustomControlView.swift // ASRoam // // Created by Yanfei Yu on 2017/6/24. // Copyright © 2017年 Ataluer. All rights reserved. // import UIKit import BMPlayer class BMPlayerCustomControlView: BMPlayerControlView { var playbackRateButton = UIButton(type: .custom) var playRate: Float = 1.0 var rotateButton = UIButton(type: .custom) var rotateCount: CGFloat = 0 /** Override if need to customize UI components */ override func customizeUIComponents() { mainMaskView.backgroundColor = UIColor.clear topMaskView.backgroundColor = UIColor.black.withAlphaComponent(0.4) bottomMaskView.backgroundColor = UIColor.black.withAlphaComponent(0.4) timeSlider.setThumbImage(UIImage(named: "custom_slider_thumb"), for: .normal) topMaskView.addSubview(playbackRateButton) playbackRateButton.layer.cornerRadius = 2 playbackRateButton.layer.borderWidth = 1 playbackRateButton.layer.borderColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.8 ).cgColor playbackRateButton.setTitleColor(UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.9 ), for: .normal) playbackRateButton.setTitle(" rate \(playRate) ", for: .normal) playbackRateButton.addTarget(self, action: #selector(onPlaybackRateButtonPressed), for: .touchUpInside) playbackRateButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) playbackRateButton.isHidden = true playbackRateButton.snp.makeConstraints { $0.right.equalTo(chooseDefitionView.snp.left).offset(-5) $0.centerY.equalTo(chooseDefitionView) } topMaskView.addSubview(rotateButton) rotateButton.layer.cornerRadius = 2 rotateButton.layer.borderWidth = 1 rotateButton.layer.borderColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.8 ).cgColor rotateButton.setTitleColor(UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.9 ), for: .normal) rotateButton.setTitle(" rotate ", for: .normal) rotateButton.addTarget(self, action: #selector(onRotateButtonPressed), for: .touchUpInside) rotateButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) rotateButton.isHidden = true rotateButton.snp.makeConstraints { $0.right.equalTo(playbackRateButton.snp.left).offset(-5) $0.centerY.equalTo(chooseDefitionView) } } override func updateUI(_ isForFullScreen: Bool) { super.updateUI(isForFullScreen) playbackRateButton.isHidden = !isForFullScreen rotateButton.isHidden = !isForFullScreen if let layer = player?.playerLayer { layer.frame = player!.bounds } } override func controlViewAnimation(isShow: Bool) { self.isMaskShowing = isShow UIApplication.shared.setStatusBarHidden(!isShow, with: .fade) UIView.animate(withDuration: 0.24, animations: { self.topMaskView.snp.remakeConstraints { $0.top.equalTo(self.mainMaskView).offset(isShow ? 0 : -65) $0.left.right.equalTo(self.mainMaskView) $0.height.equalTo(65) } self.bottomMaskView.snp.remakeConstraints { $0.bottom.equalTo(self.mainMaskView).offset(isShow ? 0 : 50) $0.left.right.equalTo(self.mainMaskView) $0.height.equalTo(50) } self.layoutIfNeeded() }) { (_) in self.autoFadeOutControlViewWithAnimation() } } @objc func onPlaybackRateButtonPressed() { autoFadeOutControlViewWithAnimation() switch playRate { case 1.0: playRate = 1.5 case 1.5: playRate = 0.5 case 0.5: playRate = 1.0 default: playRate = 1.0 } playbackRateButton.setTitle(" rate \(playRate) ", for: .normal) delegate?.controlView?(controlView: self, didChangeVideoPlaybackRate: playRate) } @objc func onRotateButtonPressed() { guard let layer = player?.playerLayer else { return } print("rotated") rotateCount += 1 layer.transform = CGAffineTransform(rotationAngle: rotateCount * CGFloat(Double.pi/2)) layer.frame = player!.bounds } }
mit
3056ca7506952860b38cc816901adcb5
36.233333
111
0.625783
4.333657
false
false
false
false
lorentey/swift
test/SILOptimizer/devirt_specialized_inherited_interplay.swift
36
4031
// RUN: %target-swift-frontend -sil-verify-all -Xllvm -sil-inline-generics -O %s -emit-sil | %FileCheck %s // This file consists of tests for making sure that protocol conformances and // inherited conformances work well together when applied to each other. The // check works by making sure we can blow through a long class hierarchy and // expose the various "unknown" functions. // // As a side-test it also checks if all allocs can be promoted to the stack. // // *NOTE* If something like templated protocols is ever implemented this file // needs to be updated. // CHECK-LABEL: sil @$s38devirt_specialized_inherited_interplay6driveryyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK-NOT: alloc_ref // CHECK: [[F0:%[0-9]+]] = function_ref @unknown0 : $@convention(thin) () -> () // CHECK: apply [[F0]] // CHECK: apply [[F0]] // CHECK: [[F1:%[0-9]+]] = function_ref @unknown1 : $@convention(thin) () -> () // CHECK: apply [[F1]] // CHECK: apply [[F1]] // CHECK: [[F2:%[0-9]+]] = function_ref @unknown2 : $@convention(thin) () -> () // CHECK: apply [[F2]] // CHECK: apply [[F2]] // CHECK: [[F3:%[0-9]+]] = function_ref @unknown3 : $@convention(thin) () -> () // CHECK: apply [[F3]] // CHECK: apply [[F3]] // CHECK: [[F4:%[0-9]+]] = function_ref @unknown4 : $@convention(thin) () -> () // CHECK: apply [[F4]] // CHECK: apply [[F4]] // CHECK: [[F5:%[0-9]+]] = function_ref @unknown5 : $@convention(thin) () -> () // CHECK: apply [[F5]] // CHECK: apply [[F5]] // CHECK: [[F6:%[0-9]+]] = function_ref @unknown6 : $@convention(thin) () -> () // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: apply [[F6]] // CHECK: [[F8:%[0-9]+]] = function_ref @unknown8 : // CHECK: apply [[F8]] // CHECK: apply [[F8]] // CHECK-NOT: dealloc_ref // CHECK: return @_silgen_name("unknown0") func unknown0() -> () @_silgen_name("unknown1") func unknown1() -> () @_silgen_name("unknown2") func unknown2() -> () @_silgen_name("unknown3") func unknown3() -> () @_silgen_name("unknown4") func unknown4() -> () @_silgen_name("unknown5") func unknown5() -> () @_silgen_name("unknown6") func unknown6() -> () @_silgen_name("unknown7") func unknown7() -> () @_silgen_name("unknown8") func unknown8() -> () protocol P1 { func foo() } struct S:P1 { func foo() { } } public final class G1<T> { } protocol P { func doSomething() } // Normal conformance class A1 : P { func doSomething() { unknown0() } } // Inherited conformance from P class A2 : A1 { override func doSomething() { unknown1() } } // Specialized Inherited conformance from P class A3<T> : A2 { override func doSomething() { unknown2() } } // Inherited Specialized Inherited conformance from P class A4<T> : A3<T> { override func doSomething() { unknown3() } } class A5<E>: A3<Array<E>> { override func doSomething() { unknown4() } } // Specialized conformance from P class B1<T> : P { func doSomething() { unknown5() } } // Inherited Specialized conformance from P class B2<T> : B1<G1<T>> { override func doSomething() { unknown6() } } class B3<E>: B2<Array<E>> { } class B4<F>: B3<Array<Array<Int>>> { override func doSomething() { unknown8() } } func WhatShouldIDo<T : P>(_ t : T) { t.doSomething() } func WhatShouldIDo2(_ p : P) { p.doSomething() } public func driver1<X>(_ x:X) { let b = B3<X>() WhatShouldIDo(b) WhatShouldIDo2(b) } public func driver2() { driver1(G1<S>()) } public func driver() { let a1 = A1() let a2 = A2() let a3 = A3<S>() let a4 = A4<S>() let a5 = A5<S>() let b1 = B1<S>() let b2 = B2<S>() let b3 = B3<S>() let b4 = B4<S>() WhatShouldIDo(a1) WhatShouldIDo2(a1) WhatShouldIDo(a2) WhatShouldIDo2(a2) WhatShouldIDo(a3) WhatShouldIDo2(a3) WhatShouldIDo(a4) WhatShouldIDo2(a4) WhatShouldIDo(a5) WhatShouldIDo2(a5) WhatShouldIDo(b1) WhatShouldIDo2(b1) WhatShouldIDo(b2) WhatShouldIDo2(b2) WhatShouldIDo(b3) WhatShouldIDo2(b3) WhatShouldIDo(b4) WhatShouldIDo2(b4) }
apache-2.0
db2b86517c5e8e0b0f41478a4fb90a25
19.778351
106
0.616472
2.927378
false
false
false
false
SeaHub/ImgTagging
ImgTagger/ImgTagger/UserInfo.swift
1
1009
// // UserInfo.swift // ImgTagger // // Created by SeaHub on 2017/6/25. // Copyright © 2017年 SeaCluster. All rights reserved. // import UIKit import SwiftyJSON struct UserInfoJSONParsingKeys { static let kScoreKey = "score" static let kFinishedNumKey = "finish_num" static let kAvatarURLKey = "avatar" static let kUserIDKey = "userId" static let kNameKey = "name" } class UserInfo: NSObject { let score: Int! let userID: Int! let finishNum: Int! var avatarURL: String? = nil var name: String? = nil init(JSON: Dictionary<String, JSON>) { self.score = JSON[UserInfoJSONParsingKeys.kScoreKey]!.int! self.finishNum = JSON[UserInfoJSONParsingKeys.kFinishedNumKey]!.int! self.avatarURL = JSON[UserInfoJSONParsingKeys.kAvatarURLKey]!.string self.userID = JSON[UserInfoJSONParsingKeys.kUserIDKey]!.int! self.name = JSON[UserInfoJSONParsingKeys.kNameKey]!.string } }
gpl-3.0
5b55840366f2e579e7d0bae09353722e
28.588235
76
0.657058
3.725926
false
false
false
false
J-Mendes/Bliss-Assignement
Bliss-Assignement/Bliss-Assignement/QuestionsViewController.swift
1
10048
// // QuestionsViewController.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import UIKit class QuestionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { @IBOutlet private weak var searchBar: UISearchBar! @IBOutlet weak var searchBarTopConstraint: NSLayoutConstraint! @IBOutlet private weak var tableView: UITableView! private enum Segues: String { case questionDetail = "detailSegue" } private var searchButton: UIBarButtonItem! private var shareButton: UIBarButtonItem! private var searchString: String = "" private var currentPage: UInt = 0 private var hasReachedLastPage: Bool = true private var isLoading: Bool = false private var questions: [Question] = [] private var searchDelayTimer: NSTimer? = nil private var selectedQuestion: Question? = nil override func viewDidLoad() { super.viewDidLoad() self.initLayout() self.updateOnSchemeLaunch() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.updateOnSchemeLaunch), name: UIApplicationDidBecomeActiveNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.networkIsReachable), name: BaseHTTPManager.networkReachable, object: nil) } private func initLayout() { self.navigationItem.setHidesBackButton(true, animated: false) self.navigationController?.setNavigationBarHidden(false, animated: true) self.title = "Questions" self.searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(self.searchAction(_:))) self.navigationItem.setRightBarButtonItem(self.searchButton, animated: false) self.shareButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(self.shareAction(_:))) self.searchBar.placeholder = "Search language" self.searchBar.returnKeyType = .Done self.searchBar.enablesReturnKeyAutomatically = false self.tableView.tableFooterView = UIView() self.tableView.registerNib(UINib(nibName: String(QuestionTableViewCell), bundle: nil), forCellReuseIdentifier: String(QuestionTableViewCell)) } internal func updateOnSchemeLaunch() { if let filter: String = NSUserDefaults.standardUserDefaults().stringForKey("filter") { self.questions = [] self.tableView.reloadData() self.searchBarTopConstraint.constant = -44.0 self.searchAction(self) if filter == "" { self.searchBar.becomeFirstResponder() self.searchBar.text = "" } else { self.searchBar.resignFirstResponder() self.searchBar.text = filter } self.searchBar(self.searchBar, textDidChange: self.searchBar.text!) NSUserDefaults.standardUserDefaults().removeObjectForKey("filter") NSUserDefaults.standardUserDefaults().synchronize() } else if let id: String = NSUserDefaults.standardUserDefaults().stringForKey("id") { self.navigationController?.popToViewController(self, animated: false) self.questions = [] self.tableView.reloadData() self.searchBarTopConstraint.constant = 0.0 self.searchAction(self) self.searchBar.text = "" self.searchBar.resignFirstResponder() self.searchBar(self.searchBar, textDidChange: self.searchBar.text!) if let id: Int = Int(id) { self.getQuestion(withId: id) } NSUserDefaults.standardUserDefaults().removeObjectForKey("id") NSUserDefaults.standardUserDefaults().synchronize() } else { if self.questions.count == 0 { self.getQuestions() } } } internal func networkIsReachable() { self.hasReachedLastPage = false } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.questions.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: QuestionTableViewCell = tableView.dequeueReusableCellWithIdentifier(String(QuestionTableViewCell), forIndexPath: indexPath) as! QuestionTableViewCell cell.configure(withQuestion: self.questions[indexPath.row]) if !self.isLoading && !self.hasReachedLastPage && indexPath.row == self.questions.count - 5 { self.getQuestions() } return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return QuestionTableViewCell.height(forTitle: self.questions[indexPath.row].question) } // MARK: - Table view delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.view.endEditing(true) self.getQuestion(withId: self.questions[indexPath.row].id) self.tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Segues.questionDetail.rawValue { (segue.destinationViewController as! QuestionDetailsViewController).question = self.selectedQuestion } } // MARK: - Search bar delegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.searchString = searchText self.currentPage = 0 if self.searchString == "" { self.navigationItem.rightBarButtonItems = nil self.navigationItem.setRightBarButtonItem(self.searchButton, animated: true) } else { if self.navigationItem.rightBarButtonItems?.count == 1 { self.navigationItem.rightBarButtonItems = nil self.navigationItem.setRightBarButtonItems([self.searchButton, self.shareButton], animated: true) } } if self.searchDelayTimer != nil && (self.searchDelayTimer?.valid)! { self.searchDelayTimer?.invalidate() } self.searchDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(self.getQuestions), userInfo: nil, repeats: false) } // MARK: - UIButton actions @IBAction func searchAction(sender: AnyObject) { if self.searchBarTopConstraint.constant == 0 { self.searchBar.resignFirstResponder() if self.navigationItem.rightBarButtonItems?.count == 2 { self.navigationItem.rightBarButtonItems = nil self.navigationItem.setRightBarButtonItem(self.searchButton, animated: true) } self.searchBarTopConstraint.constant = -44.0 UIView.animateWithDuration(0.2, animations: { self.view.layoutIfNeeded() }) } else { self.searchBar.becomeFirstResponder() self.searchBarTopConstraint.constant = 0.0 UIView.animateWithDuration(0.3, animations: { self.view.layoutIfNeeded() }) } } @IBAction func shareAction(sender: AnyObject) { let shareView: ShareView = NSBundle.mainBundle().loadNibNamed(String(ShareView), owner: self, options: nil)?.first as! ShareView shareView.shareUrl = "blissrecruitment://questions?question_filter=" + self.searchString shareView.show() } // MARK: - Data request internal func getQuestions() { self.isLoading = true self.hasReachedLastPage = false self.currentPage += 1 DataManager.sharedManager.getQuestions(forPage: self.currentPage, withFilter: self.searchString) { (questions: [Question], error: NSError?) in if self.currentPage == 1 { self.questions = [] } if error == nil { self.hasReachedLastPage = UInt(questions.count) < NetworkClient.pageSize self.questions += questions self.isLoading = false self.tableView.reloadData() } else { self.isLoading = false self.hasReachedLastPage = true if self.currentPage == 1 { ProgressHUD.showErrorHUD(UIApplication.sharedApplication().keyWindow!, text: "An error was occurred\nwhile fetching questions.") } } } } internal func getQuestion(withId id: Int) { ProgressHUD.showProgressHUD(UIApplication.sharedApplication().keyWindow!, text: "Loading...") DataManager.sharedManager.getQuestion(withId: id) { (question: Question, error: NSError?) in if error == nil { self.selectedQuestion = question self.performSegueWithIdentifier(Segues.questionDetail.rawValue, sender: self) ProgressHUD.dismissAllHuds(UIApplication.sharedApplication().keyWindow!) } else { ProgressHUD.showErrorHUD(UIApplication.sharedApplication().keyWindow!, text: "An error was occurred\nwhile fetching details.") } } } }
lgpl-3.0
b676f9de33821686db5e368f263a81ff
39.512097
171
0.643078
5.51427
false
false
false
false
KevinShawn/HackingWithSwift
project8/Project8/ViewController.swift
24
3564
// // ViewController.swift // Project8 // // Created by Hudzilla on 15/09/2015. // Copyright © 2015 Paul Hudson. All rights reserved. // import GameplayKit import UIKit class ViewController: UIViewController { @IBOutlet weak var cluesLabel: UILabel! @IBOutlet weak var answersLabel: UILabel! @IBOutlet weak var currentAnswer: UITextField! @IBOutlet weak var scoreLabel: UILabel! var letterButtons = [UIButton]() var activatedButtons = [UIButton]() var solutions = [String]() var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var level = 1 override func viewDidLoad() { super.viewDidLoad() for subview in view.subviews where subview.tag == 1001 { let btn = subview as! UIButton letterButtons.append(btn) btn.addTarget(self, action: "letterTapped:", forControlEvents: .TouchUpInside) } loadLevel() } func loadLevel() { var clueString = "" var solutionString = "" var letterBits = [String]() if let levelFilePath = NSBundle.mainBundle().pathForResource("level\(level)", ofType: "txt") { if let levelContents = try? String(contentsOfFile: levelFilePath, usedEncoding: nil) { var lines = levelContents.componentsSeparatedByString("\n") lines = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(lines) as! [String] for (index, line) in lines.enumerate() { let parts = line.componentsSeparatedByString(": ") let answer = parts[0] let clue = parts[1] clueString += "\(index + 1). \(clue)\n" let solutionWord = answer.stringByReplacingOccurrencesOfString("|", withString: "") solutionString += "\(solutionWord.characters.count) letters\n" solutions.append(solutionWord) let bits = answer.componentsSeparatedByString("|") letterBits += bits } } } cluesLabel.text = clueString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) answersLabel.text = solutionString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) letterBits = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(letterBits) as! [String] letterButtons = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(letterButtons) as! [UIButton] if letterBits.count == letterButtons.count { for i in 0 ..< letterBits.count { letterButtons[i].setTitle(letterBits[i], forState: .Normal) } } } @IBAction func submitTapped(sender: AnyObject) { if let solutionPosition = solutions.indexOf(currentAnswer.text!) { activatedButtons.removeAll() var splitClues = answersLabel.text!.componentsSeparatedByString("\n") splitClues[solutionPosition] = currentAnswer.text! answersLabel.text = splitClues.joinWithSeparator("\n") currentAnswer.text = "" ++score if score % 7 == 0 { let ac = UIAlertController(title: "Well done!", message: "Are you ready for the next level?", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "Let's go!", style: .Default, handler: levelUp)) presentViewController(ac, animated: true, completion: nil) } } } @IBAction func clearTapped(sender: AnyObject) { currentAnswer.text = "" for btn in activatedButtons { btn.hidden = false } activatedButtons.removeAll() } func letterTapped(btn: UIButton) { currentAnswer.text = currentAnswer.text! + btn.titleLabel!.text! activatedButtons.append(btn) btn.hidden = true } func levelUp(action: UIAlertAction!) { ++level solutions.removeAll(keepCapacity: true) loadLevel() for btn in letterButtons { btn.hidden = false } } }
unlicense
38c0309cefb1b766b93d835ee57af6c6
26.620155
121
0.714566
4.067352
false
false
false
false
JeffESchmitz/RideNiceRide
RideNiceRide/Models/FavoriteStation.swift
1
2489
// // FavoriteStation.swift // RideNiceRide // // Created by Jeff Schmitz on 1/1/17. // Copyright © 2017 Jeff Schmitz. All rights reserved. // import Foundation import CoreData extension FavoriteStation { convenience init(stationName: String = "Unknown", address1: String = "", address2: String = "", altitude: String = "", availableBikes: String = "0", availableDocks: String = "0", city: String = "", id: String = "", landMark: String = "", lastCommunicationTime: String = "", latitude: String = "", location: String = "", longitude: String = "", postalCode: String = "", statusKey: String = "", statusValue: String = "", testStation: Bool = false, totalDocks: String, context: NSManagedObjectContext) { //An EntityDescription is an object that has access to all //the information you provided in the Entity part of the model //you need it to create an instance of this class. if let entity = NSEntityDescription.entity(forEntityName: "FavoriteStation", in: context) { self.init(entity: entity, insertInto: context) self.stationName = stationName self.stAddress1 = address1 self.stAddress2 = address2 self.altitude = altitude self.availableBikes = availableBikes self.availableDocks = availableDocks self.city = city self.id = id self.landMark = landMark self.lastCommunicationTime = lastCommunicationTime self.latitude = latitude self.location = location self.longitude = longitude self.postalCode = postalCode self.statusKey = statusKey self.statusValue = statusValue self.testStation = testStation self.totalDocks = totalDocks } else { fatalError("Unable to find Entity name!") } } }
mit
16cb9720214b624f74add297ede9b85d
40.466667
99
0.480707
5.706422
false
true
false
false
dsay/POPDataSources
Sources/POPDataSources/TableViewDataSource+Paging.swift
1
3102
import UIKit open class PagingDataSource: TableViewDataSource, DataSourcesContainable { public enum Status { case new case normal case loading case reachedLast } public typealias Result = (Bool, [TableViewDataSource]) -> Void public typealias Loader = (_ result: @escaping Result) -> Void public var status: Status = .new public var dataSources: [TableViewDataSource] = [] public var spinner = UIActivityIndicatorView(style: .gray) private let loader: Loader! private weak var tableView: UITableView? public init(_ dataSources: [TableViewDataSource] = [], _ loader: @escaping Loader) { self.dataSources = dataSources self.loader = loader } public func numberOfSections(for tableView: UITableView) -> Int { self.tableView = tableView if status == .loading { startAnimation() } return numberOfSections() } public func willDisplay(row: UITableViewCell, in tableView: UITableView, at indexPath: IndexPath) { let dataSource = self.dataSource(at: indexPath.section) dataSource.willDisplay(row: row, in: tableView, at: indexPath) let lastSectionIndex = tableView.numberOfSections - 1 let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1 if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex { willDisplayLastCell() } } private func willDisplayLastCell() { guard status != .reachedLast else { return } startAnimation() status = .loading loader({ [weak self] isReachedLast, dataSources in if isReachedLast { self?.status = .reachedLast } else { self?.status = .normal } self?.stopAnimation() self?.dataSources += dataSources self?.tableView?.reloadData() }) } public func reloadData() { startAnimation() status = .loading loader({ [weak self] isReachedLast, dataSources in if isReachedLast { self?.status = .reachedLast } else { self?.status = .normal } self?.stopAnimation() self?.dataSources = dataSources self?.tableView?.reloadData() }) } public func isAnimated() -> Bool { return status == .loading } public func startAnimation() { guard let tableView = tableView else { return } spinner.startAnimating() spinner.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 44) tableView.tableFooterView = spinner } public func stopAnimation() { guard let tableView = tableView else { return } tableView.tableFooterView = nil tableView.setContentOffset(tableView.contentOffset, animated: false) } }
mit
db67cb3d91427481cc93224cf51b8d28
28.542857
103
0.579626
5.579137
false
false
false
false
Erickson0806/AdaptivePhotos
AdaptivePhotosUsingUIKitTraitsandSizeClasses/AdaptiveStoryboard/AdaptiveStoryboard/AppDelegate.swift
1
4121
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The application delegate and split view controller delegate. */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Load the conversations from disk and create our root model object. let user: User if let url = NSBundle.mainBundle().URLForResource("User", withExtension: "plist"), userDictionary = NSDictionary(contentsOfURL: url) as? [String: AnyObject], loadedUser = User(dictionary: userDictionary) { user = loadedUser } else { user = User() } if let splitViewController = window?.rootViewController as? UISplitViewController { splitViewController.delegate = self splitViewController.preferredDisplayMode = .AllVisible if let masterNavController = splitViewController.viewControllers.first as? UINavigationController, masterViewController = masterNavController.topViewController as? ListTableViewController { masterViewController.user = user } } window?.makeKeyAndVisible() return true } } extension AppDelegate: UISplitViewControllerDelegate { // Collapse the secondary view controller onto the primary view controller. func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { /* The secondary view is not showing a photo. Return true to tell the splitViewController to use its default behavior: just hide the secondaryViewController and show the primaryViewController. */ guard let photo = secondaryViewController.containedPhoto() else { return true } /* The secondary view is showing a photo. Set the primary navigation controller to contain a path of view controllers that lead to that photo. */ if let primaryNavController = primaryViewController as? UINavigationController { let viewControllersLeadingToPhoto = primaryNavController.viewControllers.filter { $0.containsPhoto(photo) } primaryNavController.viewControllers = viewControllersLeadingToPhoto } /* We handled the collapse. Return false to tell the splitViewController not to do anything else. */ return false } // Separate the secondary view controller from the primary view controller. func splitViewController(splitViewController: UISplitViewController, separateSecondaryViewControllerFromPrimaryViewController primaryViewController: UIViewController) -> UIViewController? { if let primaryNavController = primaryViewController as? UINavigationController { /* One of the view controllers in the navigation stack is showing a photo. Return nil to tell the splitViewController to use its default behavior: show the secondary view controller that was present when it collapsed. */ let anyViewControllerContainsPhoto = primaryNavController.viewControllers.contains { controller in return controller.containedPhoto() != nil } if anyViewControllerContainsPhoto { return nil } } /* None of the view controllers in the navigation stack contained a photo, so show a new empty view controller as the secondary. */ return primaryViewController.storyboard?.instantiateViewControllerWithIdentifier("EmptyViewController") } }
apache-2.0
ceeec357c356cac99ae9b2c6cbd36034
41.90625
224
0.673707
6.708469
false
false
false
false
suzuki-0000/SummerWars
SummerWarsExample/SummerWarsExample/ViewController.swift
1
1285
// // ViewController.swift // SummerWarsExample // // Created by suzuki keishi on 2015/11/10. // Copyright © 2015年 suzuki_keishi. All rights reserved. // import UIKit import SummerWars class ViewController: UIViewController { var captions = ["Lorem Ipsum.", "it to make a type specimen book.", "It has survived not typesetting", "remaining of Lorem Ipsum.", "simply dummy text of the printing and typesetting industry.", "text ever since the 1500s" ] override func viewDidLoad() { super.viewDidLoad() var contents = [WarsContent]() for _ in 0..<30{ let image = UIImage(named: "image\(Int.random(max: 16)).jpg") ?? UIImage() contents.append(WarsContent(image:image, caption: captions[Int.random(max: captions.count - 1)])) } let summerWarsView = SummerWarsViewController(contents: contents) addChildViewController(summerWarsView, toContainerView: view) } } extension UIViewController { func addChildViewController(vc: UIViewController, toContainerView containerView: UIView) { addChildViewController(vc) containerView.addSubview(vc.view) vc.didMoveToParentViewController(self) } } extension Int { static func random(min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } }
mit
da099b7c004696830792b019fd50e431
25.729167
100
0.717629
3.601124
false
false
false
false
GitTennis/SuccessFramework
Templates/_BusinessAppSwift_/_BusinessAppSwift_Tests/KeychainManagerTests.swift
2
2434
// // KeychainManagerTests.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 26/10/2016. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit import XCTest @testable import _BusinessAppSwift_ class KeychainManagerTests: _BusinessAppSwift_Tests { 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 test_authentificationToken() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let keychainStore = KeychainManager() // Test save let errorEntity: ErrorEntity? = keychainStore.setAuthentificationToken(token: "userToken1") XCTAssert((errorEntity == nil), "Should be no error after save") // Test load let token: String? = keychainStore.authentificationToken() NLAssertEqualOptional(expression1: token, "userToken1", "A token was not retrieved") } }
mit
0e8145df36979d89fab5da54ad53d2bd
40.931034
111
0.711349
4.623574
false
true
false
false
huangboju/Moots
UICollectionViewLayout/CollectionKit-master/Sources/Addon/EmptyStateCollectionProvider.swift
1
1543
// // EmptyStateCollectionProvider.swift // CollectionKit // // Created by Luke Zhao on 2017-08-08. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit public class EmptyStateCollectionProvider: CollectionComposer { var emptyStateView: UIView? var emptyStateViewGetter: () -> UIView var content: AnyCollectionProvider public init(identifier: String? = nil, emptyStateView: @autoclosure @escaping () -> UIView, content: AnyCollectionProvider) { self.emptyStateViewGetter = emptyStateView self.content = content super.init(identifier: identifier, layout: RowLayout("emptyStateView").transposed(), sections: [content]) } public override func willReload() { content.willReload() if content.numberOfItems == 0, sections.first === content { if emptyStateView == nil { emptyStateView = emptyStateViewGetter() } let viewSection = ViewCollectionProvider(emptyStateView!, sizeStrategy: (.fill, .fill)) viewSection.identifier = "emptyStateView" sections = [viewSection] super.willReload() } else if content.numberOfItems > 0, sections.first !== content { sections = [content] prepareForReload() // no need to call willReload on `content` } else { super.willReload() } } public override func hasReloadable(_ reloadable: CollectionReloadable) -> Bool { return reloadable === content || content.hasReloadable(reloadable) || super.hasReloadable(reloadable) } }
mit
97a66ba28c278dd99505bdba38d0ec22
31.808511
105
0.680285
4.715596
false
false
false
false
ProcedureKit/ProcedureKit
Sources/TestingProcedureKit/ConcurrencyTestCase.swift
2
22485
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import Foundation import XCTest import ProcedureKit public protocol ConcurrencyTestResultProtocol { var procedures: [TestConcurrencyTrackingProcedure] { get } var duration: Double { get } var registrar: ConcurrencyRegistrar { get } } // MARK: - ConcurrencyTestCase open class ConcurrencyTestCase: ProcedureKitTestCase { public typealias Registrar = ConcurrencyRegistrar public typealias TrackingProcedure = TestConcurrencyTrackingProcedure public var registrar: Registrar! public class TestResult: ConcurrencyTestResultProtocol { public let procedures: [TrackingProcedure] public let duration: TimeInterval public let registrar: Registrar public init(procedures: [TrackingProcedure], duration: TimeInterval, registrar: Registrar) { self.procedures = procedures self.duration = duration self.registrar = registrar } } public struct Expectations { public let checkMinimumDetected: Int? public let checkMaximumDetected: Int? public let checkAllProceduresFinished: Bool? public let checkMinimumDuration: TimeInterval? public let checkExactDetected: Int? public init(checkMinimumDetected: Int? = .none, checkMaximumDetected: Int? = .none, checkAllProceduresFinished: Bool? = .none, checkMinimumDuration: TimeInterval? = .none) { if let checkMinimumDetected = checkMinimumDetected, let checkMaximumDetected = checkMaximumDetected, checkMinimumDetected == checkMaximumDetected { self.checkExactDetected = checkMinimumDetected } else { self.checkExactDetected = .none } self.checkMinimumDetected = checkMinimumDetected self.checkMaximumDetected = checkMaximumDetected self.checkAllProceduresFinished = checkAllProceduresFinished self.checkMinimumDuration = checkMinimumDuration } } public func create(procedures count: Int = 3, delayMicroseconds: useconds_t = 500000 /* 0.5 seconds */, withRegistrar registrar: Registrar) -> [TrackingProcedure] { return (0..<count).map { i in let name = "TestConcurrencyTrackingProcedure: \(i)" return TestConcurrencyTrackingProcedure(name: name, microsecondsToSleep: delayMicroseconds, registrar: registrar) } } public func concurrencyTest(operations: Int = 3, withDelayMicroseconds delayMicroseconds: useconds_t = 500000 /* 0.5 seconds */, withName name: String = #function, withTimeout timeout: TimeInterval = 3, withConfigureBlock configure: (TrackingProcedure) -> TrackingProcedure = { return $0 }, withExpectations expectations: Expectations) { concurrencyTest(operations: operations, withDelayMicroseconds: delayMicroseconds, withTimeout: timeout, withConfigureBlock: configure, completionBlock: { (results) in XCTAssertResults(results, matchExpectations: expectations) } ) } public func concurrencyTest(operations: Int = 3, withDelayMicroseconds delayMicroseconds: useconds_t = 500000 /* 0.5 seconds */, withName name: String = #function, withTimeout timeout: TimeInterval = 3, withConfigureBlock configure: (TrackingProcedure) -> TrackingProcedure = { return $0 }, completionBlock completion: (TestResult) -> Void) { let registrar = Registrar() let procedures = create(procedures: operations, delayMicroseconds: delayMicroseconds, withRegistrar: registrar).map { return configure($0) } let startTime = CFAbsoluteTimeGetCurrent() wait(forAll: procedures, withTimeout: timeout) let endTime = CFAbsoluteTimeGetCurrent() let duration = Double(endTime) - Double(startTime) completion(TestResult(procedures: procedures, duration: duration, registrar: registrar)) } public func XCTAssertResults(_ results: TestResult, matchExpectations expectations: Expectations) { // checkAllProceduresFinished if let checkAllProceduresFinished = expectations.checkAllProceduresFinished, checkAllProceduresFinished { for i in results.procedures.enumerated() { XCTAssertTrue(i.element.isFinished, "Test procedure [\(i.offset)] did not finish") } } // exact test for registrar.maximumDetected if let checkExactDetected = expectations.checkExactDetected { XCTAssertEqual(results.registrar.maximumDetected, checkExactDetected, "maximumDetected concurrent operations (\(results.registrar.maximumDetected)) does not equal expected: \(checkExactDetected)") } else { // checkMinimumDetected if let checkMinimumDetected = expectations.checkMinimumDetected { XCTAssertGreaterThanOrEqual(results.registrar.maximumDetected, checkMinimumDetected, "maximumDetected concurrent operations (\(results.registrar.maximumDetected)) is less than expected minimum: \(checkMinimumDetected)") } // checkMaximumDetected if let checkMaximumDetected = expectations.checkMaximumDetected { XCTAssertLessThanOrEqual(results.registrar.maximumDetected, checkMaximumDetected, "maximumDetected concurrent operations (\(results.registrar.maximumDetected)) is greater than expected maximum: \(checkMaximumDetected)") } } // checkMinimumDuration if let checkMinimumDuration = expectations.checkMinimumDuration { XCTAssertGreaterThanOrEqual(results.duration, checkMinimumDuration, "Test duration exceeded minimum expected duration.") } } open override func setUp() { super.setUp() registrar = Registrar() } open override func tearDown() { registrar = nil super.tearDown() } } // MARK: - ConcurrencyRegistrar open class ConcurrencyRegistrar { private struct State { var operations: [Operation] = [] var maximumDetected: Int = 0 } private let state = Protector(State()) public var maximumDetected: Int { get { return state.read { $0.maximumDetected } } } public func registerRunning(_ operation: Operation) { state.write { ward in ward.operations.append(operation) ward.maximumDetected = max(ward.operations.count, ward.maximumDetected) } } public func deregisterRunning(_ operation: Operation) { state.write { ward in if let opIndex = ward.operations.firstIndex(of: operation) { ward.operations.remove(at: opIndex) } } } } // MARK: - TestConcurrencyTrackingProcedure open class TestConcurrencyTrackingProcedure: Procedure { private(set) weak var concurrencyRegistrar: ConcurrencyRegistrar? let microsecondsToSleep: useconds_t init(name: String = "TestConcurrencyTrackingProcedure", microsecondsToSleep: useconds_t, registrar: ConcurrencyRegistrar) { self.concurrencyRegistrar = registrar self.microsecondsToSleep = microsecondsToSleep super.init() self.name = name } override open func execute() { concurrencyRegistrar?.registerRunning(self) usleep(microsecondsToSleep) concurrencyRegistrar?.deregisterRunning(self) finish() } } // MARK: - EventConcurrencyTrackingRegistrar // Tracks Procedure Events and the Threads on which they occur. // Detects concurrency issues if two events occur conccurently on two different threads. // Use a unique EventConcurrencyTrackingRegistrar per Procedure instance. public class EventConcurrencyTrackingRegistrar { public enum ProcedureEvent: Equatable, CustomStringConvertible { case do_Execute case observer_didAttach case observer_willExecute case observer_didExecute case observer_willCancel case observer_didCancel case observer_procedureWillAdd(String) case observer_procedureDidAdd(String) case observer_willFinish case observer_didFinish case override_procedureWillCancel case override_procedureDidCancel case override_procedureWillFinish case override_procedureDidFinish // GroupProcedure open functions case override_groupWillAdd_child(String) case override_child_willFinishWithErrors(String) // GroupProcedure handlers case group_transformChildErrorsBlock(String) public var description: String { switch self { case .do_Execute: return "execute()" case .observer_didAttach: return "observer_didAttach" case .observer_willExecute: return "observer_willExecute" case .observer_didExecute: return "observer_didExecute" case .observer_willCancel: return "observer_willCancel" case .observer_didCancel: return "observer_didCancel" case .observer_procedureWillAdd(let name): return "observer_procedureWillAdd [\(name)]" case .observer_procedureDidAdd(let name): return "observer_procedureDidAdd [\(name)]" case .observer_willFinish: return "observer_willFinish" case .observer_didFinish: return "observer_didFinish" case .override_procedureWillCancel: return "procedureWillCancel()" case .override_procedureDidCancel: return "procedureDidCancel()" case .override_procedureWillFinish: return "procedureWillFinish()" case .override_procedureDidFinish: return "procedureDidFinish()" // GroupProcedure open functions case .override_groupWillAdd_child(let child): return "groupWillAdd(child:) [\(child)]" case .override_child_willFinishWithErrors(let child): return "child(_:willFinishWithErrors:) [\(child)]" case .group_transformChildErrorsBlock(let child): return "group.transformChildErrorsBlock [\(child)]" } } } public struct DetectedConcurrentEventSet: CustomStringConvertible { private var array: [DetectedConcurrentEvent] = [] public var description: String { var description: String = "" for concurrentEvent in array { guard !description.isEmpty else { description.append("\(concurrentEvent)") continue } description.append("\n\(concurrentEvent)") } return description } public var isEmpty: Bool { return array.isEmpty } public mutating func append(_ newElement: DetectedConcurrentEvent) { array.append(newElement) } } public struct DetectedConcurrentEvent: CustomStringConvertible { var newEvent: (event: ProcedureEvent, threadUUID: String) var currentEvents: [UUID: (event: ProcedureEvent, threadUUID: String)] private func truncateThreadID(_ uuidString: String) -> String { //let uuidString = threadUUID.uuidString #if swift(>=3.2) return String(uuidString[..<uuidString.index(uuidString.startIndex, offsetBy: 4)]) #else return uuidString.substring(to: uuidString.index(uuidString.startIndex, offsetBy: 4)) #endif } public var description: String { var description = "+ \(newEvent.event) (t: \(truncateThreadID(newEvent.threadUUID))) while: " /*+ "while: \n"*/ for (_, event) in currentEvents { description.append("\n\t- \(event.event) (t: \(truncateThreadID(event.threadUUID)))") } return description } } private struct State { // the current eventCallbacks var eventCallbacks: [UUID: (event: ProcedureEvent, threadUUID: String)] = [:] // maximum simultaneous eventCallbacks detected var maximumDetected: Int = 0 // a list of detected concurrent events var detectedConcurrentEvents = DetectedConcurrentEventSet() // a history of all detected events (optional) var eventHistory: [ProcedureEvent] = [] } private let state = Protector(State()) public var maximumDetected: Int { return state.read { $0.maximumDetected } } public var detectedConcurrentEvents: DetectedConcurrentEventSet { return state.read { $0.detectedConcurrentEvents } } public var eventHistory: [ProcedureEvent]? { return (recordHistory) ? state.read { $0.eventHistory } : nil } private let recordHistory: Bool public init(recordHistory: Bool = false) { self.recordHistory = recordHistory } private let kThreadUUID: NSString = "run.kit.procedure.ProcedureKit.Testing.ThreadUUID" private func registerRunning(_ event: ProcedureEvent) -> UUID { // get current thread data let currentThread = Thread.current func getThreadUUID(_ thread: Thread) -> String { guard !thread.isMainThread else { return "main" } if let currentThreadUUID = currentThread.threadDictionary.object(forKey: kThreadUUID) as? UUID { return currentThreadUUID.uuidString } else { let newUUID = UUID() currentThread.threadDictionary.setObject(newUUID, forKey: kThreadUUID) return newUUID.uuidString } } let currentThreadUUID = getThreadUUID(currentThread) return state.write { ward -> UUID in var newUUID = UUID() while ward.eventCallbacks.keys.contains(newUUID) { newUUID = UUID() } if ward.eventCallbacks.count >= 1 { // determine if all existing event callbacks are on the same thread // as the new event callback if !ward.eventCallbacks.filter({ $0.1.threadUUID != currentThreadUUID }).isEmpty { ward.detectedConcurrentEvents.append(DetectedConcurrentEvent(newEvent: (event: event, threadUUID: currentThreadUUID), currentEvents: ward.eventCallbacks)) } } ward.eventCallbacks.updateValue((event, currentThreadUUID), forKey: newUUID) ward.maximumDetected = max(ward.eventCallbacks.count, ward.maximumDetected) if recordHistory { ward.eventHistory.append(event) } return newUUID } } private func deregisterRunning(_ uuid: UUID) { state.write { ward -> Bool in return ward.eventCallbacks.removeValue(forKey: uuid) != nil } } public func doRun(_ callback: ProcedureEvent, withDelay delay: TimeInterval = 0.0001, block: (ProcedureEvent) -> Void = { _ in }) { let id = registerRunning(callback) if delay > 0 { usleep(UInt32(delay * TimeInterval(1000000))) } block(callback) deregisterRunning(id) } } // MARK: - ConcurrencyTrackingObserver open class ConcurrencyTrackingObserver: ProcedureObserver { private var registrar: EventConcurrencyTrackingRegistrar! public let eventQueue: DispatchQueueProtocol? let callbackBlock: (Procedure, EventConcurrencyTrackingRegistrar.ProcedureEvent) -> Void public init(registrar: EventConcurrencyTrackingRegistrar? = nil, eventQueue: DispatchQueueProtocol? = nil, callbackBlock: @escaping (Procedure, EventConcurrencyTrackingRegistrar.ProcedureEvent) -> Void = { _, _ in }) { if let registrar = registrar { self.registrar = registrar } self.eventQueue = eventQueue self.callbackBlock = callbackBlock } public func didAttach(to procedure: Procedure) { if let eventTrackingProcedure = procedure as? EventConcurrencyTrackingProcedureProtocol { if registrar == nil { registrar = eventTrackingProcedure.concurrencyRegistrar } doRun(.observer_didAttach, block: { callback in callbackBlock(procedure, callback) }) } } public func will(execute procedure: Procedure, pendingExecute: PendingExecuteEvent) { doRun(.observer_willExecute, block: { callback in callbackBlock(procedure, callback) }) } public func did(execute procedure: Procedure) { doRun(.observer_didExecute, block: { callback in callbackBlock(procedure, callback) }) } public func will(cancel procedure: Procedure, with: Error?) { doRun(.observer_willCancel, block: { callback in callbackBlock(procedure, callback) }) } public func did(cancel procedure: Procedure, with: Error?) { doRun(.observer_didCancel, block: { callback in callbackBlock(procedure, callback) }) } public func procedure(_ procedure: Procedure, willAdd newOperation: Operation) { doRun(.observer_procedureWillAdd(newOperation.operationName), block: { callback in callbackBlock(procedure, callback) }) } public func procedure(_ procedure: Procedure, didAdd newOperation: Operation) { doRun(.observer_procedureDidAdd(newOperation.operationName), block: { callback in callbackBlock(procedure, callback) }) } public func will(finish procedure: Procedure, with error: Error?, pendingFinish: PendingFinishEvent) { doRun(.observer_willFinish, block: { callback in callbackBlock(procedure, callback) }) } public func did(finish procedure: Procedure, with error: Error?) { doRun(.observer_didFinish, block: { callback in callbackBlock(procedure, callback) }) } public func doRun(_ callback: EventConcurrencyTrackingRegistrar.ProcedureEvent, withDelay delay: TimeInterval = 0.0001, block: (EventConcurrencyTrackingRegistrar.ProcedureEvent) -> Void = { _ in }) { registrar.doRun(callback, withDelay: delay, block: block) } } // MARK: - EventConcurrencyTrackingProcedure public protocol EventConcurrencyTrackingProcedureProtocol { var concurrencyRegistrar: EventConcurrencyTrackingRegistrar { get } } // Tracks the concurrent execution of various user code // (observers, `execute()` and other function overrides, etc.) // automatically handles events triggered from within other events // (as long as everything happens on the same thread) open class EventConcurrencyTrackingProcedure: Procedure, EventConcurrencyTrackingProcedureProtocol { public private(set) var concurrencyRegistrar: EventConcurrencyTrackingRegistrar private let delay: TimeInterval private let executeBlock: (EventConcurrencyTrackingProcedure) -> Void public init(name: String = "EventConcurrencyTrackingProcedure", withDelay delay: TimeInterval = 0, registrar: EventConcurrencyTrackingRegistrar = EventConcurrencyTrackingRegistrar(), baseObserver: ConcurrencyTrackingObserver? = ConcurrencyTrackingObserver(), execute: @escaping (EventConcurrencyTrackingProcedure) -> Void) { self.concurrencyRegistrar = registrar self.delay = delay self.executeBlock = execute super.init() self.name = name if let baseObserver = baseObserver { addObserver(baseObserver) } } open override func execute() { concurrencyRegistrar.doRun(.do_Execute, withDelay: delay, block: { _ in executeBlock(self) }) } // Cancellation Handler Overrides open override func procedureDidCancel(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureDidCancel) super.procedureDidCancel(with: error) } // Finish Handler Overrides open override func procedureWillFinish(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureWillFinish) super.procedureWillFinish(with: error) } open override func procedureDidFinish(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureDidFinish) super.procedureDidFinish(with: error) } } open class EventConcurrencyTrackingGroupProcedure: GroupProcedure, EventConcurrencyTrackingProcedureProtocol { public private(set) var concurrencyRegistrar: EventConcurrencyTrackingRegistrar private let delay: TimeInterval public init(dispatchQueue underlyingQueue: DispatchQueue? = nil, operations: [Operation], name: String = "EventConcurrencyTrackingGroupProcedure", withDelay delay: TimeInterval = 0, registrar: EventConcurrencyTrackingRegistrar = EventConcurrencyTrackingRegistrar(), baseObserver: ConcurrencyTrackingObserver? = ConcurrencyTrackingObserver()) { self.concurrencyRegistrar = registrar self.delay = delay super.init(dispatchQueue: underlyingQueue, operations: operations) self.name = name if let baseObserver = baseObserver { addObserver(baseObserver) } // GroupProcedure transformChildErrorsBlock transformChildErrorBlock = { [concurrencyRegistrar] (child, _) in concurrencyRegistrar.doRun(.group_transformChildErrorsBlock(child.operationName)) } } open override func execute() { concurrencyRegistrar.doRun(.do_Execute, withDelay: delay, block: { _ in super.execute() }) } // Cancellation Handler Overrides open override func procedureDidCancel(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureDidCancel) super.procedureDidCancel(with: error) } // Finish Handler Overrides open override func procedureWillFinish(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureWillFinish) super.procedureWillFinish(with: error) } open override func procedureDidFinish(with error: Error?) { concurrencyRegistrar.doRun(.override_procedureDidFinish) super.procedureDidFinish(with: error) } // GroupProcedure Overrides open override func groupWillAdd(child: Operation) { concurrencyRegistrar.doRun(.override_groupWillAdd_child(child.operationName)) super.groupWillAdd(child: child) } open override func child(_ child: Procedure, willFinishWithError error: Error?) { concurrencyRegistrar.doRun(.override_child_willFinishWithErrors(child.operationName)) return super.child(child, willFinishWithError: error) } }
mit
cbf2f1d46ad00c02dae0813b517eda43
42.489362
347
0.683152
5.1392
false
false
false
false
turingcorp/gattaca
gattaca/View/Basic/VGradient.swift
1
2932
import UIKit class VGradient:UIView { private static let kLocationStart:NSNumber = 0 private static let kLocationEnd:NSNumber = 1 class func diagonal( colourLeftBottom:UIColor, colourTopRight:UIColor) -> VGradient { let colours:[CGColor] = [ colourLeftBottom.cgColor, colourTopRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:1) let endPoint:CGPoint = CGPoint(x:1, y:0) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func horizontal( colourLeft:UIColor, colourRight:UIColor) -> VGradient { let colours:[CGColor] = [ colourLeft.cgColor, colourRight.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0, y:0.5) let endPoint:CGPoint = CGPoint(x:1, y:0.5) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } class func vertical( colourTop:UIColor, colourBottom:UIColor) -> VGradient { let colours:[CGColor] = [ colourTop.cgColor, colourBottom.cgColor] let locations:[NSNumber] = [ kLocationStart, kLocationEnd] let startPoint:CGPoint = CGPoint(x:0.5, y:0) let endPoint:CGPoint = CGPoint(x:0.5, y:1) let gradient:VGradient = VGradient( colours:colours, locations:locations, startPoint:startPoint, endPoint:endPoint) return gradient } private init( colours:[CGColor], locations:[NSNumber], startPoint:CGPoint, endPoint:CGPoint) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false guard let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer else { return } gradientLayer.startPoint = startPoint gradientLayer.endPoint = endPoint gradientLayer.locations = locations gradientLayer.colors = colours } required init?(coder:NSCoder) { return nil } override open class var layerClass:AnyClass { get { return CAGradientLayer.self } } }
mit
5e7bbd9821d30f0f990c356f39263fab
24.946903
78
0.555252
5.1529
false
false
false
false
sebastiancrossa/smack
Smack/Controller/ChannelVC.swift
1
5275
// // ChannelVC.swift // Smack // // Created by Sebastian Crossa on 7/29/17. // Copyright © 2017 Sebastian Crossa. All rights reserved. // import UIKit class ChannelVC: UIViewController, UITableViewDelegate, UITableViewDataSource { // Outlets @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var userImage: CircleImage! @IBOutlet weak var tableView: UITableView! // Target of the unwind segue @IBAction func prepareForUnwind(segue: UIStoryboardSegue){} override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // Changing the value of the amount revealed self.revealViewController().rearViewRevealWidth = self.view.frame.size.width - 60 // Notification observers NotificationCenter.default.addObserver(self, selector: #selector(ChannelVC.userDataDidChange(_:)), name: NOTIF_USER_DATA_DID_CHANGE, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ChannelVC.channelsLoaded(_:)), name: NOTIF_CHANNELS_LOADED, object: nil) // Will listen to the creation of channels and reloading table view SocketService.instance.getChannel { (success) in if success { self.tableView.reloadData() } } SocketService.instance.getChatMessage { (newMessage) in if newMessage.channelId != MessageService.instance.selectedChannel?.id && AuthService.instance.isLoggedIn { // Channel that has unread messages MessageService.instance.unreadChannels.append(newMessage.channelId) self.tableView.reloadData() } } } override func viewDidAppear(_ animated: Bool) { setupUserInfo() } // Will segue over to the LoginVC @IBAction func loginButtonPressed(_ sender: Any) { if AuthService.instance.isLoggedIn { let profile = ProfileVC() profile.modalPresentationStyle = .custom present(profile, animated: true, completion: nil) } else { performSegue(withIdentifier: TO_LOGIN, sender: nil) } } // Called every time we recieve the notification of a user changing data @objc func userDataDidChange(_ notif: Notification) { setupUserInfo() } @objc func channelsLoaded(_ notif: Notification) { tableView.reloadData() } // In charge of loading up the users name and profile picture func setupUserInfo() { if AuthService.instance.isLoggedIn { loginButton.setTitle(UserDataService.instance.name, for: .normal) userImage.image = UIImage(named: UserDataService.instance.avatarName) userImage.backgroundColor = UserDataService.instance.returnUIColor(components: UserDataService.instance.avatarColor) } else { loginButton.setTitle("Login", for: .normal) userImage.image = UIImage(named: "menuProfileIcon") userImage.backgroundColor = UIColor.clear // Will reload the tableView so it can display all of the channels tableView.reloadData() } } @IBAction func createChannelPressed(_ sender: Any) { if AuthService.instance.isLoggedIn { let createChannel = AddChannelVC() createChannel.modalPresentationStyle = .custom present(createChannel, animated: true, completion: nil) } } // Conforming to the table view protocols func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "channelCell", for: indexPath) as? ChannelCell { let channel = MessageService.instance.channels[indexPath.row] cell.configureCell(channel: channel) return cell } else { return UITableViewCell() } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return MessageService.instance.channels.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let channel = MessageService.instance.channels[indexPath.row] let index = IndexPath(row: indexPath.row, section: 0) MessageService.instance.selectedChannel = channel if MessageService.instance.unreadChannels.count > 0 { MessageService.instance.unreadChannels = MessageService.instance.unreadChannels.filter{$0 != channel.id} } tableView.reloadRows(at: [index], with: .none) tableView.selectRow(at: index, animated: false, scrollPosition: .none) NotificationCenter.default.post(name: NOTIF_CHANNEL_SELECTED, object: nil) self.revealViewController().revealToggle(animated: true) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
apache-2.0
9b7a912b07fd551697fdc027504eb5f7
35.881119
153
0.641638
5.284569
false
false
false
false
5calls/ios
FiveCalls/FiveCalls/FetchUserStatsOperation.swift
1
3128
// // FetchUserStatsOperation.swift // FiveCalls // // Created by Mel Stanley on 1/31/18. // Copyright © 2018 5calls. All rights reserved. // import Foundation class FetchUserStatsOperation : BaseOperation { class TokenExpiredError : Error { } var userStats: UserStats? var firstCallTime: Date? var httpResponse: HTTPURLResponse? var error: Error? private var retryCount = 0 override func execute() { let config = URLSessionConfiguration.default let session = URLSessionProvider.buildSession(configuration: config) let url = URL(string: "https://api.5calls.org/v1/users/stats")! var request = URLRequest(url: url) if let authToken = SessionManager.shared.idToken { request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization") } let task = session.dataTask(with: request) { (data, response, error) in if let e = error { self.error = e } else { let http = response as! HTTPURLResponse self.httpResponse = http guard let data = data else { return } switch http.statusCode { case 200: do { try self.parseResponse(data: data) } catch let e as NSError { // log an continue, not worth crashing over print("Error parsing user stats: \(e.localizedDescription)") } self.finish() case 401: if self.retryCount >= 2 { self.error = TokenExpiredError() self.finish() } else { self.retryCount += 1 self.refreshToken() } default: print("Received HTTP \(http.statusCode) while fetching stats") self.finish() } } } task.resume() } private func refreshToken() { print("Token is invalid or expired, try to refresh...") SessionManager.shared.refreshToken { self.execute() } } private func parseResponse(data: Data) throws { // We expect the response to look like this: // { stats: { // "contact": 221, // "voicemail": 158, // "unavailable": 32 // }, // weeklyStreak: 10, // firstCallTime: 1487959763 // } guard let statsDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] else { print("Couldn't parse JSON data.") return } userStats = UserStats(dictionary: statsDictionary as JSONDictionary) if let firstCallUnixSeconds = statsDictionary["firstCallTime"] as? Double { firstCallTime = Date(timeIntervalSince1970: firstCallUnixSeconds) } } }
mit
99dd5635128f0b4ff750073331b2cf69
31.237113
123
0.518068
5.211667
false
false
false
false
sjtu-meow/iOS
Meow/SignupViewController.swift
1
2949
// // SignupController.swift // Meow // // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit import AVOSCloud import PKHUD import Moya import RxSwift class SignupViewController: UIViewController { @IBOutlet weak var phoneText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var confirmText: UITextField! @IBOutlet weak var verificationText: UITextField! @IBOutlet weak var verifyButton: UIButton! @IBOutlet weak var signupButton: UIButton! let disposeBag = DisposeBag() var countdown: Int = 5 var timer: Timer! @IBAction func getVerificationCode(_ sender: Any) { verifyButton.isEnabled = false countdown = 5 timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true) AVSMS.sendValidationCode(phoneNumber: "15821883353") { (succeeded, error) in } } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) } func updateCounter(){ if countdown == 0 { timer.invalidate() verifyButton.isEnabled = true } else{ countdown -= 1 verifyButton.setTitle("\(countdown)秒后点击重发", for: UIControlState.disabled) } } @IBAction func signup(_ sender: Any) { guard let password = passwordText.text, let confirm = confirmText.text, let phone = phoneText.text, let verificationCode = verificationText.text else {return} //verify confirm & password consistency if password != confirm{ HUD.flash(.labeledError(title: "密码输入不一致", subtitle: nil), delay: 1) return } //verify verfication code AVOSCloud.verifySmsCode(verificationCode, mobilePhoneNumber: phone){ [weak self] (succeeded, error) in if succeeded{ self?.postSignupForm(phone: phone, password: password, validationCode: verificationCode) } else{ HUD.flash(.labeledError(title: "短信验证码错误", subtitle: nil), delay: 1) return } } } func postSignupForm(phone: String, password: String, validationCode: String) { MeowAPIProvider.shared.request(.signup(phone: phone, password: password, validationCode: validationCode)) .subscribe(onNext:{ [weak self] _ in self?.dismiss(animated: true, completion: nil) UserManager.shared.login(phone: phone, password: password) }) .addDisposableTo(disposeBag) } }
apache-2.0
67105372e49da5908f17ad17992f257f
27.94
133
0.58293
4.905085
false
false
false
false
nando0208/Reach
Reach/View/Sprites/Rocket.swift
2
3015
// // Rocket.swift // Just Touch // // Created by Fernando Ferreira on 4/21/16. // Copyright © 2016 Fernando Ferreira. All rights reserved. // import SpriteKit final class Rocket: SKSpriteNode { fileprivate var speedRocket: CGFloat = 0 var maxSpeedAlpha: CGFloat = -0.1 var minSpeedAlpha: CGFloat = -2.0 var hatch = Hatch() var smoke = SKEmitterNode() var lifes = 3 override init(texture: SKTexture!, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) guard let somkePath = Bundle.main.path(forResource: "SmokeRocket", ofType: "sks"), let smokeNode = NSKeyedUnarchiver.unarchiveObject(withFile: somkePath) as? SKEmitterNode else { return } smokeNode.setScale(CGFloat(0.34)) //Scale of Rocket smokeNode.position = CGPoint(x: self.frame.midX, y: self.frame.minY) addChild(smokeNode) smoke = smokeNode maxSpeedAlpha = smokeNode.particleAlphaSpeed smokeNode.particleAlphaSpeed = minSpeedAlpha addChild(hatch) hatch.zPosition = zPosition + 30 hatch.position = CGPoint(x: self.frame.midX, y: self.frame.height - ( hatch.frame.height / 2 ) - self.frame.height * 0.66 ) hatch.glow.zPosition = hatch.zPosition + 1 physicsBody = SKPhysicsBody(texture: texture, size: size) physicsBody?.categoryBitMask = ObjectsBitMask.rocket.rawValue physicsBody?.contactTestBitMask = ObjectsBitMask.meteor.rawValue physicsBody?.collisionBitMask = 0 physicsBody?.affectedByGravity = false } convenience init() { let texture = SKTexture(imageNamed: "rocket") self.init(texture: texture, color: UIColor.clear, size: texture.size()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSpeedRocket(_ newValue: CGFloat) { if newValue <= maxSpeedRocket && newValue >= minSpeedRocket { speedRocket = newValue smoke.particleAlphaSpeed = minSpeedAlpha - ((minSpeedAlpha - maxSpeedAlpha) * speedRocket / (maxSpeedRocket - 0.2)) } } func removeLife() { lifes -= 1 switch lifes { case 1: hatch.changeToColor(.red) case 2: hatch.changeToColor(.yellow) case 3: hatch.changeToColor(.blue) default: break } } func moveY(_ deltaTime: TimeInterval, size: CGSize) { var rotation = zRotation + .pi let margin = size.width * 0.1 rotation = rotation > 0 ? rotation - .pi : rotation + .pi var newPosition = position newPosition.x -= 340 * rotation * CGFloat(deltaTime) if margin < newPosition.x && newPosition.x < size.width - margin { position = newPosition } } }
mit
b8d02386bf1efd310bfdbe662570ce4a
27.433962
127
0.602853
4.451994
false
false
false
false
relayrides/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/BaseNotificationViewController.swift
1
2349
// // BaseNotificationViewController.swift // Mixpanel // // Created by Yarden Eitan on 8/11/16. // Copyright © 2016 Mixpanel. All rights reserved. // import UIKit protocol NotificationViewControllerDelegate { @discardableResult func notificationShouldDismiss(controller: BaseNotificationViewController, callToActionURL: URL?) -> Bool } class BaseNotificationViewController: UIViewController { var notification: InAppNotification! var delegate: NotificationViewControllerDelegate? var window: UIWindow? var panStartPoint: CGPoint! convenience init(notification: InAppNotification, nameOfClass: String) { self.init(nibName: nameOfClass, bundle: Bundle(for: type(of: self))) self.notification = notification } #if os(iOS) override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .all } override var shouldAutorotate: Bool { return true } #endif func show(animated: Bool) {} func hide(animated: Bool, completion: @escaping () -> Void) {} } extension UIColor { /** The shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #AARRGGBB. - parameter hex4: hexadecimal value. */ public convenience init(hex4: UInt) { let divisor = CGFloat(255) let alpha = CGFloat((hex4 & 0xFF000000) >> 24) / divisor let red = CGFloat((hex4 & 0x00FF0000) >> 16) / divisor let green = CGFloat((hex4 & 0x0000FF00) >> 8) / divisor let blue = CGFloat( hex4 & 0x000000FF ) / divisor self.init(red: red, green: green, blue: blue, alpha: alpha) } /** Add two colors together */ func add(overlay: UIColor) -> UIColor { var bgR: CGFloat = 0 var bgG: CGFloat = 0 var bgB: CGFloat = 0 var bgA: CGFloat = 0 var fgR: CGFloat = 0 var fgG: CGFloat = 0 var fgB: CGFloat = 0 var fgA: CGFloat = 0 self.getRed(&bgR, green: &bgG, blue: &bgB, alpha: &bgA) overlay.getRed(&fgR, green: &fgG, blue: &fgB, alpha: &fgA) let r = fgA * fgR + (1 - fgA) * bgR let g = fgA * fgG + (1 - fgA) * bgG let b = fgA * fgB + (1 - fgA) * bgB return UIColor(red: r, green: g, blue: b, alpha: 1.0) } }
apache-2.0
c0720053290328c61b6cedd6b2f5eb8b
27.634146
109
0.622658
3.946218
false
false
false
false
SuPair/firefox-ios
Storage/SQL/SQLiteLogins.swift
4
39185
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import Deferred private let log = Logger.syncLogger open class SQLiteLogins: BrowserLogins { fileprivate let db: BrowserDB fileprivate static let MainColumns: String = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField" fileprivate static let MainWithLastUsedColumns: String = MainColumns + ", timeLastUsed, timesUsed" fileprivate static let LoginColumns: String = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed" public init(db: BrowserDB) { self.db = db } fileprivate class func populateLogin(_ login: Login, row: SDRow) { login.formSubmitURL = row["formSubmitURL"] as? String login.usernameField = row["usernameField"] as? String login.passwordField = row["passwordField"] as? String login.guid = row["guid"] as! String if let timeCreated = row.getTimestamp("timeCreated"), let timeLastUsed = row.getTimestamp("timeLastUsed"), let timePasswordChanged = row.getTimestamp("timePasswordChanged"), let timesUsed = row["timesUsed"] as? Int { login.timeCreated = timeCreated login.timeLastUsed = timeLastUsed login.timePasswordChanged = timePasswordChanged login.timesUsed = timesUsed } } fileprivate class func constructLogin<T: Login>(_ row: SDRow, c: T.Type) -> T { let credential = URLCredential(user: row["username"] as? String ?? "", password: row["password"] as! String, persistence: .none) // There was a bug in previous versions of the app where we saved only the hostname and not the // scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and // hostname by converting to a URL first. If there is no valid hostname or scheme for the URL, // fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace // to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103. let hostnameString = (row["hostname"] as? String) ?? "" let hostnameURL = hostnameString.asURL let scheme = hostnameURL?.scheme let port = hostnameURL?.port ?? 0 // Check for malformed hostname urls in the DB let host: String var malformedHostname = false if let h = hostnameURL?.host { host = h } else { host = hostnameString malformedHostname = true } let protectionSpace = URLProtectionSpace(host: host, port: port, protocol: scheme, realm: row["httpRealm"] as? String, authenticationMethod: nil) let login = T(credential: credential, protectionSpace: protectionSpace) self.populateLogin(login, row: row) login.hasMalformedHostname = malformedHostname return login } class func LocalLoginFactory(_ row: SDRow) -> LocalLogin { let login = self.constructLogin(row, c: LocalLogin.self) login.localModified = row.getTimestamp("local_modified") ?? 0 login.isDeleted = row.getBoolean("is_deleted") login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)! return login } class func MirrorLoginFactory(_ row: SDRow) -> MirrorLogin { let login = self.constructLogin(row, c: MirrorLogin.self) login.serverModified = row.getTimestamp("server_modified")! login.isOverridden = row.getBoolean("is_overridden") return login } fileprivate class func LoginFactory(_ row: SDRow) -> Login { return self.constructLogin(row, c: Login.self) } fileprivate class func LoginDataFactory(_ row: SDRow) -> LoginData { return LoginFactory(row) as LoginData } fileprivate class func LoginUsageDataFactory(_ row: SDRow) -> LoginUsageData { return LoginFactory(row) as LoginUsageData } func notifyLoginDidChange() { log.debug("Notifying login did change.") // For now we don't care about the contents. // This posts immediately to the shared notification center. NotificationCenter.default.post(name: .DataLoginDidChange, object: nil) } open func getUsageDataForLoginByGUID(_ guid: GUID) -> Deferred<Maybe<LoginUsageData>> { let projection = SQLiteLogins.LoginColumns let sql = """ SELECT \(projection) FROM loginsL WHERE is_deleted = 0 AND guid = ? UNION ALL SELECT \(projection) FROM loginsM WHERE is_overridden = 0 AND guid = ? LIMIT 1 """ let args: Args = [guid, guid] return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory) >>== { value in deferMaybe(value[0]!) } } open func getLoginDataForGUID(_ guid: GUID) -> Deferred<Maybe<Login>> { let projection = SQLiteLogins.LoginColumns let sql = """ SELECT \(projection) FROM loginsL WHERE is_deleted = 0 AND guid = ? UNION ALL SELECT \(projection) FROM loginsM WHERE is_overriden IS NOT 1 AND guid = ? ORDER BY hostname ASC LIMIT 1 """ let args: Args = [guid, guid] return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory) >>== { value in if let login = value[0] { return deferMaybe(login) } else { return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)")) } } } open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> { let projection = SQLiteLogins.MainWithLastUsedColumns let sql = """ SELECT \(projection) FROM loginsL WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ? UNION ALL SELECT \(projection) FROM loginsM WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ? ORDER BY timeLastUsed DESC """ // Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB. // In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without // a scheme. Check for these as well. let args: Args = [ protectionSpace.urlString(), protectionSpace.host, protectionSpace.urlString(), protectionSpace.host, ] if Logger.logPII { log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)") } return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory) } // username is really Either<String, NULL>; we explicitly match no username. open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> { let projection = SQLiteLogins.MainWithLastUsedColumns let args: Args let usernameMatch: String if let username = username { args = [ protectionSpace.urlString(), username, protectionSpace.host, protectionSpace.urlString(), username, protectionSpace.host ] usernameMatch = "username = ?" } else { args = [ protectionSpace.urlString(), protectionSpace.host, protectionSpace.urlString(), protectionSpace.host ] usernameMatch = "username IS NULL" } if Logger.logPII { log.debug("Looking for login with username: \(username ?? "nil"), first arg: \(args[0] ?? "nil")") } let sql = """ SELECT \(projection) FROM loginsL WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ? UNION ALL SELECT \(projection) FROM loginsM WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ? ORDER BY timeLastUsed DESC """ return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory) } open func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> { return searchLoginsWithQuery(nil) } open func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<Login>>> { let projection = SQLiteLogins.LoginColumns var searchClauses = [String]() var args: Args? = nil if let query = query, !query.isEmpty { // Add wildcards to change query to 'contains in' and add them to args. We need 6 args because // we include the where clause twice: Once for the local table and another for the remote. args = (0..<6).map { _ in return "%\(query)%" as String? } searchClauses.append("username LIKE ? ") searchClauses.append(" password LIKE ? ") searchClauses.append(" hostname LIKE ?") } let whereSearchClause = searchClauses.count > 0 ? "AND (" + searchClauses.joined(separator: "OR") + ") " : "" let sql = """ SELECT \(projection) FROM loginsL WHERE is_deleted = 0 \(whereSearchClause) UNION ALL SELECT \(projection) FROM loginsM WHERE is_overridden = 0 \(whereSearchClause) ORDER BY hostname ASC """ return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory) } open func addLogin(_ login: LoginData) -> Success { if let error = login.isValid.failureValue { return deferMaybe(error) } let nowMicro = Date.nowMicroseconds() let nowMilli = nowMicro / 1000 let dateMicro = nowMicro let dateMilli = nowMilli let args: Args = [ login.hostname, login.httpRealm, login.formSubmitURL, login.usernameField, login.passwordField, login.username, login.password, login.guid, dateMicro, // timeCreated dateMicro, // timeLastUsed dateMicro, // timePasswordChanged dateMilli, // localModified ] let sql = """ INSERT OR IGNORE INTO loginsL ( -- Shared fields. hostname, httpRealm, formSubmitURL, usernameField, passwordField, timesUsed, username, password, -- Local metadata. guid, timeCreated, timeLastUsed, timePasswordChanged, local_modified, is_deleted, sync_status ) VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 0, \(SyncStatus.new.rawValue)) """ return db.run(sql, withArgs: args) >>> effect(self.notifyLoginDidChange) } fileprivate func cloneMirrorToOverlay(whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> { let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password " let local = ", local_modified, is_deleted, sync_status " let sql = "INSERT OR IGNORE INTO loginsL (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM loginsM \(whereClause ?? "")" return self.db.write(sql, withArgs: args) } /** * Returns success if either a local row already existed, or * one could be copied from the mirror. */ fileprivate func ensureLocalOverlayExistsForGUID(_ guid: GUID) -> Success { let sql = "SELECT guid FROM loginsL WHERE guid = ?" let args: Args = [guid] let c = db.runQuery(sql, args: args, factory: { _ in 1 }) return c >>== { rows in if rows.count > 0 { return succeed() } log.debug("No overlay; cloning one for GUID \(guid).") return self.cloneMirrorToOverlay(guid) >>== { count in if count > 0 { return succeed() } log.warning("Failed to create local overlay for GUID \(guid).") return deferMaybe(NoSuchRecordError(guid: guid)) } } } fileprivate func cloneMirrorToOverlay(_ guid: GUID) -> Deferred<Maybe<Int>> { let whereClause = "WHERE guid = ?" let args: Args = [guid] return self.cloneMirrorToOverlay(whereClause: whereClause, args: args) } fileprivate func markMirrorAsOverridden(_ guid: GUID) -> Success { let args: Args = [guid] let sql = "UPDATE loginsM SET is_overridden = 1 WHERE guid = ?" return self.db.run(sql, withArgs: args) } /** * Replace the local DB row with the provided GUID. * If no local overlay exists, one is first created. * * If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`. * If it's already `New`, it remains marked as `New`. * * This flag allows callers to make minor changes (such as incrementing a usage count) * without triggering an upload or a conflict. */ open func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success { if let error = new.isValid.failureValue { return deferMaybe(error) } // Right now this method is only ever called if the password changes at // point of use, so we always set `timePasswordChanged` and `timeLastUsed`. // We can (but don't) also assume that `significant` will always be `true`, // at least for the time being. let nowMicro = Date.nowMicroseconds() let nowMilli = nowMicro / 1000 let dateMicro = nowMicro let dateMilli = nowMilli let args: Args = [ dateMilli, // local_modified dateMicro, // timeLastUsed dateMicro, // timePasswordChanged new.httpRealm, new.formSubmitURL, new.usernameField, new.passwordField, new.password, new.hostname, new.username, guid, ] let update = """ UPDATE loginsL SET local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?, httpRealm = ?, formSubmitURL = ?, usernameField = ?, passwordField = ?, timesUsed = timesUsed + 1, password = ?, hostname = ?, username = ? -- We keep rows marked as New in preference to marking them as changed. This allows us to -- delete them immediately if they don't reach the server. \(significant ? ", sync_status = max(sync_status, 1)" : "") WHERE guid = ? """ return self.ensureLocalOverlayExistsForGUID(guid) >>> { self.markMirrorAsOverridden(guid) } >>> { self.db.run(update, withArgs: args) } >>> effect(self.notifyLoginDidChange) } open func addUseOfLoginByGUID(_ guid: GUID) -> Success { let sql = """ UPDATE loginsL SET timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? WHERE guid = ? AND is_deleted = 0 """ // For now, mere use is not enough to flip sync_status to Changed. let nowMicro = Date.nowMicroseconds() let nowMilli = nowMicro / 1000 let args: Args = [nowMicro, nowMilli, guid] return self.ensureLocalOverlayExistsForGUID(guid) >>> { self.markMirrorAsOverridden(guid) } >>> { self.db.run(sql, withArgs: args) } } open func removeLoginByGUID(_ guid: GUID) -> Success { return removeLoginsWithGUIDs([guid]) } fileprivate func getDeletionStatementsForGUIDs(_ guids: ArraySlice<GUID>, nowMillis: Timestamp) -> [(sql: String, args: Args?)] { let inClause = BrowserDB.varlist(guids.count) // Immediately delete anything that's marked as new -- i.e., it's never reached // the server. let delete = "DELETE FROM loginsL WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.new.rawValue)" // Otherwise, mark it as changed. let update = """ UPDATE loginsL SET local_modified = \(nowMillis), sync_status = \(SyncStatus.changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE guid IN \(inClause) """ let markMirrorAsOverridden = "UPDATE loginsM SET is_overridden = 1 WHERE guid IN \(inClause)" let insert = """ INSERT OR IGNORE INTO loginsL ( guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username ) SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM loginsM WHERE guid IN \(inClause) """ let args: Args = guids.map { $0 } return [ (delete, args), (update, args), (markMirrorAsOverridden, args), (insert, args)] } open func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success { let timestamp = Date.now() return db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap { self.getDeletionStatementsForGUIDs($0, nowMillis: timestamp) }) >>> effect(self.notifyLoginDidChange) } open func removeAll() -> Success { // Immediately delete anything that's marked as new -- i.e., it's never reached // the server. If Sync isn't set up, this will be everything. let delete = "DELETE FROM loginsL WHERE sync_status = \(SyncStatus.new.rawValue)" let nowMillis = Date.now() // Mark anything we haven't already deleted. let update = "UPDATE loginsL SET local_modified = \(nowMillis), sync_status = \(SyncStatus.changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0" // Copy all the remaining rows from our mirror, marking them as locally deleted. The // OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving // anything we already deleted. let insert = """ INSERT OR IGNORE INTO loginsL ( guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username ) SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM loginsM """ // After that, we mark all of the mirror rows as overridden. return self.db.run(delete) >>> { self.db.run(update) } >>> { self.db.run("UPDATE loginsM SET is_overridden = 1") } >>> { self.db.run(insert) } >>> effect(self.notifyLoginDidChange) } } // When a server change is detected (e.g., syncID changes), we should consider shifting the contents // of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next // full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and // resolve the remainder on completion. This assumes that a fresh start will typically end up with // the exact same records, so we might as well keep the shared parents around and double-check. extension SQLiteLogins: SyncableLogins { /** * Delete the login with the provided GUID. Succeeds if the GUID is unknown. */ public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success { // Simply ignore the possibility of a conflicting local change for now. let local = "DELETE FROM loginsL WHERE guid = ?" let remote = "DELETE FROM loginsM WHERE guid = ?" let args: Args = [guid] return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) } } func getExistingMirrorRecordByGUID(_ guid: GUID) -> Deferred<Maybe<MirrorLogin?>> { let sql = "SELECT * FROM loginsM WHERE guid = ? LIMIT 1" let args: Args = [guid] return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) } } func getExistingLocalRecordByGUID(_ guid: GUID) -> Deferred<Maybe<LocalLogin?>> { let sql = "SELECT * FROM loginsL WHERE guid = ? LIMIT 1" let args: Args = [guid] return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) } } fileprivate func storeReconciledLogin(_ login: Login) -> Success { let dateMilli = Date.now() let args: Args = [ dateMilli, // local_modified login.httpRealm, login.formSubmitURL, login.usernameField, login.passwordField, login.timeLastUsed, login.timePasswordChanged, login.timesUsed, login.password, login.hostname, login.username, login.guid, ] let update = """ UPDATE loginsL SET local_modified = ?, httpRealm = ?, formSubmitURL = ?, usernameField = ?, passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?, password = ?, hostname = ?, username = ?, sync_status = \(SyncStatus.changed.rawValue) WHERE guid = ? """ return self.db.run(update, withArgs: args) } public func applyChangedLogin(_ upstream: ServerLogin) -> Success { // Our login storage tracks the shared parent from the last sync (the "mirror"). // This allows us to conclusively determine what changed in the case of conflict. // // Our first step is to determine whether the record is changed or new: i.e., whether // or not it's present in the mirror. // // TODO: these steps can be done in a single query. Make it work, make it right, make it fast. // TODO: if there's no mirror record, all incoming records can be applied in one go; the only // reason we need to fetch first is to establish the shared parent. That would be nice. let guid = upstream.guid return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in return self.getExistingLocalRecordByGUID(guid) >>== { local in return self.applyChangedLogin(upstream, local: local, mirror: mirror) } } } fileprivate func applyChangedLogin(_ upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success { // Once we have the server record, the mirror record (if any), and the local overlay (if any), // we can always know which state a record is in. // If it's present in the mirror, then we can proceed directly to handling the change; // we assume that once a record makes it into the mirror, that the local record association // has already taken place, and we're tracking local changes correctly. if let mirror = mirror { log.debug("Mirror record found for changed record \(mirror.guid).") if let local = local { log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.") // * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the // local mirror is the shared parent of both the local overlay and the new remote record. // Apply results as in the co-creation case. return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror) } log.debug("No local overlay found. Updating mirror to upstream.") // * Changed remotely but not locally. Apply the remote changes to the mirror. // There is no local overlay to discard or resolve against. return self.updateMirrorToLogin(upstream, fromPrevious: mirror) } // * New both locally and remotely with no shared parent (cocreation). // Or we matched the GUID, and we're assuming we just forgot the mirror. // // Merge and apply the results remotely, writing the result into the mirror and discarding the overlay // if the upload succeeded. (Doing it in this order allows us to safely replay on failure.) // // If the local and remote record are the same, this is trivial. // At this point we also switch our local GUID to match the remote. if let local = local { // We might have randomly computed the same GUID on two devices connected // to the same Sync account. // With our 9-byte GUIDs, the chance of that happening is very small, so we // assume that this device has previously connected to this account, and we // go right ahead with a merge. log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.") return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream) } // If it's not present, we must first check whether we have a local record that's substantially // the same -- the co-creation or re-sync case. // // In this case, we apply the server record to the mirror, change the local record's GUID, // and proceed to reconcile the change on a content basis. return self.findLocalRecordByContent(upstream) >>== { local in if let local = local { log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.") return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream) } // * New upstream only; no local overlay, content-based merge, // or shared parent in the mirror. Insert it in the mirror. log.debug("Never seen remote record \(upstream.guid). Mirroring.") return self.insertNewMirror(upstream) } } // N.B., the final guid is sometimes a WHERE and sometimes inserted. fileprivate func mirrorArgs(_ login: ServerLogin) -> Args { let args: Args = [ login.serverModified, login.httpRealm, login.formSubmitURL, login.usernameField, login.passwordField, login.timesUsed, login.timeLastUsed, login.timePasswordChanged, login.timeCreated, login.password, login.hostname, login.username, login.guid, ] return args } /** * Called when we have a changed upstream record and no local changes. * There's no need to flip the is_overridden flag. */ fileprivate func updateMirrorToLogin(_ login: ServerLogin, fromPrevious previous: Login) -> Success { let args = self.mirrorArgs(login) let sql = """ UPDATE loginsM SET server_modified = ?, httpRealm = ?, formSubmitURL = ?, usernameField = ?, passwordField = ?, -- These we need to coalesce, because we might be supplying zeroes if the remote has -- been overwritten by an older client. In this case, preserve the old value in the -- mirror. timesUsed = coalesce(nullif(?, 0), timesUsed), timeLastUsed = coalesce(nullif(?, 0), timeLastUsed), timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged), timeCreated = coalesce(nullif(?, 0), timeCreated), password = ?, hostname = ?, username = ? WHERE guid = ? """ return self.db.run(sql, withArgs: args) } /** * Called when we have a completely new record. Naturally the new record * is marked as non-overridden. */ fileprivate func insertNewMirror(_ login: ServerLogin, isOverridden: Int = 0) -> Success { let args = self.mirrorArgs(login) let sql = """ INSERT OR IGNORE INTO loginsM ( is_overridden, server_modified, httpRealm, formSubmitURL, usernameField, passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated, password, hostname, username, guid ) VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """ return self.db.run(sql, withArgs: args) } /** * We assume a local record matches if it has the same username (password can differ), * hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the * same host and port. * * This is roughly the same as desktop's .matches(): * <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41> */ fileprivate func findLocalRecordByContent(_ login: Login) -> Deferred<Maybe<LocalLogin?>> { let primary = "SELECT * FROM loginsL WHERE hostname IS ? AND httpRealm IS ? AND username IS ?" var args: Args = [login.hostname, login.httpRealm, login.username] let sql: String if login.formSubmitURL == nil { sql = primary + " AND formSubmitURL IS NULL" } else if login.formSubmitURL!.isEmpty { sql = primary } else { if let hostPort = login.formSubmitURL?.asURL?.hostPort { // Substring check will suffice for now. TODO: proper host/port check after fetching the cursor. sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))" args.append(hostPort) } else { log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.") return deferMaybe(nil) } } return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { cursor in switch cursor.count { case 0: return deferMaybe(nil) case 1: // Great! return deferMaybe(cursor[0]) default: // TODO: join against the mirror table to exclude local logins that // already match a server record. // Right now just take the first. log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.") return deferMaybe(cursor[0]) } } } fileprivate func resolveConflictBetween(local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success { // Attempt to compute two delta sets by comparing each new record to the shared record. // Then we can merge the two delta sets -- either perfectly or by picking a winner in the case // of a true conflict -- and produce a resultant record. let localDeltas = (local.localModified, local.deltas(from: shared)) let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared)) let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas) // Not all Sync clients handle the optional timestamp fields introduced in Bug 555755. // We might get a server record with no timestamps, and it will differ from the original // mirror! // We solve that by refusing to generate deltas that discard information. We'll preserve // the local values -- either from the local record or from the last shared parent that // still included them -- and propagate them back to the server. // It's OK for us to reconcile and reupload; it causes extra work for every client, but // should not cause looping. let resultant = shared.applyDeltas(mergedDeltas) // We can immediately write the downloaded upstream record -- the old one -- to // the mirror store. // We then apply this record to the local store, and mark it as needing upload. // When the reconciled record is uploaded, it'll be flushed into the mirror // with the correct modified time. return self.updateMirrorToLogin(upstream, fromPrevious: shared) >>> { self.storeReconciledLogin(resultant) } } fileprivate func resolveConflictWithoutParentBetween(local: LocalLogin, upstream: ServerLogin) -> Success { // Do the best we can. Either the local wins and will be // uploaded, or the remote wins and we delete our overlay. if local.timePasswordChanged > upstream.timePasswordChanged { log.debug("Conflicting records with no shared parent. Using newer local record.") return self.insertNewMirror(upstream, isOverridden: 1) } log.debug("Conflicting records with no shared parent. Using newer remote record.") let args: Args = [local.guid] return self.insertNewMirror(upstream, isOverridden: 0) >>> { self.db.run("DELETE FROM loginsL WHERE guid = ?", withArgs: args) } } public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> { let sql = "SELECT * FROM loginsL WHERE sync_status IS NOT \(SyncStatus.synced.rawValue) AND is_deleted = 0" // Swift 2.0: use Cursor.asArray directly. return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory) >>== { deferMaybe($0.asArray()) } } public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> { // There are no logins that are marked as deleted that were not originally synced -- // others are deleted immediately. let sql = "SELECT guid FROM loginsL WHERE is_deleted = 1" // Swift 2.0: use Cursor.asArray directly. return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID }) >>== { deferMaybe($0.asArray()) } } /** * Chains through the provided timestamp. */ public func markAsSynchronized<T: Collection>(_ guids: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> where T.Iterator.Element == GUID { // Update the mirror from the local record that we just uploaded. // sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs, // we issue a single DELETE and a single INSERT on the mirror, then throw away the // local overlay that we just uploaded with another DELETE. log.debug("Marking \(guids.count) GUIDs as synchronized.") let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let inClause = BrowserDB.varlist(args.count) let delMirror = "DELETE FROM loginsM WHERE guid IN \(inClause)" let insMirror = """ INSERT OR IGNORE INTO loginsM ( is_overridden, server_modified, httpRealm, formSubmitURL, usernameField, passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated, password, hostname, username, guid ) SELECT 0, \(modified), httpRealm, formSubmitURL, usernameField, passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated, password, hostname, username, guid FROM loginsL WHERE guid IN \(inClause) """ let delLocal = "DELETE FROM loginsL WHERE guid IN \(inClause)" return [(delMirror, args), (insMirror, args), (delLocal, args)] } return self.db.run(queries) >>> always(modified) } public func markAsDeleted<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { log.debug("Marking \(guids.count) GUIDs as deleted.") let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in let args: Args = guids.map { $0 } let inClause = BrowserDB.varlist(args.count) return [("DELETE FROM loginsM WHERE guid IN \(inClause)", args), ("DELETE FROM loginsL WHERE guid IN \(inClause)", args)] } return self.db.run(queries) } public func hasSyncedLogins() -> Deferred<Maybe<Bool>> { let checkLoginsMirror = "SELECT 1 FROM loginsM" let checkLoginsLocal = "SELECT 1 FROM loginsL WHERE sync_status IS NOT \(SyncStatus.new.rawValue)" let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)" return self.db.queryReturnsResults(sql) } } extension SQLiteLogins: ResettableSyncStorage { /** * Clean up any metadata. * TODO: is this safe for a regular reset? It forces a content-based merge. */ public func resetClient() -> Success { // Clone all the mirrors so we don't lose data. return self.cloneMirrorToOverlay(whereClause: nil, args: nil) // Drop all of the mirror data. >>> { self.db.run("DELETE FROM loginsM") } // Mark all of the local data as new. >>> { self.db.run("UPDATE loginsL SET sync_status = \(SyncStatus.new.rawValue)") } } } extension SQLiteLogins: AccountRemovalDelegate { public func onRemovedAccount() -> Success { return self.resetClient() } }
mpl-2.0
0628a996be92cd40baef60baf41ff623
41.408009
190
0.59533
5.009588
false
false
false
false
SnappedCoffee/UnitTestViewControllerWithSwiftMiniTutorial
UnitTestViewControllerWithSwiftMiniTutorialTests/UnitTestViewControllerWithSwiftMiniTutorialTests.swift
1
2364
// // UnitTestViewControllerWithSwiftMiniTutorialTests.swift // UnitTestViewControllerWithSwiftMiniTutorialTests // // Created by SnappedCoffee on 02.01.15. // Copyright (c) 2015 SnappedCoffee. All rights reserved. // import UIKit import XCTest // Important: Import the project module import UnitTestViewControllerWithSwiftMiniTutorial class UnitTestViewControllerWithSwiftMiniTutorialTests: XCTestCase { // Important: create a variable for the view controller outside of setup(). Otherwise the variable is not available to the test functions var vc:ViewController = ViewController() override func setUp() { super.setUp() /* Set up the storyboard with the view controller. Source: http://www.iosmike.com/2014/08/unit-testing-viewcontrollers-in-swift.html Important: set the Storyboard ID to the same value as in instantiateViewControllerWithIdentifier() (e.g. MyStoryboard). Here is how: open the storyboard, select the view controller in the storyboard, select the identity inspector tab in the right inspector and finally set the Storyboard ID property in the right inspector) */ var storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType)) vc = storyboard.instantiateViewControllerWithIdentifier("MyStoryboard") as ViewController vc.loadView() vc.viewDidLoad() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testViewDidLoad() { // assert that the ViewController.view is not nil XCTAssertNotNil(vc.view, "View Did Not load") } func testMyLabelTextDidLoad() { // assert that myLabel was set to "Hello World" when viewDidLoad XCTAssertTrue(vc.myLabel.text == "Hello World", "myLabel is not set to 'Hello World', but to \(vc.myLabel.text)") } func testMyButtonPressedChangesMyLabel() { // assert that myLabel is set to "Button has been pressed", when myButton has been pressed vc.myButtonPressed(vc.myButton) XCTAssertTrue(vc.myLabel.text == "Button has been pressed", "myLabel is not set to 'Button has been pressed', but to \(vc.myLabel.text)") } }
mit
7433ade6bbc3429b048b28e686464535
41.214286
331
0.703892
4.864198
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/General/Crypto/AESCryptor.swift
1
4814
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import CryptoSwift import Foundation struct AESOptions { enum BlockMode { case CBC case OFB fileprivate func cryptoSwiftBlockMode(iv: [UInt8]) -> CryptoSwift.BlockMode { switch self { case .CBC: return CryptoSwift.CBC(iv: iv) case .OFB: return CryptoSwift.OFB(iv: iv) } } } enum Padding { case iso10126 case iso78164 case noPadding fileprivate var cryptoSwiftPadding: CryptoSwift.Padding { switch self { case .iso10126: return .iso10126 case .iso78164: return .iso78164 case .noPadding: return .noPadding } } } static let `default` = AESOptions( blockMode: .CBC, padding: .iso10126 ) let blockMode: BlockMode let padding: Padding } enum AESCryptorError: Error { case encoding case configuration(Error) case decryption(Error) } protocol AESCryptorAPI { func decryptUTF8String( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions ) -> Result<String, AESCryptorError> func decrypt( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions ) -> Result<[UInt8], AESCryptorError> func encrypt( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions ) -> Result<[UInt8], AESCryptorError> } extension AESCryptorAPI { func decryptUTF8String( data payloadData: Data, with keyData: Data, iv ivData: Data ) -> Result<String, AESCryptorError> { decryptUTF8String( data: payloadData, with: keyData, iv: ivData, options: .default ) } func decrypt( data payloadData: Data, with keyData: Data, iv ivData: Data ) -> Result<[UInt8], AESCryptorError> { decrypt( data: payloadData, with: keyData, iv: ivData, options: .default ) } func encrypt( data payloadData: Data, with keyData: Data, iv ivData: Data ) -> Result<[UInt8], AESCryptorError> { encrypt( data: payloadData, with: keyData, iv: ivData, options: .default ) } } final class AESCryptor: AESCryptorAPI { func decryptUTF8String( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions = .default ) -> Result<String, AESCryptorError> { decrypt(data: payloadData, with: keyData, iv: ivData, options: options) .map { Data($0) } .flatMap { decryptedData -> Result<String, AESCryptorError> in guard let decryptedString = String(data: decryptedData, encoding: .utf8) else { return .failure(AESCryptorError.encoding) } return .success(decryptedString) } } func decrypt( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions = .default ) -> Result<[UInt8], AESCryptorError> { let key: [UInt8] = keyData.bytes let iv: [UInt8] = ivData.bytes let pad = options.padding.cryptoSwiftPadding let blockMode = options.blockMode.cryptoSwiftBlockMode(iv: iv) let encrypted: [UInt8] = payloadData.bytes return Result { try AES(key: key, blockMode: blockMode, padding: pad) } .mapError(AESCryptorError.configuration) .flatMap { aes -> Result<[UInt8], AESCryptorError> in Result { try aes.decrypt(encrypted) } .mapError(AESCryptorError.decryption) } } func encrypt( data payloadData: Data, with keyData: Data, iv ivData: Data, options: AESOptions = .default ) -> Result<[UInt8], AESCryptorError> { let key: [UInt8] = keyData.bytes let iv: [UInt8] = ivData.bytes let payload: [UInt8] = payloadData.bytes let pad = options.padding.cryptoSwiftPadding let blockMode = options.blockMode.cryptoSwiftBlockMode(iv: iv) return Result { try AES(key: key, blockMode: blockMode, padding: pad) } .mapError(AESCryptorError.configuration) .flatMap { aes -> Result<[UInt8], AESCryptorError> in Result { try aes.encrypt(payload) } .mapError(AESCryptorError.decryption) } } }
lgpl-3.0
6f8324d2c4c511aa3869f10a802ec04b
26.502857
95
0.563058
4.43186
false
false
false
false
swifttime/SwiftlyReachable
SwiftlyReachableDemo/ViewController.swift
1
2217
// // ViewController.swift // SwiftlyReachableDemo // // Created by Rick Windham on 2/4/15. // Copyright (c) 2015 SwiftTime. All rights reserved. // import UIKit import SwiftlyReachable class ViewController: UIViewController { // MARK: - outlets @IBOutlet weak var flagsLabel: UILabel! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var monitorButton: UIButton! // MARK: - properties let reachability = STReachability() // MARK: - lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. reachability.changedBlock = {[weak self] status in if let strongSelf = self { strongSelf.flagsLabel.text = strongSelf.reachability.binaryFlags strongSelf.statusLabel.text = strongSelf.statusString(status) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) updateStatus() } // MARK: - actions @IBAction func monitorAction(sender: AnyObject) { if reachability.isMonitoring { reachability.startMonitor() monitorButton.setTitle("Start", forState: .Normal) } else { if reachability.startMonitor() { monitorButton.setTitle("Stop", forState: .Normal) } } } @IBAction func getStatusAction(sender: AnyObject) { updateStatus() } // MARK: - functions func updateStatus() { flagsLabel.text = reachability.binaryFlags statusLabel.text = statusString(reachability.getStatus()) } func statusString(status:STReachability.Status) -> String { switch (status) { case (.ViaCellData): return "Cell Data" case (.ViaWiFi): return "WiFi" case (.Unknown): return "Unknown" default: return "None" } } }
mit
6742016bd6521e2c315959ac074871c0
24.193182
80
0.59134
5.084862
false
false
false
false
blue42u/swift-t
turbine/code/export/location.swift
1
1752
/* Helper functions for dealing with locations */ @pure (location loc) rank2location(int rank) { loc = location(rank, HARD, RANK); } @pure (location loc) locationFromRank(int rank) { loc = location(rank, HARD, RANK); } /* deprecated: old naming scheme */ @pure (location loc) location_from_rank(int rank) { loc = locationFromRank(rank); } (location loc) randomWorker() { loc = locationFromRank(randomWorkerRank()); } /* deprecated: old naming scheme */ (location loc) random_worker() { loc = randomWorker(); } (int rank) randomWorkerRank() "turbine" "0.1.1" [ "set <<rank>> [ ::turbine::random_worker ]" ]; /* deprecated: no longer engine/worker distinction */ (location loc) random_engine() { loc = random_worker(); } (location loc) hostmapOne(string name) { loc = locationFromRank(hostmapOneRank(name)); } /* deprecated: old naming scheme */ (location loc) hostmap_one(string name) { loc = hostmapOne(name); } (int rank) hostmapOneRank(string name) "turbine" "0.0.2" [ "set <<rank>> [ draw [ adlb::hostmap_lookup <<name>> ] ]" ]; (location loc) hostmapOneWorker(string name) { loc = locationFromRank(hostmapOneWorkerRank(name)); } /* deprecated: old naming scheme */ (location loc) hostmap_one_worker(string name) { loc = hostmapOneWorker(name); } (int rank) hostmapOneWorkerRank(string name) "turbine" "0.0.2" [ "set <<rank>> [ ::turbine::random_rank WORKER [ adlb::hostmap_lookup <<name>> ] ]" ]; /* List available hosts Pure because it will be same throughout the run */ (string results[]) hostmapList() "turbine" "0.7.0" [ "set <<results>> [ ::turbine::hostmap_list ]" ]; /* deprecated: old naming scheme */ (string results[]) hostmap_list() { results = hostmapList(); }
apache-2.0
3ca509da73e334f3023a366046e0b72e
19.137931
86
0.664954
3.095406
false
false
false
false
AugustRush/Stellar
StellarDemo/StellarDemo/Example8ViewController.swift
1
3831
// // Example8ViewController.swift // StellarDemo // // Created by AugustRush on 6/29/16. // Copyright © 2016 August. All rights reserved. // import UIKit class Example8ViewController: UIViewController { @IBOutlet weak var animateView: Ball! @IBAction func segment1ValueChanged(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.default).reverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.easeIn).reverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.easeOut).reverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.easeInEaseOut).reverses().animate() default: print("") } } @IBAction func segment2ValueChanged(_ sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.linear).reverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.swiftOut).reverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.backEaseIn).reverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.backEaseOut).reverses().animate() default: print("") } } @IBAction func segment3ValueChanged(_ sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.backEaseInOut).reverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.bounceOut).reverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.sine).reverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.circ).reverses().animate() default: print("") } } @IBAction func segment4ValueChanged(_ sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.exponentialIn).reverses().animate() case 1: animateView.moveX(200).duration(1.0).easing(.exponentialOut).reverses().animate() case 2: animateView.moveX(200).duration(1.0).easing(.elasticIn).reverses().animate() case 3: animateView.moveX(200).duration(1.0).easing(.elasticOut).reverses().animate() default: print("") } } @IBAction func segment5ValueChanged(_ sender: UISegmentedControl) { animateView.frame = CGRect(x: 20,y: 120,width: 40,height: 40) let index = sender.selectedSegmentIndex; switch index { case 0: animateView.moveX(200).duration(1.0).easing(.bounceReverse).reverses().animate() case 1: 100.0.animate(to: 200, duration: 1.0, delay: 0.0, type: .swiftOut, autoreverses: false, repeatCount: 0, render: { (d) in print("current value is \(d)") }, completion: nil) case 2: 100.0.attachment(to: 200, render: { (d) in print("current value is \(d)") }) case 3: fallthrough default: print("") } } }
mit
556a892a46c100dc3bd39876d4bd9eec
33.504505
132
0.57624
4.213421
false
false
false
false
Brightify/Reactant
Source/Core/View/Impl/TextField.swift
2
6341
// // TextField.swift // Reactant // // Created by Tadeas Kriz on 5/2/17. // Copyright © 2017 Brightify. All rights reserved. // import RxSwift import RxOptional public enum TextInputState { case string(String) case attributedString(NSAttributedString) } extension TextInputState: TextInputStateConvertible { public func asTextInputState() -> TextInputState { return self } } public protocol TextInputStateConvertible { func asTextInputState() -> TextInputState } extension TextInputStateConvertible { public func asString() -> String { switch asTextInputState() { case .string(let string): return string case .attributedString(let attributedString): return attributedString.string } } public func asAttributedString() -> NSAttributedString { switch asTextInputState() { case .string(let string): return string.attributed() case .attributedString(let attributedString): return attributedString } } } extension String: TextInputStateConvertible { public func asTextInputState() -> TextInputState { return .string(self) } } extension NSAttributedString: TextInputStateConvertible { public func asTextInputState() -> TextInputState { return .attributedString(self) } } open class TextField: UITextField, ComponentWithDelegate, Configurable { public typealias StateType = TextInputStateConvertible public typealias ActionType = String public let lifetimeDisposeBag = DisposeBag() public let componentDelegate = ComponentDelegate<TextInputStateConvertible, String, TextField>() open var actions: [Observable<String>] { return [ rx.text.skip(1).replaceNilWith("") ] } open var action: Observable<String> { return componentDelegate.action } open var configuration: Configuration = .global { didSet { layoutMargins = configuration.get(valueFor: Properties.layoutMargins) configuration.get(valueFor: Properties.Style.textField)(self) } } open override class var requiresConstraintBasedLayout: Bool { return true } @objc open var contentEdgeInsets: UIEdgeInsets = .zero open override var text: String? { didSet { componentState = text ?? "" } } open override var attributedText: NSAttributedString? { didSet { componentState = attributedText ?? NSAttributedString() } } @objc open var placeholderColor: UIColor? = nil { didSet { updateAttributedPlaceholder() } } @objc open var placeholderFont: UIFont? = nil { didSet { updateAttributedPlaceholder() } } open var placeholderAttributes: [Attribute] = [] { didSet { updateAttributedPlaceholder() } } override open var placeholder: String? { didSet { updateAttributedPlaceholder() } } #if ENABLE_SAFEAREAINSETS_FALLBACK open override var frame: CGRect { didSet { fallback_computeSafeAreaInsets() } } open override var bounds: CGRect { didSet { fallback_computeSafeAreaInsets() } } open override var center: CGPoint { didSet { fallback_computeSafeAreaInsets() } } #endif public init() { super.init(frame: CGRect.zero) componentDelegate.ownerComponent = self translatesAutoresizingMaskIntoConstraints = false if let reactantUi = self as? ReactantUI { reactantUi.__rui.setupReactantUI() } loadView() setupConstraints() resetActions() reloadConfiguration() afterInit() componentState = "" componentDelegate.canUpdate = true } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { if let reactantUi = self as? ReactantUI { type(of: reactantUi.__rui).destroyReactantUI(target: self) } } open func afterInit() { } open func update() { let oldSelectedRange = selectedTextRange switch componentState.asTextInputState() { case .string(let string): // We have to set `super.text` because setting `self.text` would set componentState and call this method again super.text = string case .attributedString(let attributedString): // We have to set `super.attributedText` because setting `self.attributedText` would set componentState and call this method again super.attributedText = attributedString } selectedTextRange = oldSelectedRange } public func observeState(_ when: ObservableStateEvent) -> Observable<TextInputStateConvertible> { return componentDelegate.observeState(when) } open func loadView() { } open func setupConstraints() { } open func needsUpdate() -> Bool { return true } open override func textRect(forBounds bounds: CGRect) -> CGRect { let superBounds = super.textRect(forBounds: bounds) return superBounds.inset(by: contentEdgeInsets) } open override func editingRect(forBounds bounds: CGRect) -> CGRect { let superBounds = super.editingRect(forBounds: bounds) return superBounds.inset(by: contentEdgeInsets) } private func updateAttributedPlaceholder() { guard let placeholder = placeholder else { return } var attributes = placeholderAttributes if let placeholderColor = placeholderColor { attributes.append(.foregroundColor(placeholderColor)) } if let placeholderFont = placeholderFont { attributes.append(.font(placeholderFont)) } if attributes.isEmpty { // We have to set `super.placeholder` because setting `self.placeholder` would call this method again super.placeholder = placeholder } else { attributedPlaceholder = placeholder.attributed(attributes) } } }
mit
f9e1773512ba9b1b231dcb162465dd87
24.772358
142
0.635174
5.270158
false
false
false
false
Meeca/IQKeyboardManager
KeyboardTextFieldDemo/IQKeyboardManager Swift/TableViewInContainerViewController.swift
19
1750
// // TableViewInContainerViewController.swift // IQKeyboardManager // // Created by InfoEnum02 on 20/04/15. // Copyright (c) 2015 Iftekhar. All rights reserved. // import UIKit class TableViewInContainerViewController: UIViewController , UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = "TestCell" var cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier) cell?.backgroundColor = UIColor.clearColor() let contentView : UIView! = cell?.contentView let textField = UITextField(frame: CGRectMake(10,0,contentView.frame.size.width-20,33)) textField.autoresizingMask = UIViewAutoresizing.FlexibleBottomMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleWidth textField.center = contentView.center; textField.backgroundColor = UIColor.clearColor() textField.borderStyle = UITextBorderStyle.RoundedRect textField.tag = 123 cell?.contentView.addSubview(textField) } let textField : UITextField = cell!.viewWithTag(123) as! UITextField; textField.placeholder = "Cell \(indexPath.row)" return cell! } override func shouldAutorotate() -> Bool { return true } }
mit
78e244607eac0cf64de6a5ade8c62404
34.714286
154
0.669143
5.872483
false
false
false
false
nitrado/NitrAPI-Swift
Pod/Classes/common/http/ProductionHttpClient.swift
1
5574
import Just open class ProductionHttpClient { fileprivate var nitrapiUrl: String fileprivate var accessToken: String fileprivate var locale: String? = nil open fileprivate(set) var rateLimit: Int = 0 open fileprivate(set) var rateLimitRemaining: Int = 0 open fileprivate(set) var rateLimitReset: Int = 0 open var additionalHeaders: [String:String] = [:] public init (nitrapiUrl: String, accessToken: String) { self.nitrapiUrl = nitrapiUrl self.accessToken = accessToken } open func setLanguage(_ lang: String) { locale = lang } // MARK: - HTTP Operations /// send a GET request open func dataGet(_ url: String, parameters: Dictionary<String, Any?>) throws -> NSDictionary? { var params = parameters additionalHeaders["Authorization"] = "Bearer " + accessToken let res = Just.get(nitrapiUrl + url, params: removeEmptyParameters(params), headers: additionalHeaders) return try parseResult(res) } /// send a POST request open func dataPost(_ url: String,parameters: Dictionary<String, Any?>) throws -> NSDictionary? { additionalHeaders["Authorization"] = "Bearer " + accessToken let res = Just.post(nitrapiUrl + url, params: ["locale": locale ?? "en"], data: removeEmptyParameters(parameters), headers: additionalHeaders) return try parseResult(res) } /// send a PUT request open func dataPut(_ url: String,parameters: Dictionary<String, Any?>) throws -> NSDictionary? { additionalHeaders["Authorization"] = "Bearer " + accessToken let res = Just.put(nitrapiUrl + url, params: ["locale": locale ?? "en"], data: removeEmptyParameters(parameters), headers: additionalHeaders) return try parseResult(res) } /// send a DELETE request open func dataDelete(_ url: String, parameters: Dictionary<String, Any?>) throws -> NSDictionary? { additionalHeaders["Authorization"] = "Bearer " + accessToken let res = Just.delete(nitrapiUrl + url, params: ["locale": locale ?? "en"], data: removeEmptyParameters(parameters), headers: additionalHeaders) return try parseResult(res) } func removeEmptyParameters(_ parameters: Dictionary<String, Any?>) -> Dictionary<String, Any> { var result: Dictionary<String, Any> = [:] for (name, value) in parameters { if let value = value { result[name] = value } } return result } open func parseResult(_ res: HTTPResult) throws -> NSDictionary? { // get rate limit if res.headers["X-RateLimit-Limit"] != nil { rateLimit = Int(res.headers["X-RateLimit-Limit"]!)! rateLimitRemaining = Int(res.headers["X-RateLimit-Remaining"]!)! rateLimitReset = Int(res.headers["X-RateLimit-Reset"]!)! } var errorId: String? = nil if res.headers["X-Raven-Event-ID"] != nil { errorId = res.headers["X-Raven-Event-ID"] } if res.response == nil { throw NitrapiError.httpException(statusCode: res.statusCode ?? -1) } let parsedObject: Any? = try JSONSerialization.jsonObject(with: res.text!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments) var message: String = "Unknown error." if let result = parsedObject as? NSDictionary { if let status = result["status"] as? String { if status == "error" { message = result["message"] as! String } else { if let data = result["data"] as? NSDictionary { return data } else if let message = result["message"] as? String { return ["message": message] } } } } if let statusCode = res.statusCode { switch statusCode { case 401: if let result = parsedObject as? NSDictionary { if let data = result["data"] as? NSDictionary { if let error_code = data["error_code"] as? String { if error_code.starts(with: "access_token_") { throw NitrapiError.nitrapiAccessTokenInvalidException(message: message) } } } } throw NitrapiError.nitrapiException(message: message, errorId: errorId) case 428: throw NitrapiError.nitrapiConcurrencyException(message: message) case 503: throw NitrapiError.nitrapiMaintenanceException(message: message) default: throw NitrapiError.nitrapiException(message: message, errorId: errorId) } } throw NitrapiError.httpException(statusCode: res.statusCode ?? -1) } /// send a POST request with content open func rawPost(_ url: String, token: String, body: Data) throws { let res = Just.post(url, params: [:], headers: ["Token": token, "Content-Type": "application/binary"], requestBody: body ) if !res.ok { throw NitrapiError.httpException(statusCode: res.statusCode ?? -1) } } }
mit
2534ab899fad410eb923c9d1376e0ce9
37.441379
175
0.571224
4.928382
false
false
false
false
muneebm/AsterockX
AsterockX/SettingsViewController.swift
1
4102
// // SettingsViewController.swift // AsterockX // // Created by Muneeb Rahim Abdul Majeed on 1/16/16. // Copyright © 2016 beenum. All rights reserved. // import UIKit class SettingsViewController: UITableViewController { struct Constants { static let DiameterUnit = "Diameter Unit" static let VelocityUnit = "Velocity Unit" static let DistanceUnit = "Distance Unit" static let ShowUnitPickerSegueId = "ShowUnitPicker" } let unitTypes = [ Constants.DiameterUnit : [("km - kilometers" , Settings.Constants.Kilometers), ("m - meters" , Settings.Constants.Meters), ("mi - miles" , Settings.Constants.Miles), ("ft - feet" , Settings.Constants.Feet)], Constants.VelocityUnit : [("kps - kilometers per second" , Settings.Constants.KilometersPerSecond), ("kph - kilometers per hour" , Settings.Constants.KilometersPerHours), ("mph - miles per hour" , Settings.Constants.MilesPerHour)], Constants.DistanceUnit : [("au - astronomical unit" , Settings.Constants.Astronomical), ("ld - lunar distance" , Settings.Constants.Lunar), ("km - kilometers" , Settings.Constants.Kilometers), ("mi - miles" , Settings.Constants.Miles)] ] var selectedUnitType: (String?, String?)? override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if let text = cell.textLabel?.text { cell.detailTextLabel?.text = getUnitForMeasurement(text) } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath)! selectedUnitType = (cell.textLabel?.text, cell.detailTextLabel?.text) performSegueWithIdentifier(Constants.ShowUnitPickerSegueId, sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) if segue.identifier == Constants.ShowUnitPickerSegueId, let selectedUnit = selectedUnitType?.0, let units = unitTypes[selectedUnit], let unit = selectedUnitType?.1 { let pvc = segue.destinationViewController as? PickerViewController pvc?.delegate = self pvc?.initialSelectedItem = unit pvc?.items = units.map( { $0.0 } ) } } func getUnitForMeasurement(measurement: String?) -> String? { var unitDescription: String? if let measurement = measurement, let units = unitTypes[measurement] { var unit: String? switch measurement { case Constants.DiameterUnit: unit = Settings.diameterUnit() case Constants.VelocityUnit: unit = Settings.velocityUnit() case Constants.DistanceUnit: unit = Settings.distanceUnit() default: break } unitDescription = units.filter({ $0.1 == unit }).first?.0 } return unitDescription } } extension SettingsViewController: PickerViewControllerDelegate { func picker(picker: PickerViewController, didPickItem item: String?) { if let item = item, let selectedUnit = selectedUnitType?.0, let units = unitTypes[selectedUnit], let unit = units.filter({ $0.0 == item }).first?.1 { switch selectedUnit { case Constants.DiameterUnit: Settings.setDiameterUnit(unit) case Constants.VelocityUnit: Settings.setVelocityUnit(unit) case Constants.DistanceUnit: Settings.setDistanceUnit(unit) default: break } self.tableView.reloadData() } } }
mit
390251e8140fc13d9721d9e498991453
36.972222
244
0.613021
5.088089
false
false
false
false
hooman/swift
test/decl/protocol/special/coding/enum_codable_simple_conditional_separate.swift
13
1916
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown -swift-version 4 enum Conditional<T> { case a(x: T, y: T?) case b(z: [T]) func foo() { // They should receive a synthesized CodingKeys enum. let _ = Conditional.CodingKeys.self let _ = Conditional.ACodingKeys.self let _ = Conditional.BCodingKeys.self // The enum should have a case for each of the cases. let _ = Conditional.CodingKeys.a let _ = Conditional.CodingKeys.b // The enum should have a case for each of the vars. let _ = Conditional.ACodingKeys.x let _ = Conditional.ACodingKeys.y let _ = Conditional.BCodingKeys.z } } extension Conditional: Encodable where T: Encodable { // expected-note {{where 'T' = 'OnlyDec'}} } extension Conditional: Decodable where T: Decodable { // expected-note {{where 'T' = 'OnlyEnc'}} } struct OnlyEnc: Encodable {} struct OnlyDec: Decodable {} // They should receive synthesized init(from:) and an encode(to:). let _ = Conditional<OnlyDec>.init(from:) let _ = Conditional<OnlyEnc>.encode(to:) // but only for the appropriately *codable parameters. let _ = Conditional<OnlyEnc>.init(from:) // expected-error {{referencing initializer 'init(from:)' on 'Conditional' requires that 'OnlyEnc' conform to 'Decodable'}} let _ = Conditional<OnlyDec>.encode(to:) // expected-error {{referencing instance method 'encode(to:)' on 'Conditional' requires that 'OnlyDec' conform to 'Encodable'}} // The synthesized CodingKeys type should not be accessible from outside the // enum. let _ = Conditional<Int>.CodingKeys.self // expected-error {{'CodingKeys' is inaccessible due to 'private' protection level}} let _ = Conditional<Int>.ACodingKeys.self // expected-error {{'ACodingKeys' is inaccessible due to 'private' protection level}} let _ = Conditional<Int>.BCodingKeys.self // expected-error {{'BCodingKeys' is inaccessible due to 'private' protection level}}
apache-2.0
9f554f205d1f5e51b28e0790e492fdf5
41.577778
168
0.714509
3.942387
false
false
false
false
IBM-Swift/Kitura-net
Sources/KituraNet/HTTP/HTTPServer.swift
1
24194
/* * 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 Dispatch import LoggerAPI import Socket import SSLService #if os(Linux) import Signals #endif // MARK: HTTPServer /** An HTTP server that listens for connections on a socket. ### Usage Example: ### ````swift //Create a server that listens for connections on a specified socket. let server = try HTTPServer.listen(on: 0, delegate: delegate) ... //Stop the server. server.stop() ```` */ public class HTTPServer: Server { public typealias ServerType = HTTPServer /** HTTP `ServerDelegate`. ### Usage Example: ### ````swift httpServer.delegate = self ```` */ public var delegate: ServerDelegate? /// The TCP port on which this server listens for new connections. If `nil`, this server does not listen on a TCP socket. public private(set) var port: Int? /// The address of the network interface to listen on. Defaults to nil, which means this server will listen on all /// interfaces. public private(set) var address: String? /// The Unix domain socket path on which this server listens for new connections. If `nil`, this server does not listen on a Unix socket. public private(set) var unixDomainSocketPath: String? /// The types of listeners we currently support. private enum ListenerType { case inet(Int, String?) // port, node case unix(String) } /** A server state ### Usage Example: ### ````swift if(httpSever.state == .unknown) { httpServer.stop() } ```` */ public private(set) var state: ServerState = .unknown /// TCP socket used for listening for new connections private var listenSocket: Socket? /** Whether or not this server allows port reuse (default: disallowed). ### Usage Example: ### ````swift httpServer.allowPortReuse = true ```` */ public var allowPortReuse: Bool = false /// Maximum number of pending connections private let maxPendingConnections = 100 /** Controls the maximum number of requests per Keep-Alive connection. ### Usage Example: ### ````swift httpServer.keepAliveState = .unlimited ```` */ public var keepAliveState: KeepAliveState = .unlimited /// Controls policies relating to incoming connections and requests. public var options: ServerOptions = ServerOptions() { didSet { self.socketManager?.serverOptions = options } } /// Incoming socket handler private var socketManager: IncomingSocketManager? /** SSL cert configuration for handling client requests. ### Usage Example: ### ````swift httpServer.sslConfig = sslConfiguration ```` */ public var sslConfig: SSLService.Configuration? fileprivate let lifecycleListener = ServerLifecycleListener() private static let dummyServerDelegate = HTTPDummyServerDelegate() private static var incomingSocketProcessorCreatorRegistry = Dictionary<String, IncomingSocketProcessorCreator>() // Initialize the one time initialization struct to cause one time initializations to occur static private let oneTime = HTTPServerOneTimeInitializations() /** Creates an HTTP server object. ### Usage Example: ### ````swift let server = HTTPServer() server.listen(on: 8080) ```` */ public init() { #if os(Linux) // On Linux, it is not possible to set SO_NOSIGPIPE on the socket, nor is it possible // to pass MSG_NOSIGNAL when writing via SSL_write(). Instead, we will receive it but // ignore it. This happens when a remote receiver closes a socket we are to writing to. Signals.trap(signal: .pipe) { _ in Log.info("Receiver closed socket, SIGPIPE ignored") } #endif _ = HTTPServer.oneTime } /** Listens for connections on a TCP socket. ### Usage Example: ### ````swift try server.listen(on: 8080, address: "localhost") ```` - Parameter port: Port number for new connections, e.g. 8080 - Parameter address: The address of a network interface to listen on, for example "localhost". The default is nil, which listens for connections on all interfaces. */ public func listen(on port: Int, address: String? = nil) throws { self.port = port self.address = address try listen(.inet(port, address)) } /** Listens for connections on a Unix socket. ### Usage Example: ### ````swift try server.listen(unixDomainSocketPath: "/my/path") ```` - Parameter unixDomainSocketPath: Unix socket path for new connections, eg. "/my/path" */ public func listen(unixDomainSocketPath: String) throws { self.unixDomainSocketPath = unixDomainSocketPath try listen(.unix(unixDomainSocketPath)) } private func listen(_ listener: ListenerType) throws { do { let socket: Socket switch listener { case .inet: socket = try Socket.create(family: .inet) case .unix: socket = try Socket.create(family: .unix) } self.listenSocket = socket // If SSL config has been created, // create and attach the SSLService delegate to the socket if let sslConfig = sslConfig { socket.delegate = try SSLService(usingConfiguration: sslConfig); } let listenerDescription: String switch listener { case .inet(let port, let node): try socket.listen(on: port, maxBacklogSize: maxPendingConnections, allowPortReuse: self.allowPortReuse, node: node) // If a random (ephemeral) port number was requested, get the listening port let listeningPort = Int(socket.listeningPort) if listeningPort != port { self.port = listeningPort // We should only expect a different port if the requested port was zero. if port != 0 { Log.error("Listening port \(listeningPort) does not match requested port \(port)") } } listenerDescription = "port \(listeningPort)" case .unix(let path): try socket.listen(on: path, maxBacklogSize: maxPendingConnections) listenerDescription = "path \(path)" } let socketManager = IncomingSocketManager(options: self.options) self.socketManager = socketManager if let delegate = socket.delegate { #if os(Linux) // Add the list of supported ALPN protocols to the SSLServiceDelegate for (protoName, _) in HTTPServer.incomingSocketProcessorCreatorRegistry { socket.delegate?.addSupportedAlpnProtocol(proto: protoName) } #endif Log.info("Listening on \(listenerDescription) (delegate: \(delegate))") Log.verbose("Options for \(listenerDescription): delegate: \(delegate), maxPendingConnections: \(maxPendingConnections), allowPortReuse: \(self.allowPortReuse)") } else { Log.info("Listening on \(listenerDescription)") Log.verbose("Options for \(listenerDescription): maxPendingConnections: \(maxPendingConnections), allowPortReuse: \(self.allowPortReuse)") } // set synchronously to avoid contention in back to back server start/stop calls self.state = .started self.lifecycleListener.performStartCallbacks() let queuedBlock = DispatchWorkItem(block: { self.listen(listenSocket: socket, socketManager: socketManager) self.lifecycleListener.performStopCallbacks() }) ListenerGroup.enqueueAsynchronously(on: DispatchQueue.global(), block: queuedBlock) } catch let error { self.state = .failed self.lifecycleListener.performFailCallbacks(with: error) throw error } } /** Static method to create a new HTTP server and have it listen for connections. ### Usage Example: ### ````swift let server = HTTPServer.listen(on: 8080, address: "localhost", delegate: self) ```` - Parameter on: Port number for accepting new connections. - Parameter address: The address of a network interface to listen on, for example "localhost". The default is nil, which listens for connections on all interfaces. - Parameter delegate: The delegate handler for HTTP connections. - Returns: A new instance of a `HTTPServer`. */ public static func listen(on port: Int, address: String? = nil, delegate: ServerDelegate?) throws -> HTTPServer { let server = HTTP.createServer() server.delegate = delegate try server.listen(on: port, address: address) return server } /** Static method to create a new HTTP server and have it listen for connections on a Unix domain socket. ### Usage Example: ### ````swift let server = HTTPServer.listen(unixDomainSocketPath: "/my/path", delegate: self) ```` - Parameter unixDomainSocketPath: The path of the Unix domain socket that this server should listen on. - Parameter delegate: The delegate handler for HTTP connections. - Returns: A new instance of a `HTTPServer`. */ public static func listen(unixDomainSocketPath: String, delegate: ServerDelegate?) throws -> HTTPServer { let server = HTTP.createServer() server.delegate = delegate try server.listen(unixDomainSocketPath: unixDomainSocketPath) return server } /** Listen for connections on a socket. ### Usage Example: ### ````swift try server.listen(on: 8080, errorHandler: errorHandler) ```` - Parameter port: port number for new connections (eg. 8080) - Parameter errorHandler: optional callback for error handling */ @available(*, deprecated, message: "use 'listen(on:) throws' with 'server.failed(callback:)' instead") public func listen(port: Int, errorHandler: ((Swift.Error) -> Void)? = nil) { do { try listen(on: port) } catch let error { if let callback = errorHandler { callback(error) } else { Log.error("Error listening on port \(port): \(error)") } } } /** Static method to create a new HTTPServer and have it listen for connections. ### Usage Example: ### ````swift let server = HTTPServer(port: 8080, delegate: self, errorHandler: errorHandler) ```` - Parameter port: port number for new connections (eg. 8080) - Parameter delegate: The delegate handler for HTTP connections. - Parameter errorHandler: optional callback for error handling - Returns: A new `HTTPServer` instance. */ @available(*, deprecated, message: "use 'listen(on:delegate:) throws' with 'server.failed(callback:)' instead") public static func listen(port: Int, delegate: ServerDelegate, errorHandler: ((Swift.Error) -> Void)? = nil) -> HTTPServer { let server = HTTP.createServer() server.delegate = delegate server.listen(port: port, errorHandler: errorHandler) return server } /// Listen on socket while server is started and pass on to socketManager to handle private func listen(listenSocket: Socket, socketManager: IncomingSocketManager) { repeat { do { let clientSocket = try listenSocket.acceptClientConnection(invokeDelegate: false) let clientSource = "\(clientSocket.remoteHostname):\(clientSocket.remotePort)" if let connectionLimit = self.options.connectionLimit, socketManager.socketHandlerCount >= connectionLimit { // See if any idle sockets can be removed before rejecting this connection socketManager.removeIdleSockets(runNow: true) } if let connectionLimit = self.options.connectionLimit, socketManager.socketHandlerCount >= connectionLimit { // Connections still at limit, this connection must be rejected if let (httpStatus, response) = self.options.connectionResponseGenerator(connectionLimit, clientSource) { let statusCode = httpStatus.rawValue let statusDescription = HTTP.statusCodes[statusCode] ?? "" let contentLength = response.utf8.count let httpResponse = "HTTP/1.1 \(statusCode) \(statusDescription)\r\nConnection: Close\r\nContent-Length: \(contentLength)\r\n\r\n".appending(response) _ = try? clientSocket.write(from: httpResponse) } clientSocket.close() continue } else { Log.debug("Accepted HTTP connection from: \(clientSource)") } if listenSocket.delegate != nil { DispatchQueue.global().async { [weak self] in guard let strongSelf = self else { Log.info("Cannot initialize client connection from \(clientSource), server has been deallocated") return } do { try strongSelf.initializeClientConnection(clientSocket: clientSocket, listenSocket: listenSocket) strongSelf.handleClientConnection(clientSocket: clientSocket, socketManager: socketManager) } catch let error { if strongSelf.state == .stopped { if let socketError = error as? Socket.Error { Log.warning("Socket.Error initializing client connection from \(clientSource) after server stopped: \(socketError)") } else { Log.warning("Error initializing client connection from \(clientSource) after server stopped: \(error)") } } else { Log.error("Error initializing client connection from \(clientSource): \(error)") strongSelf.lifecycleListener.performClientConnectionFailCallbacks(with: error) } } } } else { handleClientConnection(clientSocket: clientSocket, socketManager: socketManager) } } catch let error { if self.state == .stopped { if let socketError = error as? Socket.Error { if socketError.errorCode == Int32(Socket.SOCKET_ERR_ACCEPT_FAILED) { Log.info("Server has stopped listening") } else { Log.warning("Socket.Error accepting client connection after server stopped: \(error)") } } else { Log.warning("Error accepting client connection after server stopped: \(error)") } } else { Log.error("Error accepting client connection: \(error)") self.lifecycleListener.performClientConnectionFailCallbacks(with: error) } } } while self.state == .started && listenSocket.isListening if self.state == .started { Log.error("listenSocket closed without stop() being called") stop() } } /// Initializes a newly accepted client connection. /// This procedure may involve reading bytes from the client (in the case of an SSL handshake), /// so must be done on a separate thread to avoid blocking the listener (Kitura issue #1143). /// private func initializeClientConnection(clientSocket: Socket, listenSocket: Socket) throws { if listenSocket.delegate != nil { try listenSocket.invokeDelegateOnAccept(for: clientSocket) } } /// Completes the process of accepting a new client connection. This is either invoked from the /// main listen() loop, or in the presence of an SSL delegate, from an async block. /// private func handleClientConnection(clientSocket: Socket, socketManager: IncomingSocketManager) { #if os(Linux) let negotiatedProtocol = clientSocket.delegate?.negotiatedAlpnProtocol ?? "http/1.1" #else let negotiatedProtocol = "http/1.1" #endif if let incomingSocketProcessorCreator = HTTPServer.incomingSocketProcessorCreatorRegistry[negotiatedProtocol] { let serverDelegate = delegate ?? HTTPServer.dummyServerDelegate let incomingSocketProcessor: IncomingSocketProcessor? switch incomingSocketProcessorCreator { case let creator as HTTPIncomingSocketProcessorCreator: incomingSocketProcessor = creator.createIncomingSocketProcessor(socket: clientSocket, using: serverDelegate, keepalive: self.keepAliveState) default: incomingSocketProcessor = incomingSocketProcessorCreator.createIncomingSocketProcessor(socket: clientSocket, using: serverDelegate) } socketManager.handle(socket: clientSocket, processor: incomingSocketProcessor!) } else { Log.error("Negotiated protocol \(negotiatedProtocol) not supported on this server") } } /** Stop listening for new connections. ### Usage Example: ### ````swift server.stop() ```` */ public func stop() { self.state = .stopped listenSocket?.close() listenSocket = nil socketManager?.stop() socketManager = nil } /** Add a new listener for a server being started. ### Usage Example: ### ````swift server.started(callback: callBack) ```` - Parameter callback: The listener callback that will run after a successfull start-up. - Returns: A `HTTPServer` instance. */ @discardableResult public func started(callback: @escaping () -> Void) -> Self { self.lifecycleListener.addStartCallback(perform: self.state == .started, callback) return self } /** Add a new listener for a server being stopped. ### Usage Example: ### ````swift server.stopped(callback: callBack) ```` - Parameter callback: The listener callback that will run when the server stops. - Returns: A `HTTPServer` instance. */ @discardableResult public func stopped(callback: @escaping () -> Void) -> Self { self.lifecycleListener.addStopCallback(perform: self.state == .stopped, callback) return self } /** Add a new listener for a server throwing an error. ### Usage Example: ### ````swift server.started(callback: callBack) ```` - Parameter callback: The listener callback that will run when the server throws an error. - Returns: A `HTTPServer` instance. */ @discardableResult public func failed(callback: @escaping (Swift.Error) -> Void) -> Self { self.lifecycleListener.addFailCallback(callback) return self } /** Add a new listener for when `listenSocket.acceptClientConnection` throws an error. ### Usage Example: ### ````swift server.clientConnectionFailed(callback: callBack) ```` - Parameter callback: The listener callback that will run on server after successfull start-up. - Returns: A `HTTPServer` instance. */ @discardableResult public func clientConnectionFailed(callback: @escaping (Swift.Error) -> Void) -> Self { self.lifecycleListener.addClientConnectionFailCallback(callback) return self } /** Wait for all of the listeners to stop. ### Usage Example: ### ````swift server.waitForListeners() ```` - todo: This calls the ListenerGroup object, and is left in for backwards compatability. It can be safely removed once Kitura is patched to talk directly to ListenerGroup. */ @available(*, deprecated, message:"Will be removed in future versions. Use ListenerGroup.waitForListeners() directly.") public static func waitForListeners() { ListenerGroup.waitForListeners() } /// A Dummy `ServerDelegate` used when the user didn't supply a delegate, but has registerd /// at least one ConnectionUpgradeFactory. This `ServerDelegate` will simply return 404 for /// any requests it is asked to process. private class HTTPDummyServerDelegate: ServerDelegate { /// Handle new incoming requests to the server /// /// - Parameter request: The ServerRequest class instance for working with this request. /// The ServerRequest object enables you to get the query parameters, headers, and body amongst other /// information about the incoming request. /// - Parameter response: The ServerResponse class instance for working with this request. /// The ServerResponse object enables you to build and send your response to the client who sent /// the request. This includes headers, the body, and the response code. func handle(request: ServerRequest, response: ServerResponse){ do { response.statusCode = .notFound let theBody = "Path not found" response.headers["Content-Type"] = ["text/plain"] response.headers["Content-Length"] = [String(theBody.utf8.count)] try response.write(from: theBody) try response.end() } catch { Log.error("Failed to send the response. Error = \(error)") } } } /** Register a class that creates `IncomingSockerProcessor`s for use with new incoming sockets. ### Usage Example: ### ````swift server.register(incomingSocketProcessorCreator: creator) ```` - Parameter incomingSocketProcessorCreator: An implementation of the `IncomingSocketProcessorCreator` protocol which creates an implementation of the `IncomingSocketProcessor` protocol to process the data from a new incoming socket. */ public static func register(incomingSocketProcessorCreator creator: IncomingSocketProcessorCreator) { incomingSocketProcessorCreatorRegistry[creator.name] = creator } /// Singleton struct for one time initializations private struct HTTPServerOneTimeInitializations { init() { HTTPServer.register(incomingSocketProcessorCreator: HTTPIncomingSocketProcessorCreator()) } } }
apache-2.0
96d1e790d883b7020b4cf582e8138a19
38.339837
237
0.612218
5.253855
false
false
false
false
Tsukishita/CaveCommentViewer
CaveCommentViewer/CreateRoomView.swift
1
15880
// // CreateRoomView.swift // CaveCommentViewer // // Created by 月下 on 2015/12/28. // Copyright © 2015年 月下. All rights reserved. // protocol CreateRoomViewDelegate{ func createRoom(params params:String) } import Foundation import UIKit import KeychainAccess import SwiftyJSON import Kanna class CreateRoomView:UIViewController,UITextFieldDelegate,UITextViewDelegate, UITableViewDataSource,UITableViewDelegate,CreateRoomDetailViewDelegate,UIBarPositioningDelegate { @IBOutlet weak var titleText: UITextField! @IBOutlet weak var detailText: UITextView! @IBOutlet weak var tagText: UITextField! @IBOutlet weak var ComIDSw: UISwitch! @IBOutlet weak var AuthSw: UISwitch! @IBOutlet weak var NameSw: UISwitch! @IBOutlet weak var TestModeSw: UISwitch! @IBOutlet weak var genreTable: UITableView! @IBOutlet weak var thubmTable: UITableView! @IBOutlet weak var PresetTable: UITableView! @IBOutlet weak var scrollview: UIScrollView! let Api = CaveAPI() var delegate: CreateRoomViewDelegate! = nil //選択されているサムネ,有効なサムネ番号,サムネの画像 var Thumb_slot = 0 var Thumb_list:[Int] = [0] var ThumbImage:Dictionary<Int,UIImage> = Dictionary() var Genre_slot = 0 var PresetSlot = -1 var ComID:Bool = false var AuthCom:Bool = false var AnonyCom:Bool = false var TestMode:Bool = false var txtActiveField = UITextField() let genre:[String]=["配信ジャンルを選択","FPS", "MMO","MOBA", "TPS","サンドボックス", "FINAL FANTASY XIV","PSO2", "フットボールゲーム","音ゲー", "イラスト","マンガ", "ゲーム","手芸 工作","演奏", "開発","雑談"] let tag:[String]=["含まれるタグ","FPS ゲーム", "MMO ゲーム","MOBA ゲーム", "TPS ゲーム","サンドボックス ゲーム", "FF14 ゲーム","PSO2 ゲーム", "サッカー ゲーム","音ゲー ゲーム", "イラスト","マンガ", "ゲーム","手芸工作","演奏", "開発","雑談"] override func viewDidLoad() { super.viewDidLoad() let NavTitle: UILabel = UILabel(frame: CGRectZero) NavTitle.font = UIFont.boldSystemFontOfSize(16.0) NavTitle.textColor = UIColor.whiteColor() NavTitle.text = "新規放送枠の作成" NavTitle.sizeToFit() navigationItem.titleView = NavTitle; ComIDSw.addTarget(self, action: "onClickMySwicth:", forControlEvents: UIControlEvents.ValueChanged) AuthSw.addTarget(self, action: "onClickMySwicth:", forControlEvents: UIControlEvents.ValueChanged) NameSw.addTarget(self, action: "onClickMySwicth:", forControlEvents: UIControlEvents.ValueChanged) TestModeSw.addTarget(self, action: "onClickMySwicth:", forControlEvents: UIControlEvents.ValueChanged) let str = "http://gae.cavelis.net/user/\(self.Api.auth_user)" let url:NSURL! = NSURL( string:str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! ) let request = NSMutableURLRequest(URL: url) if self.Api.cookieKey != nil{ let header = NSHTTPCookie.requestHeaderFieldsWithCookies(self.Api.cookieKey!) request.allHTTPHeaderFields = header } let task : NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) -> Void in if error == nil { self.profParse(data: data!) } } task.resume() } //UIbuttonAction @IBAction func CreateRoom(sender: AnyObject) { if titleText.text == ""{ let Date:NSDate = NSDate() let DateFormatter: NSDateFormatter = NSDateFormatter() DateFormatter.locale = NSLocale(localeIdentifier: "ja") DateFormatter.dateFormat = "yyyy'/'MM'/'dd' 'HH':'mm':'ss" titleText.text = DateFormatter.stringFromDate(Date) print(DateFormatter.stringFromDate(Date)) } var params:String = String() params += "devkey=\(self.Api.devKey)&" params += "title=\(self.titleText.text!)&" params += "apikey=\(self.Api.apiKey)&" params += "description=\(self.detailText.text!)&" params += "tag=\(self.tagText.text!)&" params += "id_visible=\(self.ComID)&" params += "anonymous_only=\(self.AnonyCom)&" params += "login_user=\(self.AuthCom)&" params += "thumbnail_slot=\(self.Thumb_slot)&" params += "test_mode=\(self.TestMode)" self.delegate.createRoom(params: params) } @IBAction func savePreset(sender: AnyObject) { //ダイアログでプリセット名入力 if titleText.text == "" { let cancelAction = UIAlertAction(title: "閉じる", style: .Default) {action in} let alertController: UIAlertController = UIAlertController(title: "タイトルは必須です", message: "", preferredStyle: .Alert) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) }else{ let alertController = UIAlertController(title: "プリセットの保存", message: "", preferredStyle: .Alert) let SaveAction = UIAlertAction(title: "保存", style: .Default) { action in self.view.endEditing(true) let textField:UITextField = alertController.textFields![0] let pre:Preset = Preset() pre.PresetName = textField.text! pre.Title = self.titleText.text pre.Comment = self.detailText.text pre.Gunre = self.Genre_slot pre.Tag = self.tagText.text pre.ThumbsSlot = self.Thumb_slot pre.ShowId = self.ComID pre.AnonyCom = self.AnonyCom pre.AuthCom = self.AuthCom if textField.text! == ""{ let cancelAction = UIAlertAction(title: "閉じる", style: .Default) {action in} let alertController: UIAlertController = UIAlertController(title: "保存失敗", message: "プリセット名が入力されていません", preferredStyle: .Alert) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } if self.Api.savePreset(preset: pre) == true{ status.animation(str: "保存が完了しました") self.PresetSlot = self.Api.presets.count - 1 self.PresetTable.reloadData() }else{ let cancelAction = UIAlertAction(title: "閉じる", style: .Default) {action in} let alertController: UIAlertController = UIAlertController(title: "保存失敗", message: "同じ名前のプリセットが既に存在します", preferredStyle: .Alert) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } } let cancelAction = UIAlertAction(title: "キャンセル", style: .Cancel) { action in self.view.endEditing(true) } alertController.addTextFieldWithConfigurationHandler({(textField:UITextField!) -> Void in textField.placeholder = "プリセット名" }) alertController.addAction(SaveAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) } } @IBAction func CaveRuleButton(sender: AnyObject) { let searchURL : NSURL = NSURL(string:"http://gae.cavelis.net/rule")! // ブラウザ起動 if UIApplication.sharedApplication().canOpenURL(searchURL){ UIApplication.sharedApplication().openURL(searchURL) } } //UITextFieldが編集された直後に呼ばれる. func textFieldShouldBeginEditing(textField: UITextField) -> Bool { txtActiveField = textField return true } //UITableDelegate func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch tableView.tag{ case 0: let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") cell.accessoryType = .DisclosureIndicator cell.textLabel!.text = "\(genre[Genre_slot]) (\(tag[Genre_slot]))" cell.textLabel?.font = UIFont.systemFontOfSize(14) return cell case 1: let cell:ThumbnailCell = tableView.dequeueReusableCellWithIdentifier("ThumbnailCell") as! ThumbnailCell cell.thumbLabel.text = "サムネイル\(Thumb_list[Thumb_slot] + 1)" cell.thumbnail!.image = self.ThumbImage[Thumb_list[Thumb_slot]] return cell case 2: let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") if PresetSlot == -1{ cell.textLabel!.text = "新規(デフォルト)" }else{ cell.textLabel!.text = Api.presets[PresetSlot].PresetName } return cell default: let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:(NSIndexPath)) { tableView.deselectRowAtIndexPath(indexPath, animated: true) self.performSegueWithIdentifier("CellSelectView",sender:tableView.tag) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch tableView.tag{ case 0: return 44 case 1: return 88 case 2: return 44 default : return 44 } } //DetailDeglegate func selectRowAtIndex(Tag Tag: Int, Row: Int) { if Tag == 0{ Genre_slot = Row if Row == 0{ tagText.text = "" }else{ tagText.text = "\(tag[Genre_slot]) " } self.genreTable.reloadData() }else if Tag == 1{ self.Thumb_slot = Row self.thubmTable.reloadData() }else{ if Row != -1{ self.PresetSlot = Row let selectPreset = Api.presets[Row] self.titleText.text = selectPreset.Title self.detailText.text = selectPreset.Comment self.Genre_slot = selectPreset.Gunre self.tagText.text = selectPreset.Tag self.Thumb_slot = selectPreset.ThumbsSlot self.ComID = selectPreset.ShowId self.AnonyCom = selectPreset.AnonyCom self.AuthCom = selectPreset.AuthCom self.ComIDSw.on = selectPreset.ShowId self.AuthSw.on = selectPreset.AnonyCom self.NameSw.on = selectPreset.AuthCom self.genreTable.reloadData() self.thubmTable.reloadData() self.PresetTable.reloadData() }else{ self.PresetSlot = Row self.genreTable.reloadData() self.thubmTable.reloadData() self.PresetTable.reloadData() } } self.navigationController?.popViewControllerAnimated(true) } func profParse(data data:NSData){ let doc = HTML(html: data, encoding: NSUTF8StringEncoding) for node in doc!.css("section#live_information_area li"){ let str = node.innerHTML! as NSString let start:NSRange = str.rangeOfString("src=") let end:NSRange = str.rangeOfString("\" class") let length = end.location - (start.location+start.length+1) let imgutl = str.substringWithRange(NSRange(location: start.location+5, length: length)) if imgutl == "/img/no_thumbnail_image.png"{ continue } if node["data-slot"] == "1"{ getThumbImage(url: imgutl, slot: 0) }else if node["data-slot"] == "2"{ Thumb_list.append(1) getThumbImage(url: imgutl, slot: 1) }else if node["data-slot"] == "3"{ Thumb_list.append(2) getThumbImage(url: imgutl, slot: 2) } } } func getThumbImage(url url:String,slot:Int){ let request = NSMutableURLRequest(URL: NSURL(string:"http:\(url)")!) let task : NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request){ (data, response, error) -> Void in if error == nil { self.ThumbImage[slot] = UIImage(data: data!) } dispatch_async(dispatch_get_main_queue()){() in self.thubmTable.reloadData() } } task.resume() } func onClickMySwicth(sender: UISwitch){ if sender.on { switch sender.tag{ case 0: ComID = true case 1: AuthCom = true case 2: AnonyCom = true case 3: TestMode = true default:break } } else { switch sender.tag{ case 0: ComID = false case 1: AuthCom = false case 2: AnonyCom = false case 3: TestMode = false default:break } } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "CellSelectView" { let tag = sender as! Int let DetailView : CreateRoomDetailView = segue.destinationViewController as! CreateRoomDetailView DetailView.delegate = self DetailView.tableTag = tag DetailView.thumb_select = self.Thumb_list DetailView.ThumbImage = self.ThumbImage } } func textFieldShouldEndEditing(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textViewDidEndEditing(textView: UITextView) { textView.resignFirstResponder() } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return UIBarPosition.TopAttached } }
mit
c410365c92ba0ee2deeff3ab4bc73432
36.850254
148
0.566286
4.825032
false
false
false
false
darthpelo/TimerH2O
TimerH2O/TimerH2O/Controllers/SessionManager.swift
1
3310
// // SessionManager.swift // TimerH2O // // Created by Alessio Roberto on 24/10/16. // Copyright © 2016 Alessio Roberto. All rights reserved. // import Foundation protocol SessionManager { func newSession(isStart: Bool) func state() -> State func intervalState() -> State func newInterval(isStart: Bool) func amountOfWater() -> Double func new(sessioId: String) func newAmountOf(water: Double) func newTimeInterval(second: TimeInterval) func endTimer() -> Date? func timeInterval() -> TimeInterval func new(countDown: TimeInterval) func countDown() -> TimeInterval func new(endTimer: Date) } enum StorageKey: String { case amountOfWater = "com.alessioroberto.amountOfWater" case sessionStart = "com.alessioroberto.sessionStart" case intervalStart = "com.alessioroberto.intervalStart" case timeInterval = "com.alessioroberto.timeInterval" case countDown = "com.alessioroberto.countDown" case endTimer = "com.alessioroberto.endTimer" case sessionID = "com.alessioroberto.sessionid" } enum State { case start case end } struct SessionManagerImplementation: SessionManager { private var userDefault: UserDefaults init(userDefault: UserDefaults = UserDefaults.standard) { self.userDefault = userDefault } func state() -> State { if userDefault.bool(forKey: StorageKey.sessionStart.rawValue) == true { return .start } else { return .end } } func intervalState() -> State { if userDefault.bool(forKey: StorageKey.intervalStart.rawValue) == true { return .start } else { return .end } } func newSession(isStart: Bool) { userDefault.set(isStart, forKey: StorageKey.sessionStart.rawValue) } func newInterval(isStart: Bool) { userDefault.set(isStart, forKey: StorageKey.intervalStart.rawValue) } func newAmountOf(water: Double) { userDefault.set(water, forKey: StorageKey.amountOfWater.rawValue) } func amountOfWater() -> Double { return userDefault.double(forKey: StorageKey.amountOfWater.rawValue) } func newTimeInterval(second: TimeInterval) { userDefault.set(second, forKey: StorageKey.timeInterval.rawValue) } func timeInterval() -> TimeInterval { return userDefault.double(forKey: StorageKey.timeInterval.rawValue) } func new(countDown: TimeInterval) { userDefault.set(countDown, forKey: StorageKey.countDown.rawValue) } func countDown() -> TimeInterval { return userDefault.double(forKey: StorageKey.countDown.rawValue) } func new(endTimer: Date) { userDefault.set(endTimer, forKey: StorageKey.endTimer.rawValue) } func endTimer() -> Date? { guard let when = userDefault.object(forKey: StorageKey.endTimer.rawValue) else { return nil } let date = when as? Date return date } func new(sessioId: String) { userDefault.set(sessioId, forKey: StorageKey.sessionID.rawValue) } func sessionID() -> String? { return userDefault.string(forKey: StorageKey.sessionID.rawValue) } }
mit
6d5a409914848bb4a602aed3684c9805
27.282051
88
0.653974
4.417891
false
false
false
false
See-Ku/SK4Toolkit
SK4Toolkit/gui/SK4TextAttributes.swift
1
1585
// // SK4TextAttributes.swift // SK4Toolkit // // Created by See.Ku on 2016/03/27. // Copyright (c) 2016 AxeRoad. All rights reserved. // import UIKit /// TextAttributesを簡単に扱うためのクラス public class SK4TextAttributes { /// 実際のTextAttributes ※随時、構成される public var attributes = [String:AnyObject]() /// NSFontAttributeName public var font: UIFont? { didSet { attributes[NSFontAttributeName] = font } } /// NSForegroundColorAttributeName public var textColor: UIColor? { didSet { attributes[NSForegroundColorAttributeName] = textColor } } /// NSBackgroundColorAttributeName public var backColor: UIColor? { didSet { attributes[NSBackgroundColorAttributeName] = backColor } } /// NSParagraphStyleAttributeName - alignment public var alignment = NSTextAlignment.Left { didSet { paragraph.alignment = alignment attributes[NSParagraphStyleAttributeName] = paragraph } } /// NSParagraphStyleAttributeName - lineBreakMode public var lineBreakMode = NSLineBreakMode.ByWordWrapping { didSet { paragraph.lineBreakMode = lineBreakMode attributes[NSParagraphStyleAttributeName] = paragraph } } /// NSParagraphStyleAttributeName public var paragraph = NSMutableParagraphStyle() { didSet { attributes[NSParagraphStyleAttributeName] = paragraph } } /// NSStrikethroughStyleAttributeName public var strikethrough: Int = 0 { didSet { attributes[NSStrikethroughStyleAttributeName] = NSNumber(integer: strikethrough) } } /// 初期化 public init() { } } // eof
mit
dffe3a9bb3bec3647b547307c38bbc92
19.945205
83
0.737737
4.099196
false
false
false
false
adonoho/XCGLogger
Sources/XCGLogger/Filters/UserInfoFilter.swift
14
4866
// // UserInfoFilter.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2016-09-01. // Copyright © 2016 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // // MARK: - UserInfoFilter /// Filter log messages by the contents of a key in the UserInfo dictionary /// Note: - This is intended to be subclassed, unlikely you'll use it directly open class UserInfoFilter: FilterProtocol { /// The key to check in the LogDetails.userInfo dictionary open var userInfoKey: String = "" /// Option to also apply the filter to internal messages (ie, app details, error's opening files etc) open var applyFilterToInternalMessages: Bool = false /// Option to toggle the match results open var inverse: Bool = false /// Internal list of items to match against private var itemsToMatch: Set<String> = [] /// Initializer to create an inclusion list of items to match against /// /// Note: Only log messages with a specific item will be logged, all others will be excluded /// /// - Parameters: /// - items: Set or Array of items to match against. /// public init<S: Sequence>(includeFrom items: S) where S.Iterator.Element == String { inverse = true add(items: items) } /// Initializer to create an exclusion list of items to match against /// /// Note: Log messages with a specific item will be excluded from logging /// /// - Parameters: /// - items: Set or Array of items to match against. /// public init<S: Sequence>(excludeFrom items: S) where S.Iterator.Element == String { inverse = false add(items: items) } /// Add another fileName to the list of names to match against. /// /// - Parameters: /// - item: Item to match against. /// /// - Returns: /// - true: FileName added. /// - false: FileName already added. /// @discardableResult open func add(item: String) -> Bool { return itemsToMatch.insert(item).inserted } /// Add a list of fileNames to the list of names to match against. /// /// - Parameters: /// - items: Set or Array of fileNames to match against. /// /// - Returns: Nothing /// open func add<S: Sequence>(items: S) where S.Iterator.Element == String { for item in items { add(item: item) } } /// Clear the list of fileNames to match against. /// /// - Note: Doesn't change whether or not the filter is inclusive of exclusive /// /// - Parameters: None /// /// - Returns: Nothing /// open func clear() { itemsToMatch = [] } /// Check if the log message should be excluded from logging. /// /// - Note: If the fileName matches /// /// - Parameters: /// - logDetails: The log details. /// - message: Formatted/processed message ready for output. /// /// - Returns: /// - true: Drop this log message. /// - false: Keep this log message and continue processing. /// open func shouldExclude(logDetails: inout LogDetails, message: inout String) -> Bool { var matched: Bool = false if !applyFilterToInternalMessages, let isInternal = logDetails.userInfo[XCGLogger.Constants.userInfoKeyInternal] as? Bool, isInternal { return inverse } if let messageItemsObject = logDetails.userInfo[userInfoKey] { if let messageItemsSet: Set<String> = messageItemsObject as? Set<String> { matched = itemsToMatch.intersection(messageItemsSet).count > 0 } else if let messageItemsArray: Array<String> = messageItemsObject as? Array<String> { matched = itemsToMatch.intersection(messageItemsArray).count > 0 } else if let messageItem = messageItemsObject as? String { matched = itemsToMatch.contains(messageItem) } } if inverse { matched = !matched } return matched } // MARK: - CustomDebugStringConvertible open var debugDescription: String { get { var description: String = "\(extractTypeName(self)): \(applyFilterToInternalMessages ? "(Filtering Internal) " : "")" + (inverse ? "Including only matches for: " : "Excluding matches for: ") if itemsToMatch.count > 5 { description += "\n\t- " + itemsToMatch.sorted().joined(separator: "\n\t- ") } else { description += itemsToMatch.sorted().joined(separator: ", ") } return description } } }
mit
632cbff6239f83ed5fe17aa493341dfe
33.020979
202
0.596506
4.585297
false
false
false
false
kperryua/swift
stdlib/public/SDK/XPC/XPC.swift
2
2933
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import XPC import _SwiftXPCOverlayShims //===----------------------------------------------------------------------===// // XPC Types //===----------------------------------------------------------------------===// public var XPC_TYPE_CONNECTION: xpc_type_t { return _swift_xpc_type_CONNECTION() } public var XPC_TYPE_ENDPOINT: xpc_type_t { return _swift_xpc_type_ENDPOINT() } public var XPC_TYPE_NULL: xpc_type_t { return _swift_xpc_type_NULL() } public var XPC_TYPE_BOOL: xpc_type_t { return _swift_xpc_type_BOOL() } public var XPC_TYPE_INT64: xpc_type_t { return _swift_xpc_type_INT64() } public var XPC_TYPE_UINT64: xpc_type_t { return _swift_xpc_type_UINT64() } public var XPC_TYPE_DOUBLE: xpc_type_t { return _swift_xpc_type_DOUBLE() } public var XPC_TYPE_DATE: xpc_type_t { return _swift_xpc_type_DATE() } public var XPC_TYPE_DATA: xpc_type_t { return _swift_xpc_type_DATA() } public var XPC_TYPE_STRING: xpc_type_t { return _swift_xpc_type_STRING() } public var XPC_TYPE_UUID: xpc_type_t { return _swift_xpc_type_UUID() } public var XPC_TYPE_FD: xpc_type_t { return _swift_xpc_type_FD() } public var XPC_TYPE_SHMEM: xpc_type_t { return _swift_xpc_type_SHMEM() } public var XPC_TYPE_ARRAY: xpc_type_t { return _swift_xpc_type_ARRAY() } public var XPC_TYPE_DICTIONARY: xpc_type_t { return _swift_xpc_type_DICTIONARY() } public var XPC_TYPE_ERROR: xpc_type_t { return _swift_xpc_type_ERROR() } public var XPC_TYPE_ACTIVITY: xpc_type_t { return _swift_xpc_type_ACTIVITY() } //===----------------------------------------------------------------------===// // Macros //===----------------------------------------------------------------------===// // xpc/xpc.h public let XPC_ERROR_KEY_DESCRIPTION: UnsafePointer<Int8> = _xpc_error_key_description public let XPC_EVENT_KEY_NAME: UnsafePointer<Int8> = _xpc_event_key_name public var XPC_BOOL_TRUE: xpc_object_t { return _swift_xpc_bool_true() } public var XPC_BOOL_FALSE: xpc_object_t { return _swift_xpc_bool_false() } public var XPC_ARRAY_APPEND: size_t { return -1 } // xpc/connection.h public var XPC_ERROR_CONNECTION_INTERRUPTED: xpc_object_t { return _swift_xpc_connection_interrupted() } public var XPC_ERROR_CONNECTION_INVALID: xpc_object_t { return _swift_xpc_connection_invalid() } public var XPC_ERROR_TERMINATION_IMMINENT: xpc_object_t { return _swift_xpc_connection_termination_imminent() }
apache-2.0
bb24c139145b0c082941dd2f7286fa56
23.647059
86
0.60075
3.277095
false
false
false
false
Hendrik44/pi-weather-app
AppSettings.swift
2
602
// // AppSettings.swift // Pi-Weather // // Created by Hendrik on 22.09.16. // Copyright © 2016 JG-Bits UG (haftungsbeschränkt). All rights reserved. // import UIKit class AppSettings: NSObject { static let sharedInstance = AppSettings() let refreshDataInterval:Double = 60 #if os(iOS) var datapointsInChart: Int { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad) { return 20 } else { return 10 } } #elseif os(tvOS) let datapointsInChart: Int = 60 #endif }
mit
d8fe29eb869863157005960021daaccd
20.428571
74
0.568333
4.026846
false
false
false
false
DanielAsher/SwiftReferenceApp
SwiftReferenceApp/Playgrounds/Swiftx.playground/Sources/Swiftx/Combinators.swift
3
6058
// // Functions.swift // Swiftx // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // /// The identity function. public func identity<A>(a : A) -> A { return a } /// The constant combinator ignores its second argument and always returns its first argument. public func const<A, B>(x : A) -> B -> A { return { _ in x } } /// Flip a function's arguments public func flip<A, B, C>(f : ((A, B) -> C), b : B, a : A) -> C { return f(a, b) } /// Flip a function's arguments and return a function that takes the arguments in flipped order. public func flip<A, B, C>(f : (A, B) -> C)(b : B, a : A) -> C { return f(a, b) } /// Flip a function's arguments and return a curried function that takes /// the arguments in flipped order. public func flip<A, B, C>(f : A -> B -> C) -> B -> A -> C { return { b in { a in f(a)(b) } } } /// Compose | Applies one function to the result of another function to produce a third function. /// /// f : B -> C /// g : A -> B /// (f • g)(x) === f(g(x)) : A -> B -> C public func • <A, B, C>(f : B -> C, g : A -> B) -> A -> C { return { (a : A) -> C in return f(g(a)) } } /// Apply | Applies an argument to a function. /// /// /// Because of this operator's extremely low precedence it can be used to elide parenthesis in /// complex expressions. For example: /// /// f § g § h § x = f(g(h(x))) /// /// Key Chord: ⌥ + 6 public func § <A, B>(f : A -> B, a : A) -> B { return f(a) } /// Key Chord: ⌥ + 6 public func § <A, B>(f : A throws -> B, a : A) throws -> B { return try f(a) } /// Pipe Backward | Applies the function to its left to an argument on its right. /// /// Because of this operator's extremely low precedence it can be used to elide parenthesis in /// complex expressions. For example: /// /// f <| g <| h <| x = f (g (h x)) /// /// Acts as a synonym for §. public func <| <A, B>(f : A -> B, a : A) -> B { return f(a) } /// Pipe forward | Applies an argument on the left to a function on the right. /// /// Complex expressions may look more natural when expressed with this operator rather than normal /// argument application. For example: /// /// { $0 * $0 }({ $0.advancedBy($0) }({ $0.advancedBy($0) }(1))) /// /// can also be written as: /// /// 1 |> { $0.advancedBy($0) } /// |> { $0.advancedBy($0) } /// |> { $0 * $0 } public func |> <A, B>(a : A, f : A -> B) -> B { return f(a) } /// The fixpoint (or Y) combinator computes the least fixed point of an equation. That is, the first /// point at which further application of x to a function is the same x. /// /// x = f(x) //public func fix<A, B>(f : ((A -> B) -> A -> B)) -> A -> B { // return { x in f(fix(f))(x) } //} /// Returns the least fixed point of the function returned by `f`. /// /// This is useful for e.g. making recursive closures without using the two-step assignment dance. /// /// \param f - A function which takes a parameter function, and returns a result function. The result function may recur by calling the parameter function. /// /// \return A recursive function. public func fix<A, B>(f: (A -> B) -> A -> B) -> A -> B { return { x in f(fix(f))(x) } } /// The fixpoint (or Y) combinator computes the least fixed point of an equation. That is, the first /// point at which further application of x to a function is the same x. /// fixt is the exception enabled version of fix. /// x = f(x) //public func fixt<A, B>(f : ((A throws -> B) -> A throws -> B)) -> A throws -> A { // return { x in try f(fixt(f))(x) } //} /// Returns the least fixed point of the function returned by `f`. /// /// This is useful for e.g. making recursive closures without using the two-step assignment dance. /// /// \param f - A function which takes a parameter function, and returns a result function. The result function may recur by calling the parameter function. /// /// \return A recursive function. public func fixt<A, B>(f : (A throws -> B) throws -> (A throws -> B)) rethrows -> A throws -> B { return { x in try f(fixt(f))(x) } } /// On | Applies the function on its right to both its arguments, then applies the function on its /// left to the result of both prior applications. /// /// f |*| g = { x in { y in f(g(x))(g(y)) } } /// /// This function may be useful when a comparing two like objects using a given property, as in: /// /// let arr : [(Int, String)] = [(2, "Second"), (1, "First"), (5, "Fifth"), (3, "Third"), (4, "Fourth")] /// let sortedByFirstIndex = arr.sort((<) |*| fst) public func |*| <A, B, C>(o : B -> B -> C, f : A -> B) -> A -> A -> C { return on(o)(f) } /// On | Applies the function on its right to both its arguments, then applies the function on its /// left to the result of both prior applications. /// /// (+) |*| f = { x, y in f(x) + f(y) } /// /// This function may be useful when a comparing two like objects using a given property, as in: /// /// let arr : [(Int, String)] = [(2, "Second"), (1, "First"), (5, "Fifth"), (3, "Third"), (4, "Fourth")] /// let sortedByFirstIndex = arr.sort((<) |*| fst) public func |*| <A, B, C>(o : (B, B) -> C, f : A -> B) -> A -> A -> C { return on(o)(f) } /// On | Applies the function on its right to both its arguments, then applies the function on its /// left to the result of both prior applications. /// /// (+) |*| f = { x in { y in f(x) + f(y) } } public func on<A, B, C>(o : B -> B -> C) -> (A -> B) -> A -> A -> C { return { f in { x in { y in o(f(x))(f(y)) } } } } /// On | Applies the function on its right to both its arguments, then applies the function on its /// left to the result of both prior applications. /// /// (+) |*| f = { x, y in f(x) + f(y) } public func on<A, B, C>(o : (B, B) -> C) -> (A -> B) -> A -> A -> C { return { f in { x in { y in o(f(x), f(y)) } } } } /// Applies a function to an argument until a given predicate returns true. public func until<A>(p : A -> Bool) -> (A -> A) -> A -> A { return { f in { x in p(x) ? x : until(p)(f)(f(x)) } } }
mit
83fb081366c6153ae7d75362b229f7a3
33.735632
156
0.579583
3.003976
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/OrderedSet.swift
1
3773
// // OrderedSet.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-03-21. // // --------------------------------------------------------------------------- // // © 2017-2020 1024jp // // 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 // // https://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. // struct OrderedSet<Element: Hashable>: RandomAccessCollection { typealias Index = Array<Element>.Index private var elements: [Element] = [] // MARK: - // MARK: Lifecycle init() { } init<S: Sequence>(_ elements: S) where S.Element == Element { self.append(contentsOf: elements) } // MARK: Collection Methods /// return the element at the specified position. subscript(_ index: Index) -> Element { return self.elements[index] } var startIndex: Index { return self.elements.startIndex } var endIndex: Index { return self.elements.endIndex } func index(after index: Index) -> Index { return self.elements.index(after: index) } // MARK: Methods var array: [Element] { return self.elements } var set: Set<Element> { return Set(self.elements) } /// return a new set with the elements that are common to both this set and the given sequence. func intersection<S: Sequence>(_ other: S) -> Self where S.Element == Element { var set = OrderedSet() set.elements = self.elements.filter { other.contains($0) } return set } // MARK: Mutating Methods /// insert the given element in the set if it is not already present. mutating func append(_ element: Element) { guard !self.elements.contains(element) else { return } self.elements.append(element) } /// insert the given elements in the set only which it is not already present. mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element { for element in elements { self.append(element) } } /// insert the given element at the desired position. mutating func insert(_ element: Element, at index: Index) { guard !self.elements.contains(element) else { return } self.elements.insert(element, at: index) } /// remove the elements of the set that aren’t also in the given sequence. mutating func formIntersection<S: Sequence>(_ other: S) where S.Element == Element { self.elements.removeAll { !other.contains($0) } } /// remove the the element at the position from the set. @discardableResult mutating func remove(at index: Index) -> Element { return self.elements.remove(at: index) } /// remove the specified element from the set. @discardableResult mutating func remove(_ element: Element) -> Element? { guard let index = self.firstIndex(of: element) else { return nil } return self.remove(at: index) } }
apache-2.0
f6cda69028329415f05bc125159b6e9d
23.640523
99
0.575066
4.724311
false
false
false
false
orazz/CreditCardForm-iOS
CreditCardForm/Classes/CreditCardFormView.swift
1
29648
// // CreditCardForumView.swift // CreditCardForm // // Created by Atakishiyev Orazdurdy on 11/28/16. // Copyright © 2016 Veriloft. All rights reserved. // import UIKit public enum Brands : String { case NONE, Visa, UnionPay, MasterCard, Amex, JCB, DEFAULT, Discover } @IBDesignable public class CreditCardFormView : UIView { fileprivate var cardView: UIView = UIView(frame: .zero) fileprivate var backView: UIView = UIView(frame: .zero) fileprivate var frontView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200)) fileprivate var gradientLayer = CAGradientLayer() fileprivate var showingBack:Bool = false fileprivate var backImage: UIImageView = UIImageView(frame: .zero) fileprivate var brandImageView = UIImageView(frame: .zero) fileprivate var cardNumber:AKMaskField = AKMaskField(frame: .zero) fileprivate var cardHolderText:UILabel = UILabel(frame: .zero) fileprivate var cardHolder:UILabel = UILabel(frame: .zero) fileprivate var expireDate: AKMaskField = AKMaskField(frame: .zero) fileprivate var expireDateText: UILabel = UILabel(frame: .zero) fileprivate var backLine: UIView = UIView(frame: .zero) fileprivate var cvc: AKMaskField = AKMaskField(frame: .zero) fileprivate var chipImg: UIImageView = UIImageView(frame: .zero) fileprivate var cvcAmexImageView: UIImageView = UIImageView(frame: .zero) fileprivate var amexCVC: AKMaskField = AKMaskField(frame: .zero) fileprivate var colors = [Brands.DEFAULT.rawValue: [ UIColor.hexStr(hexStr: "363434", alpha: 1), UIColor.hexStr(hexStr: "363434", alpha: 1)] ] fileprivate var cardNumberCenterXConstraint = NSLayoutConstraint() fileprivate var amex = false { didSet { self.cardNumberCenterXConstraint.constant = (self.amex) ? -20 : 0.0 self.cvcAmexImageView.isHidden = !self.amex self.amexCVC.isHidden = !self.amex UIView.animate(withDuration: 0.5) { self.cardView.layoutIfNeeded() } } } public var cardGradientColors = [String : [UIColor]]() @IBInspectable public var defaultCardColor: UIColor = UIColor.hexStr(hexStr: "363434", alpha: 1) { didSet { gradientLayer.colors = [defaultCardColor.cgColor, defaultCardColor.cgColor] backView.backgroundColor = defaultCardColor } } @IBInspectable public var cardHolderExpireDateTextColor: UIColor = UIColor.hexStr(hexStr: "#bdc3c7", alpha: 1) { didSet { cardHolderText.textColor = cardHolderExpireDateTextColor expireDateText.textColor = cardHolderExpireDateTextColor amexCVC.textColor = cardHolderExpireDateColor } } @IBInspectable public var cardHolderExpireDateColor: UIColor = .white { didSet { cardHolder.textColor = cardHolderExpireDateColor expireDate.textColor = cardHolderExpireDateColor cardNumber.textColor = cardHolderExpireDateColor } } @IBInspectable public var backLineColor: UIColor = .black { didSet { backLine.backgroundColor = backLineColor } } @IBInspectable public var chipImage = UIImage(named: "chip", in: Bundle.currentBundle(), compatibleWith: nil) { didSet { chipImg.image = chipImage } } @IBInspectable public var cvcAmexImageName = UIImage(named: "amexCvc", in: Bundle.currentBundle(), compatibleWith: nil) { didSet { cvcAmexImageView.image = cvcAmexImageName } } @IBInspectable public var cardHolderString = "----" { didSet { cardHolder.text = cardHolderString } } @IBInspectable public var cardHolderPlaceholderString = "CARD HOLDER" { didSet { cardHolderText.text = cardHolderPlaceholderString } } @IBInspectable public var expireDatePlaceholderText = "EXPIRY" { didSet { expireDateText.text = expireDatePlaceholderText } } @IBInspectable public var cardNumberMaskExpression = "{....} {....} {....} {....}" { didSet { cardNumber.maskExpression = cardNumberMaskExpression } } @IBInspectable public var cardNumberMaskTemplate = "**** **** **** ****" { didSet { cardNumber.maskTemplate = cardNumberMaskTemplate } } public var cardNumberFont: UIFont = UIFont(name: "HelveticaNeue", size: 20)! public var cardPlaceholdersFont: UIFont = UIFont(name: "HelveticaNeue", size: 10)! public var cardTextFont: UIFont = UIFont(name: "HelveticaNeue", size: 12)! public override init(frame: CGRect) { super.init(frame: frame) createViews() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func layoutSubviews() { super.layoutSubviews() createViews() } private func createViews() { frontView.isHidden = false backView.isHidden = true cardView.clipsToBounds = true if colors.count < 7 { setBrandColors() } createCardView() createFrontView() createbackImage() createBrandImageView() createCardNumber() createCardHolder() createCardHolderText() createExpireDate() createExpireDateText() createChipImage() createAmexCVC() createBackView() createBackLine() createCVC() } private func setGradientBackground(v: UIView, top: CGColor, bottom: CGColor) { let colorTop = top let colorBottom = bottom gradientLayer.colors = [ colorTop, colorBottom] gradientLayer.locations = [ 0.0, 1.0] gradientLayer.frame = v.bounds backView.backgroundColor = defaultCardColor v.layer.addSublayer(gradientLayer) } private func createCardView() { cardView.translatesAutoresizingMaskIntoConstraints = false cardView.layer.cornerRadius = 6 cardView.backgroundColor = .clear self.addSubview(cardView) //CardView self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.0, constant: 0.0)); } private func createBackView() { backView.translatesAutoresizingMaskIntoConstraints = false backView.layer.cornerRadius = 6 backView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) backView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin] cardView.addSubview(backView) self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.0, constant: 0.0)); } private func createFrontView() { frontView.translatesAutoresizingMaskIntoConstraints = false frontView.layer.cornerRadius = 6 frontView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) frontView.autoresizingMask = [UIView.AutoresizingMask.flexibleLeftMargin, UIView.AutoresizingMask.flexibleRightMargin, UIView.AutoresizingMask.flexibleTopMargin, UIView.AutoresizingMask.flexibleBottomMargin] cardView.addSubview(frontView) setGradientBackground(v: frontView, top: defaultCardColor.cgColor, bottom: defaultCardColor.cgColor) self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.0, constant: 0.0)); } private func createbackImage() { backImage.translatesAutoresizingMaskIntoConstraints = false backImage.image = UIImage(named: "back.jpg") backImage.contentMode = UIView.ContentMode.scaleAspectFill frontView.addSubview(backImage) self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: 0.0)); self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 0.0)); } private func createBrandImageView() { //Card brand image brandImageView.translatesAutoresizingMaskIntoConstraints = false brandImageView.contentMode = UIView.ContentMode.scaleAspectFit frontView.addSubview(brandImageView) self.addConstraint(NSLayoutConstraint(item: brandImageView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 10)); self.addConstraint(NSLayoutConstraint(item: brandImageView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: -10)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==60)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": brandImageView])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==40)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": brandImageView])); } private func createCardNumber() { //Credit card number cardNumber.translatesAutoresizingMaskIntoConstraints = false cardNumber.maskExpression = cardNumberMaskExpression cardNumber.maskTemplate = cardNumberMaskTemplate cardNumber.textColor = cardHolderExpireDateColor cardNumber.isUserInteractionEnabled = false cardNumber.textAlignment = NSTextAlignment.center cardNumber.font = cardNumberFont frontView.addSubview(cardNumber) cardNumberCenterXConstraint = NSLayoutConstraint(item: cardNumber, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0) self.addConstraint(cardNumberCenterXConstraint); self.addConstraint(NSLayoutConstraint(item: cardNumber, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0.0)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==200)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cardNumber])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==30)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cardNumber])); } private func createCardHolder() { //Name cardHolder.translatesAutoresizingMaskIntoConstraints = false cardHolder.font = cardTextFont cardHolder.textColor = cardHolderExpireDateColor cardHolder.text = cardHolderString frontView.addSubview(cardHolder) self.addConstraint(NSLayoutConstraint(item: cardHolder, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: -20)); self.addConstraint(NSLayoutConstraint(item: cardHolder, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1.0, constant: 15)); self.addConstraint(NSLayoutConstraint(item: cardHolder, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1.0, constant: 20)); } private func createCardHolderText() { //Card holder uilabel cardHolderText.translatesAutoresizingMaskIntoConstraints = false cardHolderText.font = cardPlaceholdersFont cardHolderText.text = cardHolderPlaceholderString cardHolderText.textColor = cardHolderExpireDateTextColor frontView.addSubview(cardHolderText) self.addConstraint(NSLayoutConstraint(item: cardHolderText, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardHolder, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: -3)); self.addConstraint(NSLayoutConstraint(item: cardHolderText, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1.0, constant: 15)); } private func createExpireDate() { //Expire Date expireDate = AKMaskField() expireDate.translatesAutoresizingMaskIntoConstraints = false expireDate.font = cardTextFont expireDate.maskExpression = "{..}/{..}" expireDate.text = "MM/YY" expireDate.textColor = cardHolderExpireDateColor frontView.addSubview(expireDate) self.addConstraint(NSLayoutConstraint(item: expireDate, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: -20)); self.addConstraint(NSLayoutConstraint(item: expireDate, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: -55)); } private func createExpireDateText() { //Expire Date Text expireDateText.translatesAutoresizingMaskIntoConstraints = false expireDateText.font = cardPlaceholdersFont expireDateText.text = expireDatePlaceholderText expireDateText.textColor = cardHolderExpireDateTextColor frontView.addSubview(expireDateText) self.addConstraint(NSLayoutConstraint(item: expireDateText, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: expireDate, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: -3)); self.addConstraint(NSLayoutConstraint(item: expireDateText, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: -58)); } private func createAmexCVC() { //Create Amex card cvc amexCVC = AKMaskField() amexCVC.translatesAutoresizingMaskIntoConstraints = false amexCVC.font = cardTextFont amexCVC.text = expireDatePlaceholderText amexCVC.maskExpression = "{....}" amexCVC.text = "***" amexCVC.isHidden = true frontView.addSubview(amexCVC) self.addConstraint(NSLayoutConstraint(item: amexCVC, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: -23)); self.addConstraint(NSLayoutConstraint(item: amexCVC, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardNumber, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 15)); self.addConstraint(NSLayoutConstraint(item: amexCVC, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1.0, constant: 27)); // Create amex cvc image cvcAmexImageView.translatesAutoresizingMaskIntoConstraints = false cvcAmexImageView.image = cvcAmexImageName cvcAmexImageView.contentMode = ContentMode.scaleAspectFit cvcAmexImageView.isHidden = true frontView.addSubview(cvcAmexImageView) self.addConstraint(NSLayoutConstraint(item: cvcAmexImageView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: amexCVC, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1.0, constant: -5)); self.addConstraint(NSLayoutConstraint(item: cvcAmexImageView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: amexCVC, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: 0)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==15)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cvcAmexImageView])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==15)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cvcAmexImageView])); } private func createChipImage() { //Chip image chipImg.translatesAutoresizingMaskIntoConstraints = false chipImg.alpha = 0.5 chipImg.image = chipImage frontView.addSubview(chipImg) self.addConstraint(NSLayoutConstraint(item: chipImg, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 15)); self.addConstraint(NSLayoutConstraint(item: chipImg, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: cardView, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1.0, constant: 15)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==45)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": chipImg])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==30)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": chipImg])); } private func createBackLine() { //BackLine backLine.translatesAutoresizingMaskIntoConstraints = false backLine.backgroundColor = backLineColor backView.addSubview(backLine) self.addConstraint(NSLayoutConstraint(item: backLine, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: backView, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1.0, constant: 20)); self.addConstraint(NSLayoutConstraint(item: backLine, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: backView, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==300)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": backLine])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==50)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": backLine])); } private func createCVC() { //CVC textfield cvc.translatesAutoresizingMaskIntoConstraints = false cvc.maskExpression = "..." cvc.text = "CVC" cvc.backgroundColor = .white cvc.textAlignment = NSTextAlignment.center cvc.isUserInteractionEnabled = false if #available(iOS 13.0, *) { cvc.backgroundColor = UIColor.systemGray3 } backView.addSubview(cvc) self.addConstraint(NSLayoutConstraint(item: cvc, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: backLine, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1.0, constant: 10)); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==50)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cvc])); self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==25)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["view": cvc])); self.addConstraint(NSLayoutConstraint(item: cvc, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: backView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: -10)); } private func setType(colors: [UIColor], alpha: CGFloat, back: UIColor) { UIView.animate(withDuration: 2, animations: { () -> Void in self.gradientLayer.colors = [colors[0].cgColor, colors[1].cgColor] }) self.backView.backgroundColor = back self.chipImg.alpha = alpha } private func flip() { var showingSide = frontView var hiddenSide = backView if showingBack { (showingSide, hiddenSide) = (backView, frontView) } UIView.transition(from:showingSide, to: hiddenSide, duration: 0.7, options: [UIView.AnimationOptions.transitionFlipFromRight, UIView.AnimationOptions.showHideTransitionViews], completion: nil) } public func isAmex() -> Bool { return self.amex } public func paymentCardTextFieldDidChange(cardNumber: String? = "", expirationYear: UInt?, expirationMonth: UInt?, cvc: String? = "") { self.cardNumber.text = cardNumber if let expireMonth = expirationMonth, let expireYear = expirationYear { self.expireDate.text = NSString(format: "%02ld", expireMonth) as String + "/" + (NSString(format: "%02ld", expireYear) as String) } if expirationMonth == 0 { expireDate.text = "MM/YY" } let v = CreditCardValidator() self.cvc.text = cvc self.amexCVC.text = cvc guard let cardN = cardNumber else { return } if (cardN.count == 0) { self.cardNumber.maskExpression = "{....} {....} {....} {....}" } if (cardN.count >= 7 || cardN.count < 4) { amex = false guard let type = v.type(from: "\(cardN as String?)") else { self.brandImageView.image = nil if let name = colors["NONE"] { setType(colors: [name[0], name[1]], alpha: 0.5, back: name[0]) } return } // Visa, Mastercard, Amex etc. if let name = colors[type.name] { if(type.name.lowercased() == "amex".lowercased()){ if !amex { self.cardNumber.maskExpression = "{....} {....} {....} {...}" self.cardNumber.text = cardNumber amex = true } } self.brandImageView.image = UIImage(named: type.name, in: Bundle.currentBundle(), compatibleWith: nil) setType(colors: [name[0], name[1]], alpha: 1, back: name[0]) } else { setType(colors: [self.colors["DEFAULT"]![0], self.colors["DEFAULT"]![0]], alpha: 1, back: self.colors["DEFAULT"]![0]) } } } public func paymentCardTextFieldDidEndEditingExpiration(expirationYear: UInt) { if "\(expirationYear)".count <= 1 { expireDate.text = "MM/YY" } } public func paymentCardTextFieldDidBeginEditingCVC() { if !showingBack { if !amex { flip() showingBack = true } } } public func paymentCardTextFieldDidEndEditingCVC() { if showingBack { flip() showingBack = false } } } //: CardColors extension CreditCardFormView { fileprivate func setBrandColors() { colors[Brands.NONE.rawValue] = [defaultCardColor, defaultCardColor] colors[Brands.Visa.rawValue] = [UIColor.hexStr(hexStr: "#5D8BF2", alpha: 1), UIColor.hexStr(hexStr: "#3545AE", alpha: 1)] colors[Brands.MasterCard.rawValue] = [UIColor.hexStr(hexStr: "#ED495A", alpha: 1), UIColor.hexStr(hexStr: "#8B1A2B", alpha: 1)] colors[Brands.UnionPay.rawValue] = [UIColor.hexStr(hexStr: "#987c00", alpha: 1), UIColor.hexStr(hexStr: "#826a01", alpha: 1)] colors[Brands.Amex.rawValue] = [UIColor.hexStr(hexStr: "#005B9D", alpha: 1), UIColor.hexStr(hexStr: "#132972", alpha: 1)] colors[Brands.JCB.rawValue] = [UIColor.hexStr(hexStr: "#265797", alpha: 1), UIColor.hexStr(hexStr: "#3d6eaa", alpha: 1)] colors["Diners Club"] = [UIColor.hexStr(hexStr: "#5b99d8", alpha: 1), UIColor.hexStr(hexStr: "#4186CD", alpha: 1)] colors[Brands.Discover.rawValue] = [UIColor.hexStr(hexStr: "#e8a258", alpha: 1), UIColor.hexStr(hexStr: "#D97B16", alpha: 1)] colors[Brands.DEFAULT.rawValue] = [UIColor.hexStr(hexStr: "#5D8BF2", alpha: 1), UIColor.hexStr(hexStr: "#3545AE", alpha: 1)] if cardGradientColors.count > 0 { for (_, value) in cardGradientColors.enumerated() { colors[value.key] = value.value } } } }
mit
40eadb0cc80712ad9703f41aaeb41bf2
52.51444
266
0.68867
5.005403
false
false
false
false
twittemb/Weavy
Weavy/Loom.swift
1
8230
// // Loom.swift // Weavy // // Created by Thibault Wittemberg on 17-07-25. // Copyright © 2017 Warp Factor. All rights reserved. // import RxSwift /// Delegate used to communicate from a WarpWeaver protocol WarpWeaverDelegate: class { /// Used to tell the delegate a new Warp is to be weaved /// /// - Parameter stitch: this stitch has a Warp nextPresentable func weaveAnotherWarp (withStitch stitch: Stitch) /// Used to triggered the delegate before the warp/weft is knitted /// /// - Parameters: /// - warp: the warp that is knitted /// - weft: the weft that is knitted func willKnit (withWarp warp: Warp, andWeft weft: Weft) func didKnit (withWarp warp: Warp, andWeft weft: Weft) } /// A WarpWeaver handles the weaving for a dedicated Warp /// It will listen for Wefts emitted be the Warp Weftable companion or /// the Weftables produced by the Warp.knit function along the way class WarpWeaver { /// The warp to weave private let warp: Warp /// The Rx subject that holds all the wefts trigerred either by the Warp's Weftable /// or by the Weftables produced by the Warp.knit function private let wefts = PublishSubject<Weft>() /// The delegate is used so that the WarpWeaver can communicate with the Loom /// in the case of a new Warp to weave or before and after a knit process private weak var delegate: WarpWeaverDelegate! internal let disposeBag = DisposeBag() /// Initialize a WarpWeaver /// /// - Parameter warp: The Warp to weave init(forWarp warp: Warp, withDelegate delegate: WarpWeaverDelegate) { self.warp = warp self.delegate = delegate } /// Launch the weaving process /// /// - Parameter weftable: The Weftable that goes with the Warp. It will trigger some Weft at the Warp level (the first one for instance) func weave (listeningToWeftable weftable: Weftable) { // Weft can be emitted by the Weftable companion of the Warp or the weftables in the Stitches fired by the Warp.knit function self.wefts.asObservable().subscribe(onNext: { [unowned self] (weft) in // a new Weft has been triggered for this Warp. Let's knit it and see what Stitches come from that self.delegate.willKnit(withWarp: self.warp, andWeft: weft) let stitches = self.warp.knit(withWeft: weft) self.delegate.didKnit(withWarp: self.warp, andWeft: weft) // we know which stitches have been triggered by this navigation action // each one of these stitches will lead to a weaving action (for example, new warps to handle and new weftable to listen) stitches.forEach({ [unowned self] (stitch) in // if the stitch next presentable represents a Warp, it has to be processed at a higher level because // the WarpWeaver only knowns about the warp it's in charge of. // The WarpWeaver will expose through its delegate if stitch.nextPresentable is Warp { self.delegate.weaveAnotherWarp(withStitch: stitch) } else { // the stitch next presentable is not a warp, it can be processed at the WarpWeaver level if let nextPresentable = stitch.nextPresentable, let nextWeftable = stitch.nextWeftable { // we have to wait for the presentable to be displayed at least once to be able to // listen to the weftable. Indeed, we do not want to triggered another navigation action // until there is a first ViewController in the hierarchy nextPresentable.rxFirstTimeVisible.subscribe(onSuccess: { [unowned self, unowned nextPresentable, unowned nextWeftable] (_) in // we listen to the presentable weftable. For each new weft value, we trigger a new weaving process // this is the core principle of the whole navigation process // The process is paused each time the presntable is not currently displayed // for instance when another presentable is above it in the ViewControllers hierarchy. nextWeftable.weft .pausable(nextPresentable.rxVisible.startWith(true)) .asDriver(onErrorJustReturn: VoidWeft()).drive(onNext: { [unowned self] (weft) in // the nextPresentable's weftable fires a new weft self.wefts.onNext(weft) }).disposed(by: nextPresentable.disposeBag) }).disposed(by: self.disposeBag) } } // when first presentable is discovered we can assume the Warp is ready to be used (its head can be used in other warps) self.warp.warpReadySubject.onNext(true) }) }).disposed(by: self.disposeBag) // we listen for the Warp dedicated Weftable weftable.weft.pausable(self.warp.rxVisible.startWith(true)).asDriver(onErrorJustReturn: VoidWeft()).drive(onNext: { [unowned self] (weft) in // the warp's weftable fires a new weft (the initial weft for exemple) self.wefts.onNext(weft) }).disposed(by: warp.disposeBag) } } /// the only purpose of a Loom is to handle the navigation that is /// declared in the Warps of the application. final public class Loom { private var warpWeavers = [WarpWeaver]() private let disposeBag = DisposeBag() internal let willKnitSubject = PublishSubject<(String, String)>() internal let didKnitSubject = PublishSubject<(String, String)>() /// Initialize the Loom public init() { } /// Launch the weaving process /// /// - Parameters: /// - warp: The warp to weave /// - weftable: The Warp's Weftable companion that will determine the first navigation state for instance public func weave (fromWarp warp: Warp, andWeftable weftable: Weftable) { // a new WarpWeaver will handle this warp weaving let warpWeaver = WarpWeaver(forWarp: warp, withDelegate: self) // we stack the WarpWeavers so that we do not lose there reference (whereas it could be a leak) self.warpWeavers.append(warpWeaver) // let's weave the Warp warpWeaver.weave(listeningToWeftable: weftable) // clear the WarpWeavers stack when the warp has been dismissed (its head has been dismissed) let warpIndex = self.warpWeavers.count-1 warp.rxDismissed.subscribe(onSuccess: { [unowned self] (_) in self.warpWeavers.remove(at: warpIndex) }).disposed(by: self.disposeBag) } } extension Loom: WarpWeaverDelegate { func weaveAnotherWarp(withStitch stitch: Stitch) { guard let nextWeftable = stitch.nextWeftable else { print ("A Warp must have a Weftable companion") return } if let nextWarp = stitch.nextPresentable as? Warp { self.weave(fromWarp: nextWarp, andWeftable: nextWeftable) } } func willKnit(withWarp warp: Warp, andWeft weft: Weft) { if !(weft is VoidWeft) { self.willKnitSubject.onNext(("\(warp)", "\(weft)")) } } func didKnit(withWarp warp: Warp, andWeft weft: Weft) { if !(weft is VoidWeft) { self.didKnitSubject.onNext(("\(warp)", "\(weft)")) } } } // swiftlint:disable identifier_name extension Loom { /// Reactive extension to a Loom public var rx: Reactive<Loom> { return Reactive(self) } } // swiftlint:enable identifier_name extension Reactive where Base: Loom { /// Rx Observable triggered before the Loom knit a Warp/Weft public var willKnit: Observable<(String, String)> { return self.base.willKnitSubject.asObservable() } /// Rx Observable triggered after the Loom knit a Warp/Weft public var didKnit: Observable<(String, String)> { return self.base.didKnitSubject.asObservable() } }
mit
5403e9b36e091aca97537a3c635d753a
40.145
150
0.636408
4.118619
false
false
false
false
rubnsbarbosa/swift
firstApp/firstApp/ViewController.swift
1
1641
// // ViewController.swift // firstApp // // Created by Rubens Santos Barbosa on 22/05/17. // Copyright © 2017 Rubens Santos Barbosa. All rights reserved. // /* fazer o clique no botao mudar outras propriedades da label (p.ex: background e color) fazer o clique no botao mudar propriedades da view (p.ex: color) usar o attributes inspector para alterar propriedades da view e seus componentes investigar o uso do metodo viewDidLoad, na viewController (ciclo de vida do View Controller) */ import UIKit class ViewController: UIViewController { let p = Pessoa(nome: "Rubens", idade: 26, altura: 1.70) @IBOutlet weak var name: UILabel! @IBOutlet weak var idade: UILabel! @IBOutlet weak var altura: UILabel! @IBOutlet weak var meuNome: UILabel! @IBOutlet weak var minhaIdade: UILabel! @IBOutlet weak var minhaAltura: UILabel! @IBAction func exibir(_ sender: Any) { meuNome.text = p.nome minhaIdade.text = String(p.idade) minhaAltura.text = String(p.altura) } @IBAction func limpar(_ sender: Any) { meuNome.text = "" minhaIdade.text = "" minhaAltura.text = "" } override func viewDidLoad() { super.viewDidLoad() let backgd = UIColor(red: 51/255, green: 112/255, blue: 201/255, alpha: 1) view.backgroundColor = backgd // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
0b56edc4d3703a3cb563427617b460b0
27.275862
96
0.651829
3.822844
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Dynamic Programming/140_Word Break II.swift
1
3729
// 140_Word Break II // https://leetcode.com/problems/word-break-ii/ // // Created by Honghao Zhang on 9/23/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences. // //Note: // //The same word in the dictionary may be reused multiple times in the segmentation. //You may assume the dictionary does not contain duplicate words. //Example 1: // //Input: //s = "catsanddog" //wordDict = ["cat", "cats", "and", "sand", "dog"] //Output: //[ // "cats and dog", // "cat sand dog" //] //Example 2: // //Input: //s = "pineapplepenapple" //wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] //Output: //[ // "pine apple pen apple", // "pineapple pen apple", // "pine applepen apple" //] //Explanation: Note that you are allowed to reuse a dictionary word. //Example 3: // //Input: //s = "catsandog" //wordDict = ["cats", "dog", "sand", "and", "cat"] //Output: //[] // import Foundation class Num140: Solution { // DP: // a standard DP will just require one state, which here is the result dictionary // However, since computing substirng needs some time. If we just start to collect // the results but finally found there's no solution, this is a waste of time. // // To optimize the efficiency, we can use word break I to check if there's a solution // Or not firstly // Once we know there's a solution. We start to compute the results (the real job). func wordBreak(_ str: String, _ wordDict: [String]) -> [String] { // isBreakable[i], substring [0, i) is breakable var isBreakable: [Bool] = Array(repeating: false, count: str.count + 1) isBreakable[0] = true for i in 1..<isBreakable.count { for j in (0...(i - 1)).reversed() { // if found s[j] is true, which is breakable for [0, j) // and // substring from [j to i] is in the wordDict, then s[i] is true if isBreakable[j] == true, wordDict.contains(str[j..<i]) { isBreakable[i] = true break // We only care if i is breakable or not. found one solution is good } } } // We want to confirm we do have a solution. Otherwise, just return empty array. // This can avoid unnecessary string/substring computation ahead. guard isBreakable[str.count] == true else { return [] } // result[i] stores the solutions for str[0..<i] var result: [Int: [String]] = [:] result[0] = [""] // s[i] is true for every j in 0..<i // 1) s[j] is true // 2) s[j..<i] is in the dict // 01234567 // leetcode, "leet", "code" // tffftffft // 0123456789 // "catsanddog" // result[0] = [""] // result[3] = ["cat"] // result[4] = ["cats"] // for index 7: result[7] is: // [["cats and"] // ["cat sand"]] for i in 1...str.count { // construct list of strings for i var stringsForI: [String] = [] for j in 0..<i { let substring = str[j..<i] if isBreakable[j] == true, wordDict.contains(substring) { // found a solution let stringsForJ = result[j]! // collect the one string for i stringsForI += stringsForJ.map { if $0 == "" { // to avoid unnecessary space return substring } else { return $0 + " " + substring } } } } result[i] = stringsForI } return result[str.count] ?? [] } func test() { print(wordBreak("catsanddog", ["cat","cats","and","sand","dog"])) } }
mit
29a923aa249d337765bf58f6b95393f1
28.587302
213
0.589324
3.493908
false
false
false
false
brentsimmons/Evergreen
iOS/Settings/AddExtensionViewContrller.swift
1
2022
// // AddExtensionViewContrller.swift // NetNewsWire-iOS // // Created by Maurice Parker on 4/16/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import UIKit protocol AddExtensionDismissDelegate: UIViewController { func dismiss() } class AddExtensionViewController: UITableViewController, AddExtensionDismissDelegate { private var availableExtensionPointTypes = [ExtensionPoint.Type]() override func viewDidLoad() { super.viewDidLoad() availableExtensionPointTypes = ExtensionPointManager.shared.availableExtensionPointTypes } override func numberOfSections(in tableView: UITableView) -> Int { 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return availableExtensionPointTypes.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 52.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsExtensionTableViewCell", for: indexPath) as! SettingsComboTableViewCell let extensionPointType = availableExtensionPointTypes[indexPath.row] cell.comboNameLabel?.text = extensionPointType.title cell.comboImage?.image = extensionPointType.templateImage return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let navController = UIStoryboard.settings.instantiateViewController(withIdentifier: "EnableExtensiontNavigationViewController") as! UINavigationController navController.modalPresentationStyle = .currentContext let enableViewController = navController.topViewController as! EnableExtensionViewController enableViewController.delegate = self enableViewController.extensionPointType = availableExtensionPointTypes[indexPath.row] present(navController, animated: true) } func dismiss() { navigationController?.popViewController(animated: false) } }
mit
5a3e060bfc03ce9e9e5a3b2af92a44b9
33.254237
156
0.804057
4.823389
false
false
false
false
dduan/swift
benchmark/single-source/DictionaryRemove.swift
1
2253
//===--- DictionaryRemove.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Dictionary element removal benchmark // rdar://problem/19804127 import TestsUtils @inline(never) public func run_DictionaryRemove(N: Int) { let size = 100 var dict = [Int: Int](minimumCapacity: size) // Fill dictionary for i in 1...size { dict[i] = i } CheckResults(dict.count == size, "Incorrect dict count: \(dict.count) != \(size).") var tmpDict = dict for _ in 1...1000*N { tmpDict = dict // Empty dictionary for i in 1...size { tmpDict.removeValue(forKey: i) } if !tmpDict.isEmpty { break } } CheckResults(tmpDict.isEmpty, "tmpDict should be empty: \(tmpDict.count) != 0.") } class Box<T : Hashable where T : Equatable> : Hashable { var value: T init(_ v: T) { value = v } var hashValue : Int { return value.hashValue } } extension Box : Equatable { } func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool { return lhs.value == rhs.value } @inline(never) public func run_DictionaryRemoveOfObjects(N: Int) { let size = 100 var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size) // Fill dictionary for i in 1...size { dict[Box(i)] = Box(i) } CheckResults(dict.count == size, "Incorrect dict count: \(dict.count) != \(size).") var tmpDict = dict for _ in 1...1000*N { tmpDict = dict // Empty dictionary for i in 1...size { tmpDict.removeValue(forKey: Box(i)) } if !tmpDict.isEmpty { break } } CheckResults(tmpDict.isEmpty, "tmpDict should be empty: \(tmpDict.count) != 0.") }
apache-2.0
fbc4a6fd93d42b95269d0c2ebac2aa25
24.033333
80
0.54949
4.141544
false
false
false
false
huangboju/HYAlertController
Carthage/Checkouts/SnapKit/Example-iOS/demos/SimpleLayoutViewController.swift
1
2715
// // SimpleLayoutViewController.swift // SnapKit // // Created by Spiros Gerokostas on 01/03/16. // Copyright © 2016 SnapKit Team. All rights reserved. // import UIKit class SimpleLayoutViewController: UIViewController { var didSetupConstraints = false let blackView: UIView = { let view = UIView() view.backgroundColor = .blackColor() return view }() let redView: UIView = { let view = UIView() view.backgroundColor = .redColor() return view }() let yellowView: UIView = { let view = UIView() view.backgroundColor = .yellowColor() return view }() let blueView: UIView = { let view = UIView() view.backgroundColor = .blueColor() return view }() let greenView: UIView = { let view = UIView() view.backgroundColor = .greenColor() return view }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() view.addSubview(blackView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(blueView) view.addSubview(greenView) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if !didSetupConstraints { blackView.snp_makeConstraints { make in make.center.equalTo(view) make.size.equalTo(CGSize(width: 100.0, height: 100.0)) } redView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.right.equalTo(blackView.snp_left).offset(-20.0) make.size.equalTo(CGSize(width: 100.0, height: 100.0)) } yellowView.snp_makeConstraints { make in make.top.equalTo(blackView.snp_bottom).offset(20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSize(width: 100.0, height: 100.0)) } blueView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.left.equalTo(blackView.snp_right).offset(20.0) make.size.equalTo(CGSize(width: 100.0, height: 100.0)) } greenView.snp_makeConstraints { make in make.bottom.equalTo(blackView.snp_top).offset(-20.0) make.right.equalTo(blackView.snp_left).offset(-20.0) make.size.equalTo(CGSize(width: 100.0, height: 100.0)) } didSetupConstraints = true } super.updateViewConstraints() } }
mit
9fcef2323b08685ae4fde26cbfab70b4
26.979381
70
0.580324
4.420195
false
false
false
false
NeilNie/Done-
Pods/Eureka/Source/Rows/DatePickerRow.swift
1
5471
// DateRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class DatePickerCell: Cell<Date>, CellType { @IBOutlet weak public var datePicker: UIDatePicker! public required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { let datePicker = UIDatePicker() self.datePicker = datePicker self.datePicker.translatesAutoresizingMaskIntoConstraints = false super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.datePicker) self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": self.datePicker])) self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": self.datePicker])) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func setup() { super.setup() selectionStyle = .none accessoryType = .none editingAccessoryType = .none height = { UITableView.automaticDimension } datePicker.datePickerMode = datePickerMode() datePicker.addTarget(self, action: #selector(DatePickerCell.datePickerValueChanged(_:)), for: .valueChanged) } deinit { datePicker?.removeTarget(self, action: nil, for: .allEvents) } open override func update() { super.update() selectionStyle = row.isDisabled ? .none : .default datePicker.isUserInteractionEnabled = !row.isDisabled detailTextLabel?.text = nil textLabel?.text = nil datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow) datePicker.minimumDate = (row as? DatePickerRowProtocol)?.minimumDate datePicker.maximumDate = (row as? DatePickerRowProtocol)?.maximumDate if let minuteIntervalValue = (row as? DatePickerRowProtocol)?.minuteInterval { datePicker.minuteInterval = minuteIntervalValue } } @objc func datePickerValueChanged(_ sender: UIDatePicker) { row?.value = sender.date // workaround for UIDatePicker bug when it doesn't trigger "value changed" event after trying to pick 00:00 value // for details see this comment: https://stackoverflow.com/questions/20181980/uidatepicker-bug-uicontroleventvaluechanged-after-hitting-minimum-internal#comment56681891_20204225 if sender.datePickerMode == .countDownTimer && sender.countDownDuration == TimeInterval(sender.minuteInterval * 60) { datePicker.countDownDuration = sender.countDownDuration } } private func datePickerMode() -> UIDatePicker.Mode { switch row { case is DatePickerRow: return .date case is TimePickerRow: return .time case is DateTimePickerRow: return .dateAndTime case is CountDownPickerRow: return .countDownTimer default: return .date } } } open class _DatePickerRow: Row<DatePickerCell>, DatePickerRowProtocol { open var minimumDate: Date? open var maximumDate: Date? open var minuteInterval: Int? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } /// A row with an Date as value where the user can select a date directly. public final class DatePickerRow: _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an Date as value where the user can select a time directly. public final class TimePickerRow: _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an Date as value where the user can select date and time directly. public final class DateTimePickerRow: _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an Date as value where the user can select hour and minute as a countdown timer. public final class CountDownPickerRow: _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } }
apache-2.0
bedea4b4909dfa7c6d8ee9b516368cba
37.801418
185
0.69384
4.773997
false
false
false
false
lioonline/v2ex-lio
V2ex/V2ex/NewFeedCell.swift
1
3324
// // NewFeedCell.swift // V2ex // // Created by Cocoa Lee on 9/29/15. // Copyright © 2015 lio. All rights reserved. // import UIKit import SnapKit class NewFeedCell: UITableViewCell { var vAvatar:UIButton = UIButton() var vName:UILabel = UILabel() var vTime:UILabel = UILabel() var vTitle:UILabel = UILabel() var vContent:UILabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: UITableViewCellStyle.Default, reuseIdentifier:"home") rendering() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func rendering() -> Void{ self.contentView.addSubview(vAvatar) vAvatar.layer.cornerRadius = 4 vAvatar.clipsToBounds = true vAvatar.snp_makeConstraints { (make) -> Void in make.top.equalTo(self.contentView).offset(10) make.left.equalTo(self.contentView).offset(10) make.height.width.equalTo(30) } // self.contentView.addSubview(vName) vName.text = "name(T)" vName.textColor = RGBA(119, g: 128, b: 135, a: 1) vName.font = UIFont.systemFontOfSize(12) vName.snp_makeConstraints { (make) -> Void in make.left.equalTo(vAvatar.snp_right).offset(10) make.top.equalTo(vAvatar.snp_top) } // self.contentView.addSubview(vTime) vTime.textColor = RGBA(204 , g: 204, b: 204, a: 1) vTime.text = "2015-09-23(T)" vTime.font = UIFont.systemFontOfSize(10) vTime .snp_updateConstraints { (make) -> Void in make.left.equalTo(vName.snp_left) make.top.equalTo(vName.snp_bottom).offset(5) } // // self.contentView.addSubview(vTitle) vTitle.text = "V2EX" vTitle.font = UIFont.systemFontOfSize(15) vTitle.textColor = RGBA(119, g: 128, b: 135, a: 1) vTitle.numberOfLines = 2 vTitle.lineBreakMode = NSLineBreakMode.ByTruncatingTail vTitle.snp_makeConstraints { (make) -> Void in make.left.equalTo(vTime.snp_left) make.top.equalTo(vAvatar.snp_bottom).offset(10) make.right.equalTo(self.contentView.snp_right).offset(-10) } // // self.contentView.addSubview(vContent) // vContent.font = UIFont.systemFontOfSize(12) // vContent.textColor = RGBA(110, g: 110, b: 110, a: 1) // vContent.snp_makeConstraints { (make) -> Void in // make.left.equalTo(vTitle.snp_left) // make.top.equalTo(vTitle.snp_bottom).offset(5) // make.right.equalTo(vTitle.snp_right) // make.bottom.equalTo(self.contentView.snp_bottom) // } // vContent.lineBreakMode = NSLineBreakMode.ByTruncatingTail // vContent.numberOfLines = 0 } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
569014f1e3d5e62a78ce6d9e07c5256c
27.895652
79
0.587421
3.965394
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Fatten Effect.xcplaygroundpage/Contents.swift
1
1669
//: ## Fatten Effect //: ### This is a cool fattening effect that Matthew Flecher wanted for the //: ### Analog Synth X project, so it was developed here in a playground first. import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true let fatten = AKOperationEffect(player) { input, parameters in let time = parameters[0] let mix = parameters[1] let fatten = "\(input) dup \(1 - mix) * swap 0 \(time) 1.0 vdelay \(mix) * +" return AKStereoOperation(fatten) } AudioKit.output = fatten AudioKit.start() player.play() fatten.parameters = [0.1, 0.5] //: User Interface Set up class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Analog Synth X Fatten") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: processingPlaygroundFiles)) addSubview(AKPropertySlider( property: "Time", format: "%0.3f s", value: fatten.parameters[0], minimum: 0.03, maximum: 0.1, color: AKColor.cyanColor() ) { sliderValue in fatten.parameters[0] = sliderValue }) addSubview(AKPropertySlider( property: "Mix", value: fatten.parameters[1], color: AKColor.cyanColor() ) { sliderValue in fatten.parameters[1] = sliderValue }) } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
efb620a2269447209954745b270c9aeb
25.078125
81
0.633313
4.392105
false
false
false
false
mpclarkson/vapor
Sources/Vapor/Core/Application.swift
1
8094
import libc public class Application { public static let VERSION = "0.5.3" /** The router driver is responsible for returning registered `Route` handlers for a given request. */ public lazy var router: RouterDriver = BranchRouter() /** The server driver is responsible for handling connections on the desired port. This property is constant since it cannot be changed after the server has been booted. */ public lazy var server: Server = HTTPStreamServer<Socket>() /** The session driver is responsible for storing and reading values written to the users session. */ public let session: SessionDriver /** Provides access to config settings. */ public lazy var config: Config = Config(application: self) /** Provides access to the underlying `HashDriver`. */ public let hash: Hash /** `Middleware` will be applied in the order it is set in this array. Make sure to append your custom `Middleware` if you don't want to overwrite default behavior. */ public var middleware: [Middleware] /** Provider classes that have been registered with this application */ public var providers: [Provider] /** Internal value populated the first time self.environment is computed */ private var detectedEnvironment: Environment? /** Current environment of the application */ public var environment: Environment { if let environment = self.detectedEnvironment { return environment } let environment = bootEnvironment() self.detectedEnvironment = environment return environment } /** Optional handler to be called when detecting the current environment. */ public var detectEnvironmentHandler: ((String) -> Environment)? /** The work directory of your application is the directory in which your Resources, Public, etc folders are stored. This is normally `./` if you are running Vapor using `.build/xxx/App` */ public var workDir = "./" { didSet { if self.workDir.characters.last != "/" { self.workDir += "/" } } } /** Resources directory relative to workDir */ public var resourcesDir: String { return workDir + "Resources/" } var scopedHost: String? var scopedMiddleware: [Middleware] = [] var scopedPrefix: String? var port: Int = 80 var ip: String = "0.0.0.0" var routes: [Route] = [] /** Initialize the Application. */ public init(sessionDriver: SessionDriver? = nil) { self.middleware = [ AbortMiddleware(), ] self.providers = [] let hash = Hash() self.session = sessionDriver ?? MemorySessionDriver(hash: hash) self.hash = hash self.middleware.append( SessionMiddleware(session: session) ) } public func bootProviders() { for provider in self.providers { provider.boot(self) } } func bootEnvironment() -> Environment { var environment: String if let value = Process.valueFor(argument: "env") { Log.info("Environment override: \(value)") environment = value } else { // TODO: This should default to "production" in release builds environment = "development" } if let handler = self.detectEnvironmentHandler { return handler(environment) } else { return Environment.fromString(environment) } } /** If multiple environments are passed, return value will be true if at least one of the passed in environment values matches the app environment and false if none of them match. If a single environment is passed, the return value will be true if the the passed in environment matches the app environment. */ public func inEnvironment(environments: Environment...) -> Bool { if environments.count == 1 { return self.environment == environments[0] } else { return environments.contains(self.environment) } } func bootRoutes() { routes.forEach(router.register) } func bootArguments() { //grab process args if let workDir = Process.valueFor(argument: "workDir") { Log.info("Work dir override: \(workDir)") self.workDir = workDir } if let ip = Process.valueFor(argument: "ip") { Log.info("IP override: \(ip)") self.ip = ip } if let port = Process.valueFor(argument: "port")?.int { Log.info("Port override: \(port)") self.port = port } } /** Boots the chosen server driver and optionally runs on the supplied ip & port overrides */ public func start(ip ip: String? = nil, port: Int? = nil) { self.ip = ip ?? self.ip self.port = port ?? self.port bootArguments() bootProviders() bootRoutes() if environment == .Production { Log.info("Production mode detected, disabling information logs.") Log.enabledLevels = [.Error, .Fatal] } do { Log.info("Server starting on \(self.ip):\(self.port)") try server.serve(self, on: self.ip, at: self.port) } catch { Log.error("Server start error: \(error)") } } func checkFileSystem(request: Request) -> Request.Handler? { // Check in file system let filePath = self.workDir + "Public" + (request.uri.path ?? "") guard FileManager.fileAtPath(filePath).exists else { return nil } // File exists if let fileBody = try? FileManager.readBytesFromFile(filePath) { return Request.Handler { _ in return Response(status: .ok, headers: [:], body: Data(fileBody)) } } else { return Request.Handler { _ in Log.warning("Could not open file, returning 404") return Response(status: .notFound, text: "Page not found") } } } } extension Application: Responder { public func respond(request: Request) throws -> Response { Log.info("\(request.method) \(request.uri.path ?? "/")") var responder: Responder var request = request request.parseData() // Check in routes if let (parameters, routerHandler) = router.route(request) { request.parameters = parameters responder = routerHandler } else if let fileHander = self.checkFileSystem(request) { responder = fileHander } else { // Default not found handler responder = Request.Handler { _ in return Response(status: .notFound, text: "Page not found") } } // Loop through middlewares in order for middleware in self.middleware { responder = middleware.intercept(responder) } var response: Response do { response = try responder.respond(request) if response.headers["Content-Type"].first == nil { Log.warning("Response had no 'Content-Type' header.") } } catch { var error = "Server Error: \(error)" if environment == .Production { error = "Something went wrong" } response = Response(error: error) } response.headers["Date"] = Response.Headers.Values(Response.date) response.headers["Server"] = Response.Headers.Values("Vapor \(Application.VERSION)") return response } }
mit
d6f8790063801290def49c57e4f8da44
26.719178
92
0.570299
4.920365
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/Controller/DetailGameViewController.swift
1
7672
// // DetailGameViewController.swift // MGDYZB // // Created by i-Techsys.com on 17/4/8. // Copyright © 2017年 ming. All rights reserved. // import UIKit import SafariServices class DetailGameViewController: BaseViewController { // MARK: - 懒加载属性 fileprivate lazy var detailGameVM : DetailGameViewModel = DetailGameViewModel() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = kItemMargin/2 layout.minimumInteritemSpacing = kItemMargin layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin/2, bottom: 0, right: kItemMargin/2) // 2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.dataSource = self collectionView.delegate = self return collectionView }() // MARK: - 系统方法 convenience init(model: BaseGameModel) { self.init(nibName: nil, bundle: nil) self.title = model.tag_name detailGameVM.tag_id = String(describing: model.tag_id) // 这个tag_id是用作url参数用的,具体你看ViewModel的两个url分析 } override func viewDidLoad() { super.viewDidLoad() setUpRefresh() if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: self.view) } } } override func setUpMainView() { contentView = collectionView view.addSubview(collectionView) super.setUpMainView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - loadData extension DetailGameViewController { fileprivate func loadData() { // 1.请求数据 detailGameVM.loadDetailGameData { [weak self] in // 1.1.刷新表格 self!.collectionView.header.endRefreshing() self!.collectionView.footer.endRefreshing() self?.collectionView.reloadData() // 1.2.数据请求完成 self?.loadDataFinished() } } fileprivate func setUpRefresh() { // MARK: - 下拉 self.collectionView.header = MJRefreshGifHeader(refreshingBlock: { [weak self]() -> Void in self!.detailGameVM.anchorGroups.removeAll() self!.detailGameVM.offset = 0 self!.loadData() }) // MARK: - 上拉 self.collectionView.footer = MJRefreshAutoGifFooter(refreshingBlock: {[weak self] () -> Void in self!.detailGameVM.offset += 20 self!.loadData() }) self.collectionView.header.isAutoChangeAlpha = true self.collectionView.header.beginRefreshing() self.collectionView.footer.noticeNoMoreData() } } // MARK: - UICollectionViewDataSource extension DetailGameViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return detailGameVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return detailGameVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell if detailGameVM.anchorGroups.count > 0 { cell.anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item] } return cell } } // MARK: - UICollectionViewDelegate extension DetailGameViewController: UICollectionViewDelegate { @objc(collectionView:viewForSupplementaryElementOfKind:atIndexPath:) func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给HeaderView设置数据 headerView.group = detailGameVM.anchorGroups[indexPath.section] return headerView } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1.取出对应的主播信息 let anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item] // 2.判断是秀场房间&普通房间 anchor.isVertical == 0 ? pushNormalRoomVc(anchor: anchor) : presentShowRoomVc(anchor: anchor) } fileprivate func presentShowRoomVc(anchor: AnchorModel) { if #available(iOS 9.0, *) { // 1.创建SFSafariViewController let safariVC = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) // 2.以Modal方式弹出 present(safariVC, animated: true, completion: nil) } else { let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) present(webVC, animated: true, completion: nil) } } fileprivate func pushNormalRoomVc(anchor: AnchorModel) { // 1.创建WebViewController let webVC = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) webVC.navigationController?.setNavigationBarHidden(true, animated: true) // 2.以Push方式弹出 navigationController?.pushViewController(webVC, animated: true) } } // MARK: - UIViewControllerPreviewingDelegate extension DetailGameViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) else { return nil } if #available(iOS 9.0, *) { previewingContext.sourceRect = cell.frame } var vc = UIViewController() let anchor = detailGameVM.anchorGroups[indexPath.section].anchors[indexPath.item] if anchor.isVertical == 0 { if #available(iOS 9, *) { vc = SFSafariViewController(url: URL(string: anchor.jumpUrl)!, entersReaderIfAvailable: true) } else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } }else { vc = WKWebViewController(navigationTitle: anchor.room_name, urlStr: anchor.jumpUrl) } return vc } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: nil) } }
mit
013dcd82c8de45d61391616dee833e23
38.571429
231
0.669608
5.407809
false
false
false
false
Trxy/TRX
Pods/Nimble-Snapshots/DynamicType/HaveValidDynamicTypeSnapshot.swift
2
4836
import Nimble import UIKit func allContentSizeCategories() -> [UIContentSizeCategory] { return [ .extraSmall, .small, .medium, .large, .extraLarge, .extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge ] } func shortCategoryName(_ category: UIContentSizeCategory) -> String { return category.rawValue.replacingOccurrences(of: "UICTContentSizeCategory", with: "") } func combinePredicates<T>(_ predicates: [Predicate<T>], ignoreFailures: Bool = false, deferred: (() -> Void)? = nil) -> Predicate<T> { return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in defer { deferred?() } return try predicates.reduce(true) { acc, matcher -> Bool in guard acc || ignoreFailures else { return false } let result = try matcher.matches(actualExpression, failureMessage: failureMessage) return result && acc } } } public func haveValidDynamicTypeSnapshot(named name: String? = nil, usesDrawRect: Bool = false, tolerance: CGFloat? = nil, sizes: [UIContentSizeCategory] = allContentSizeCategories(), isDeviceAgnostic: Bool = false) -> Predicate<Snapshotable> { let mock = NBSMockedApplication() let predicates: [Predicate<Snapshotable>] = sizes.map { category in let sanitizedName = sanitizedTestName(name) let nameWithCategory = "\(sanitizedName)_\(shortCategoryName(category))" return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in mock.mockPreferredContentSizeCategory(category) updateTraitCollection(on: actualExpression) let predicate: Predicate<Snapshotable> if isDeviceAgnostic { predicate = haveValidDeviceAgnosticSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect, tolerance: tolerance) } else { predicate = haveValidSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect, tolerance: tolerance) } return try predicate.matches(actualExpression, failureMessage: failureMessage) } } return combinePredicates(predicates) { mock.stopMockingPreferredContentSizeCategory() } } public func recordDynamicTypeSnapshot(named name: String? = nil, usesDrawRect: Bool = false, sizes: [UIContentSizeCategory] = allContentSizeCategories(), isDeviceAgnostic: Bool = false) -> Predicate<Snapshotable> { let mock = NBSMockedApplication() let predicates: [Predicate<Snapshotable>] = sizes.map { category in let sanitizedName = sanitizedTestName(name) let nameWithCategory = "\(sanitizedName)_\(shortCategoryName(category))" return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in mock.mockPreferredContentSizeCategory(category) updateTraitCollection(on: actualExpression) let predicate: Predicate<Snapshotable> if isDeviceAgnostic { predicate = recordDeviceAgnosticSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect) } else { predicate = recordSnapshot(named: nameWithCategory, usesDrawRect: usesDrawRect) } return try predicate.matches(actualExpression, failureMessage: failureMessage) } } return combinePredicates(predicates, ignoreFailures: true) { mock.stopMockingPreferredContentSizeCategory() } } private func updateTraitCollection(on expression: Expression<Snapshotable>) { // swiftlint:disable:next force_try force_unwrapping let instance = try! expression.evaluate()! updateTraitCollection(on: instance) } private func updateTraitCollection(on element: Snapshotable) { if let environment = element as? UITraitEnvironment { if let vc = environment as? UIViewController { vc.beginAppearanceTransition(true, animated: false) vc.endAppearanceTransition() } environment.traitCollectionDidChange(nil) if let view = environment as? UIView { view.subviews.forEach(updateTraitCollection(on:)) } else if let vc = environment as? UIViewController { vc.childViewControllers.forEach(updateTraitCollection(on:)) if vc.isViewLoaded { updateTraitCollection(on: vc.view) } } } }
mit
92b61737a043b2417707a8c5669c6fdc
39.3
120
0.645782
5.584296
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/Loaders/New Model/RootPlaylistsLoader.swift
1
1238
// // RootPlaylistsLoader.swift // iSub // // Created by Benjamin Baron on 1/4/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class RootPlaylistsLoader: ApiLoader, PersistedItemLoader { var playlists = [Playlist]() var associatedItem: Item? var items: [Item] { return playlists } override func createRequest() -> URLRequest? { return URLRequest(subsonicAction: .getPlaylists, serverId: serverId) } override func processResponse(root: RXMLElement) -> Bool { var playlistsTemp = [Playlist]() root.iterate("playlists.playlist") { playlist in if let aPlaylist = Playlist(rxmlElement: playlist, serverId: self.serverId) { playlistsTemp.append(aPlaylist) } } playlistsTemp.sort(by: {$0.name < $1.name}) playlists = playlistsTemp persistModels() return true } func persistModels() { playlists.forEach({$0.replace()}) } @discardableResult func loadModelsFromDatabase() -> Bool { playlists = PlaylistRepository.si.allPlaylists(serverId: serverId) return true } }
gpl-3.0
eadbb64a69da1a3f93256a70f65df59c
24.770833
89
0.609539
4.632959
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/finalProject/TotalTime/Source/Controller/HistoryViewController.swift
1
1976
// // HistoryViewController.swift // TotalTime // // Created by Dylan Secreast on 3/8/17. // Copyright © 2017 Dylan Secreast. All rights reserved. // import UIKit class HistoryViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var jobs: [Job] = [] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self } override func viewWillAppear(_ animated: Bool) { getData() tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return jobs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let job = jobs[indexPath.row] cell.textLabel?.text = job.title return cell } func getData() { let delegate = UIApplication.shared.delegate as! AppDelegate let context = delegate.persistentContainer.viewContext do { jobs = try context.fetch(Job.fetchRequest()) } catch { print("Error fetching jobs") } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let delegate = UIApplication.shared.delegate as! AppDelegate let context = delegate.persistentContainer.viewContext if editingStyle == .delete { let job = jobs[indexPath.row] context.delete(job) delegate.saveContext() do { jobs = try context.fetch(Job.fetchRequest()) } catch { print("Error fetching jobs") } } tableView.reloadData() } }
gpl-3.0
d05e88964e446a449313defe25487ef9
26.054795
127
0.589873
5.410959
false
false
false
false
lee0741/Glider
Glider/SearchController.swift
1
5624
// // SearchController.swift // Glider // // Created by Yancen Li on 2/26/17. // Copyright © 2017 Yancen Li. All rights reserved. // import UIKit class SearchController: UITableViewController { let cellId = "searchId" let defaults = UserDefaults.standard var editBarButtonItem: UIBarButtonItem? var savedSearches = [String]() var searchController: UISearchController! override func viewDidLoad() { super.viewDidLoad() configController() } func configController() { if let savedSearch = defaults.object(forKey: "SavedQuery") { savedSearches = savedSearch as! [String] } UIApplication.shared.statusBarStyle = .lightContent navigationItem.title = "Search" if savedSearches.count != 0 { editBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editAction)) navigationItem.setRightBarButton(editBarButtonItem, animated: true) } tableView = UITableView(frame: tableView.frame, style: .grouped) tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId) tableView.separatorColor = .separatorColor tableView.backgroundColor = .bgColor searchController = UISearchController(searchResultsController: nil) tableView.tableHeaderView = searchController.searchBar searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.tintColor = .mainColor searchController.searchBar.searchBarStyle = .minimal definesPresentationContext = true searchController.loadViewIfNeeded() NotificationCenter.default.addObserver(self, selector: #selector(defaultsChanged), name: UserDefaults.didChangeNotification, object: nil) let tap = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } func dismissKeyboard() { searchController.searchBar.resignFirstResponder() } func defaultsChanged() { if let savedSearch = defaults.object(forKey: "SavedQuery") { savedSearches = savedSearch as! [String] } if savedSearches.count == 0 { navigationItem.setRightBarButton(UIBarButtonItem(), animated: true) editBarButtonItem = nil } else { if editBarButtonItem == nil { editBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editAction)) navigationItem.setRightBarButton(editBarButtonItem, animated: true) } } tableView.reloadData() } func editAction() { if tableView.isEditing { navigationItem.rightBarButtonItem?.title = "Edit" tableView.setEditing(false, animated: true) } else { navigationItem.rightBarButtonItem?.title = "Done" tableView.setEditing(true, animated: true) } } // MARK: - Table View Data Source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Saved Searches" } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if savedSearches.count == 0 { return 1 } else { return savedSearches.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) if savedSearches.count == 0 { cell.textLabel?.text = "No saved searches found." cell.textLabel?.textColor = .lightGray cell.selectionStyle = .none cell.accessoryType = .none } else { cell.textLabel?.text = savedSearches[indexPath.row] cell.textLabel?.textColor = .mainTextColor cell.accessoryType = .disclosureIndicator } cell.textLabel?.font = UIFont(name: "AvenirNext-Medium", size: 17) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if savedSearches.count != 0 { let homeController = HomeController() homeController.query = savedSearches[indexPath.row] homeController.storyType = .search navigationController?.pushViewController(homeController, animated: true) } } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { savedSearches.remove(at: indexPath.row) if savedSearches.count == 0 { tableView.reloadData() tableView.setEditing(false, animated: true) } else { tableView.deleteRows(at: [indexPath], with: .fade) } defaults.set(savedSearches, forKey: "SavedQuery") defaults.synchronize() } } override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { if tableView.isEditing { return .delete } else { return .none } } } // MARK: - Search Delegate extension SearchController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { let homeController = HomeController() guard let query = searchBar.text else { return } homeController.query = query homeController.storyType = .search navigationController?.pushViewController(homeController, animated: true) } }
mit
50e9f4bc35aca4e3aa2a36b00ecfa5a3
31.50289
141
0.706207
5.07491
false
false
false
false
Osis/cf-apps-ios
CF Apps/Data/AccountStore.swift
1
2356
import Foundation import Locksmith import CFoundry // Accounts are stored in the Keychain. // Reference to those accounts are stored in NSUserDefaults. enum AccountError: Error { case notFound } public class AccountStore { class var accountsKey: String { return "Accounts" } class var accountListKey: String { return "AccountList" } public class func create(_ account: CFAccount) throws { do { try account.createInSecureStore() saveKey(account.account) } catch LocksmithError.duplicate { try account.updateInSecureStore() } if !exists(account.username, target: account.target) { saveKey(account.account) } } class func read(_ key: String) -> CFAccount? { if let data = Locksmith.loadDataForUserAccount(userAccount: key, inService: "CloudFoundry") { return CFAccount.deserialize(data) } return nil } public class func delete(_ account: CFAccount) throws { try account.deleteFromSecureStore() removeKey(account.account) } public class func exists(_ username: String, target: String) -> Bool { return list().contains { $0.account == "\(username)_\(target)" } } public class func list() -> [CFAccount] { var accounts = [CFAccount]() let keys = self.keyList() keys.forEach { let account = read($0 as! String) accounts.append(account!) } return accounts } class func isEmpty() -> Bool { return self.keyList().count == 0 } } private extension AccountStore { class func keyList() -> NSMutableArray { let savedKeys = UserDefaults.standard .array(forKey: accountListKey) if let keys = savedKeys { return NSMutableArray(array: keys) } return NSMutableArray() } class func saveKey(_ key: String) { let keyList = self.keyList().adding(key) UserDefaults.standard .set(keyList, forKey: accountListKey) } class func removeKey(_ key: String) { let list = self.keyList().filter { $0 as! String != key } UserDefaults.standard.set(list, forKey: accountListKey) } }
mit
5bc711f18fbc878b33c69a6ca5fa201e
26.395349
101
0.58871
4.665347
false
false
false
false
chrishulbert/gondola-appletv
Gondola TVOS/ViewControllers/MoviesViewController.swift
1
4175
// // MoviesViewController.swift // Gondola TVOS // // Created by Chris on 14/02/2017. // Copyright © 2017 Chris Hulbert. All rights reserved. // // Lists the movies. import UIKit class MoviesViewController: UIViewController { let metadata: GondolaMetadata init(metadata: GondolaMetadata) { self.metadata = metadata super.init(nibName: nil, bundle: nil) title = "Movies" } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var rootView = MoviesView() override func loadView() { view = rootView } override func viewDidLoad() { super.viewDidLoad() rootView.collection.register(PictureCell.self, forCellWithReuseIdentifier: "cell") rootView.collection.dataSource = self rootView.collection.delegate = self } } extension MoviesViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return metadata.movies.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let movie = metadata.movies[indexPath.item] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PictureCell cell.label.text = movie.name cell.image.image = nil cell.imageAspectRatio = 1.5 // TODO use a reusable image view? Or some helper that checks for stale? cell.imagePath = movie.image ServiceHelpers.imageRequest(path: movie.image) { result in DispatchQueue.main.async { if cell.imagePath == movie.image { // Cell hasn't been recycled? switch result { case .success(let image): cell.image.image = image case .failure(let error): NSLog("error: \(error)") // TODO show sad cloud image. } } } } return cell } } extension MoviesViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as? PictureCell let movie = metadata.movies[indexPath.item] let vc = MovieViewController(movie: movie, image: cell?.image.image) navigationController?.pushViewController(vc, animated: true) } } class MoviesView: UIView { let collection: UICollectionView init() { let size = UIScreen.main.bounds.size // TODO have a layout helper. let columns = 5 let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical let itemWidth = floor((size.width - 2*LayoutHelpers.sideMargins) / CGFloat(columns)) let itemHeight = PictureCell.height(forWidth: itemWidth, imageAspectRatio: 1.5) layout.itemSize = CGSize(width: itemWidth, height: itemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: LayoutHelpers.vertMargins, left: LayoutHelpers.sideMargins, bottom: LayoutHelpers.vertMargins, right: LayoutHelpers.sideMargins) collection = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout) let back = UIImageView(image: #imageLiteral(resourceName: "Background")) back.contentMode = .scaleAspectFill collection.backgroundView = back super.init(frame: CGRect.zero) addSubview(collection) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() collection.frame = bounds } }
mit
1a21cf045e43b61e6a05d594d4945c7d
31.107692
176
0.621945
5.276865
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift
1
4219
// // SessionDataTask.swift // Kingfisher // // Created by Wei Wang on 2018/11/1. // // Copyright (c) 2018年 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents a session data task in `ImageDownloader`. It consists of an underlying `URLSessionDataTask` and /// an array of `TaskCallback`. Multiple `TaskCallback`s could be added for a single downloading data task. public class SessionDataTask { /// Represents the type of token which used for cancelling a task. public typealias CancelToken = Int struct TaskCallback { let onProgress: Delegate<(Int64, Int64), Void>? let onCompleted: Delegate<Result<ImageLoadingResult, KingfisherError>, Void>? let options: KingfisherParsedOptionsInfo } /// Downloaded raw data of current task. public private(set) var mutableData: Data /// The underlying download task. It is only for debugging purpose when you encountered an error. You should not /// modify the content of this task or start it yourself. public let task: URLSessionDataTask private var callbacksStore = [CancelToken: TaskCallback]() var callbacks: Dictionary<SessionDataTask.CancelToken, SessionDataTask.TaskCallback>.Values { return callbacksStore.values } private var currentToken = 0 private let lock = NSLock() let onTaskDone = Delegate<(Result<(Data, URLResponse?), KingfisherError>, [TaskCallback]), Void>() let onCallbackCancelled = Delegate<(CancelToken, TaskCallback), Void>() var started = false var containsCallbacks: Bool { // We should be able to use `task.state != .running` to check it. // However, in some rare cases, cancelling the task does not change // task state to `.cancelling` immediately, but still in `.running`. // So we need to check callbacks count to for sure that it is safe to remove the // task in delegate. return !callbacks.isEmpty } init(task: URLSessionDataTask) { self.task = task mutableData = Data() } func addCallback(_ callback: TaskCallback) -> CancelToken { lock.lock() defer { lock.unlock() } callbacksStore[currentToken] = callback defer { currentToken += 1 } return currentToken } func removeCallback(_ token: CancelToken) -> TaskCallback? { lock.lock() defer { lock.unlock() } if let callback = callbacksStore[token] { callbacksStore[token] = nil return callback } return nil } func resume() { guard !started else { return } started = true task.resume() } func cancel(token: CancelToken) { guard let callback = removeCallback(token) else { return } if callbacksStore.count == 0 { task.cancel() } onCallbackCancelled.call((token, callback)) } func forceCancel() { for token in callbacksStore.keys { cancel(token: token) } } func didReceiveData(_ data: Data) { mutableData.append(data) } }
mit
599bdf2889a9cc3a66567baba78d2ce4
34.737288
116
0.672753
4.669989
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/SobelEdgeDetectionThreshold.swift
1
1496
// // SobelEdgeDetectionThreshold.swift // Pods // // Created by Mohssen Fathi on 5/9/16. // // import UIKit struct SobelEdgeDetectionThresholdUniforms: Uniforms { var threshold: Float = 0.5; } public class SobelEdgeDetectionThreshold: Filter { var uniforms = SobelEdgeDetectionThresholdUniforms() let sobelEdgeDetectionFilter = SobelEdgeDetection() @objc public var threshold: Float = 0.5 { didSet { clamp(&threshold, low: 0, high: 1) needsUpdate = true } } @objc public var edgeStrength: Float = 0.0 { didSet { sobelEdgeDetectionFilter.edgeStrength = edgeStrength } } public init() { super.init(functionName: "sobelEdgeDetectionThreshold") title = "Sobel Edge Detection Threshold" properties = [Property(key: "threshold", title: "Threshold"), Property(key: "edgeStrength", title: "Edge Strength")] sobelEdgeDetectionFilter.addTarget(self) input = sobelEdgeDetectionFilter update() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } uniforms.threshold = threshold updateUniforms(uniforms: uniforms) } public override func process() { super.process() sobelEdgeDetectionFilter.process() } }
mit
1178d614db8dd3b8cd3fa92706b4bca7
23.129032
76
0.604278
4.465672
false
false
false
false
williamshowalter/DOTlog_iOS
DOTlog/Support Files/AppDelegate.swift
1
6135
// // AppDelegate.swift // DOTlog // // Created by William Showalter on 15/02/28. // Copyright (c) 2015 UAF CS Capstone 2015. 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. UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.darkGrayColor()], forState: .Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Selected) 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 "DOTlog.DOTlog" 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("DOTlog", 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("DOTlog.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. let dict = NSMutableDictionary() 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 as [NSObject : AnyObject]) // 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
2d280061bebafdf10e433a66ce9d5499
53.292035
287
0.752893
5.367454
false
false
false
false
zsheikh-systango/WordPower
Skeleton/Pods/NotificationBannerSwift/NotificationBanner/Classes/BaseNotificationBanner.swift
2
17270
/* The MIT License (MIT) Copyright (c) 2017 Dalton Hinterscher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import SnapKit #if CARTHAGE_CONFIG import MarqueeLabelSwift #else import MarqueeLabel #endif public protocol NotificationBannerDelegate: class { func notificationBannerWillAppear(_ banner: BaseNotificationBanner) func notificationBannerDidAppear(_ banner: BaseNotificationBanner) func notificationBannerWillDisappear(_ banner: BaseNotificationBanner) func notificationBannerDidDisappear(_ banner: BaseNotificationBanner) } public class BaseNotificationBanner: UIView { /// The delegate of the notification banner public weak var delegate: NotificationBannerDelegate? /// The height of the banner when it is presented public var bannerHeight: CGFloat { get { if let customBannerHeight = customBannerHeight { return customBannerHeight } else { return shouldAdjustForIphoneX() ? 88.0 : 64.0 } } set { customBannerHeight = newValue } } /// The topmost label of the notification if a custom view is not desired public internal(set) var titleLabel: MarqueeLabel? /// The time before the notificaiton is automatically dismissed public var duration: TimeInterval = 5.0 { didSet { updateMarqueeLabelsDurations() } } /// If false, the banner will not be dismissed until the developer programatically dismisses it public var autoDismiss: Bool = true { didSet { if !autoDismiss { dismissOnTap = false dismissOnSwipeUp = false } } } /// The type of haptic to generate when a banner is displayed public var haptic: BannerHaptic = .heavy /// If true, notification will dismissed when tapped public var dismissOnTap: Bool = true /// If true, notification will dismissed when swiped up public var dismissOnSwipeUp: Bool = true /// Closure that will be executed if the notification banner is tapped public var onTap: (() -> Void)? /// Closure that will be executed if the notification banner is swiped up public var onSwipeUp: (() -> Void)? /// Wether or not the notification banner is currently being displayed public private(set) var isDisplaying: Bool = false /// The view that the notification layout is presented on. The constraints/frame of this should not be changed internal var contentView: UIView! /// A view that helps the spring animation look nice when the banner appears internal var spacerView: UIView! /// The default padding between edges and views internal var padding: CGFloat = 15.0 /// The view controller to display the banner on. This is useful if you are wanting to display a banner underneath a navigation bar internal weak var parentViewController: UIViewController? /// If this is not nil, then this height will be used instead of the auto calculated height internal var customBannerHeight: CGFloat? /// Used by the banner queue to determine wether a notification banner was placed in front of it in the queue var isSuspended: Bool = false /// Responsible for positioning and auto managing notification banners private let bannerQueue: NotificationBannerQueue = NotificationBannerQueue.default /// The main window of the application which banner views are placed on private let appWindow: UIWindow = UIApplication.shared.delegate!.window!! /// The position the notification banner should slide in from private(set) var bannerPosition: BannerPosition! /// Object that stores the start and end frames for the notification banner based on the provided banner position private var bannerPositionFrame: BannerPositionFrame! /// The user info that gets passed to each notification private var notificationUserInfo: [String: BaseNotificationBanner] { return [NotificationBanner.BannerObjectKey: self] } public override var backgroundColor: UIColor? { get { return contentView.backgroundColor } set { contentView.backgroundColor = newValue spacerView.backgroundColor = newValue } } init(style: BannerStyle, colors: BannerColorsProtocol? = nil) { super.init(frame: .zero) spacerView = UIView() addSubview(spacerView) contentView = UIView() addSubview(contentView) if let colors = colors { backgroundColor = colors.color(for: style) } else { backgroundColor = BannerColors().color(for: style) } let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: #selector(onSwipeUpGestureRecognizer)) swipeUpGesture.direction = .up addGestureRecognizer(swipeUpGesture) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } /** Creates the proper banner constraints based on the desired banner position */ private func createBannerConstraints(for bannerPosition: BannerPosition) { spacerView.snp.remakeConstraints { (make) in if bannerPosition == .top { make.top.equalToSuperview().offset(-10) } else { make.bottom.equalToSuperview().offset(10) } make.left.equalToSuperview() make.right.equalToSuperview() updateSpacerViewHeight(make: make) } contentView.snp.remakeConstraints { (make) in if bannerPosition == .top { make.top.equalTo(spacerView.snp.bottom) make.bottom.equalToSuperview() } else { make.top.equalToSuperview() make.bottom.equalTo(spacerView.snp.top) } make.left.equalToSuperview() make.right.equalToSuperview() } } /** Updates the spacer view height. Specifically used for orientation changes. */ private func updateSpacerViewHeight(make: ConstraintMaker? = nil) { let finalHeight = NotificationBannerUtilities.isiPhoneX() && UIApplication.shared.statusBarOrientation.isPortrait && parentViewController == nil ? 40.0 : 10.0 if let make = make { make.height.equalTo(finalHeight) } else { spacerView.snp.updateConstraints({ (make) in make.height.equalTo(finalHeight) }) } } /** Dismisses the NotificationBanner and shows the next one if there is one to show on the queue */ @objc public func dismiss() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil) NotificationCenter.default.post(name: NotificationBanner.BannerWillDisappear, object: self, userInfo: notificationUserInfo) delegate?.notificationBannerWillDisappear(self) UIView.animate(withDuration: 0.5, animations: { self.frame = self.bannerPositionFrame.startFrame }) { (completed) in self.removeFromSuperview() self.isDisplaying = false NotificationCenter.default.post(name: NotificationBanner.BannerDidDisappear, object: self, userInfo: self.notificationUserInfo) self.delegate?.notificationBannerDidDisappear(self) self.bannerQueue.showNext(callback: { (isEmpty) in if isEmpty || self.statusBarShouldBeShown() { self.appWindow.windowLevel = UIWindowLevelNormal } }) } } /** Places a NotificationBanner on the queue and shows it if its the first one in the queue - parameter queuePosition: The position to show the notification banner. If the position is .front, the banner will be displayed immediately - parameter viewController: The view controller to display the notifification banner on. If nil, it will be placed on the main app window - parameter bannerPosition: The position the notification banner should slide in from */ public func show(queuePosition: QueuePosition = .back, bannerPosition: BannerPosition = .top, on viewController: UIViewController? = nil) { parentViewController = viewController show(placeOnQueue: true, queuePosition: queuePosition, bannerPosition: bannerPosition) } /** Places a NotificationBanner on the queue and shows it if its the first one in the queue - parameter placeOnQueue: If false, banner will not be placed on the queue and will be showed/resumed immediately - parameter queuePosition: The position to show the notification banner. If the position is .front, the banner will be displayed immediately - parameter bannerPosition: The position the notification banner should slide in from */ func show(placeOnQueue: Bool, queuePosition: QueuePosition = .back, bannerPosition: BannerPosition = .top) { if bannerPositionFrame == nil { self.bannerPosition = bannerPosition createBannerConstraints(for: bannerPosition) bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition, bannerWidth: appWindow.frame.width, bannerHeight: bannerHeight, maxY: maximumYPosition()) } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanged), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) if placeOnQueue { bannerQueue.addBanner(self, queuePosition: queuePosition) } else { self.frame = bannerPositionFrame.startFrame if let parentViewController = parentViewController { parentViewController.view.addSubview(self) if statusBarShouldBeShown() { appWindow.windowLevel = UIWindowLevelNormal } } else { appWindow.addSubview(self) if statusBarShouldBeShown() && !(parentViewController == nil && bannerPosition == .top) { appWindow.windowLevel = UIWindowLevelNormal } else { appWindow.windowLevel = UIWindowLevelStatusBar + 1 } } NotificationCenter.default.post(name: NotificationBanner.BannerWillAppear, object: self, userInfo: notificationUserInfo) delegate?.notificationBannerWillAppear(self) UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveLinear, animations: { BannerHapticGenerator.generate(self.haptic) self.frame = self.bannerPositionFrame.endFrame }) { (completed) in NotificationCenter.default.post(name: NotificationBanner.BannerDidAppear, object: self, userInfo: self.notificationUserInfo) self.delegate?.notificationBannerDidAppear(self) self.isDisplaying = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTapGestureRecognizer)) self.addGestureRecognizer(tapGestureRecognizer) /* We don't want to add the selector if another banner was queued in front of it before it finished animating or if it is meant to be shown infinitely */ if !self.isSuspended && self.autoDismiss { self.perform(#selector(self.dismiss), with: nil, afterDelay: self.duration) } } } } /** Suspends a notification banner so it will not be dismissed. This happens because a new notification banner was placed in front of it on the queue. */ func suspend() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil) isSuspended = true isDisplaying = false } /** Resumes a notification banner immediately. */ func resume() { if autoDismiss { self.perform(#selector(dismiss), with: nil, afterDelay: self.duration) isSuspended = false isDisplaying = true } } /** Changes the frame of the notificaiton banner when the orientation of the device changes */ @objc private dynamic func onOrientationChanged() { updateSpacerViewHeight() self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: appWindow.frame.width, height: bannerHeight) bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition, bannerWidth: appWindow.frame.width, bannerHeight: bannerHeight, maxY: maximumYPosition()) } /** Called when a notification banner is tapped */ @objc private dynamic func onTapGestureRecognizer() { if dismissOnTap { dismiss() } onTap?() } /** Called when a notification banner is swiped up */ @objc private dynamic func onSwipeUpGestureRecognizer() { if dismissOnSwipeUp { dismiss() } onSwipeUp?() } /** Determines wether or not the status bar should be shown when displaying a banner underneath the navigation bar */ private func statusBarShouldBeShown() -> Bool { for banner in bannerQueue.banners { if (banner.parentViewController == nil && banner.bannerPosition == .top) { return false } } return true } /** Calculates the maximum `y` position that a notification banner can slide in from */ private func maximumYPosition() -> CGFloat { if let parentViewController = parentViewController { return parentViewController.view.frame.height } else { return appWindow.frame.height } } /** Determines wether or not we should adjust the banner for the iPhoneX */ internal func shouldAdjustForIphoneX() -> Bool { return NotificationBannerUtilities.isiPhoneX() && UIApplication.shared.statusBarOrientation.isPortrait && parentViewController == nil } /** Updates the scrolling marquee label duration */ internal func updateMarqueeLabelsDurations() { titleLabel?.speed = .duration(CGFloat(duration - 3)) } }
mit
1bd33cb729e8077a36a585c41f3c8590
38.976852
154
0.613086
5.806994
false
false
false
false
diyfj1989/FJCycleScrollView
swiftLunBoTest/FJCycleScrollView/FJCycleScrollView.swift
1
6728
// // FJCycleScrollView.swift // swiftLunBoTest // // Created by fengjie on 16/11/17. // Copyright © 2016年 hanzgrp. All rights reserved. // import UIKit import SDWebImage public protocol FJCycleScrollViewDelegata { //点击图片的位置 func cycleScrollView(_ cycleScrollView:FJCycleScrollView, didSelectAt index: Int) } extension FJCycleScrollViewDelegata { //点击图片的位置 func cycleScrollView(_ cycleScrollView:FJCycleScrollView, didSelectAt index: Int){ } } open class FJCycleScrollView: UIView, UICollectionViewDelegate, UICollectionViewDataSource { fileprivate let baseNum:Int = 100 open var scrollInterval:Double = 5 fileprivate var timer:Timer? open var autoScroll:Bool = true { didSet{ timer?.invalidate() timer = nil if autoScroll { configTimer() } } } //url图片 open var images:[UIImage]? { didSet{ if let _ = images { imageStrs = nil if autoScroll { configTimer() } } else { timer?.invalidate() timer = nil } collectionView?.reloadData() } } open var imageStrs:[String]? { didSet{ if let _ = imageStrs { images = nil if autoScroll { configTimer() } } else { timer?.invalidate() timer = nil } collectionView?.reloadData() } } open var titles:[String]? { didSet{ if let count = titles?.count { pageControl?.numberOfPages = count } else { pageControl?.numberOfPages = 0 } collectionView?.reloadData() } } var collectionView:UICollectionView? open var pageControl:UIPageControl? open var delegata: FJCycleScrollViewDelegata? open var titleColor:UIColor? open var titleFont:UIFont? open var titleBackgroundColor:UIColor? open var titleAlignmet:NSTextAlignment? override public init(frame: CGRect) { super.init(frame: frame) configView() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate func configView() { let layout = UICollectionViewFlowLayout.init() layout.scrollDirection = UICollectionViewScrollDirection.horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.itemSize = bounds.size collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout) collectionView?.backgroundColor = UIColor.white collectionView?.showsHorizontalScrollIndicator = false collectionView?.isPagingEnabled = true collectionView?.delegate = self collectionView?.dataSource = self collectionView?.register(FJCycleScrollCell.self, forCellWithReuseIdentifier: "FJCycleScrollCell") addSubview(collectionView!) pageControl = UIPageControl(frame: CGRect(x: 0, y: bounds.height - 20, width: bounds.width, height: 20)) pageControl!.backgroundColor = UIColor.black.withAlphaComponent(0.1) pageControl!.hidesForSinglePage = true addSubview(pageControl!) } fileprivate func configTimer () { timer = Timer.scheduledTimer(timeInterval: scrollInterval, target: self, selector: #selector(atuomaticScroll), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .commonModes) } func atuomaticScroll() { var page:Int = Int(Float((self.collectionView?.contentOffset.x)! + 0.5 * (self.collectionView?.frame.width)!) / Float((self.collectionView?.frame.width)!)) page += 1 if (page >= self.baseNum * (self.titles?.count)!) { page = 0 } self.collectionView?.scrollToItem(at: IndexPath(row: page, section: 0), at: UICollectionViewScrollPosition.centeredHorizontally, animated: true) } open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let count = titles?.count { return count * baseNum } else { return 0 } } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell:FJCycleScrollCell = collectionView.dequeueReusableCell(withReuseIdentifier: "FJCycleScrollCell", for: indexPath) as! FJCycleScrollCell cell.titleLabel?.textColor = titleColor ?? UIColor.white cell.titleLabel?.font = titleFont ?? UIFont.systemFont(ofSize: 16) cell.titleBackgroundView?.backgroundColor = titleBackgroundColor ?? UIColor.black.withAlphaComponent(0.1) cell.titleLabel?.textAlignment = titleAlignmet ?? NSTextAlignment.left let index:Int = indexPath.row % (self.titles?.count)! if let _imageStrs = imageStrs { if index < _imageStrs.count { cell.imageView?.sd_setImage(with: URL(string: _imageStrs[index])) } } else if let _images = images { if index < _images.count { cell.imageView?.image = _images[index] } } if let title = titles?[index] { cell.titleLabel?.text = title } return cell } open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let index = indexPath.row % (self.titles?.count)! delegata?.cycleScrollView(self, didSelectAt: index) } open func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView == collectionView { var page:Int! = Int(Float((self.collectionView?.contentOffset.x)! + 0.5 * (self.collectionView?.frame.width)!) / Float((self.collectionView?.frame.width)!)) page = page % (self.titles?.count)! pageControl?.currentPage = page } } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if autoScroll { timer?.invalidate() timer = nil } } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if autoScroll { timer?.invalidate() timer = nil configTimer() } } }
gpl-3.0
3102c7b995aae5b303cfccb7664aa626
31.64878
168
0.601524
5.220749
false
false
false
false
pmlbrito/WeatherExercise
WeatherExercise/Presentation/City/CityLocationDetailPresenter.swift
1
1389
// // CityLocationDetailPresenter.swift // WeatherExercise // // Created by Pedro Brito on 12/05/2017. // Copyright © 2017 BringGlobal. All rights reserved. // import UIKit protocol CityLocationDetailPresenterProtocol: BasePresenterProtocol { func loadWeather(location: LocationModel) } class CityLocationDetailPresenter: CityLocationDetailPresenterProtocol { var view: CityLocationDetailViewController? func loadWeather(location: LocationModel) { if self.view == nil { return } (self.view! as UIViewController).showLoadingOverlay() APIDataManager.getTodaysWeather(location: location, completionHandler: { (weather, error) in DispatchQueue.main.async { (self.view! as UIViewController).hideLoadingOverlay() if error != nil { (self.view! as UIViewController).showError(error: error!) return } if weather != nil { self.view?.renderLocationWeather(weather: weather!) } } }) } } //MARK: - BasePresenterProtocol Implementation extension CityLocationDetailPresenter { func bindView(view: UIViewController) { self.view = view as? CityLocationDetailViewController } }
mit
c0f4c4b356616d90931cf1f3c381c776
27.326531
100
0.60879
5.277567
false
false
false
false
tdgunes/TDGMessageKit
TDGMessageKit/TDGMessageBox.swift
1
7266
// // TDGMessageBox.swift // Deformity // // Created by Taha Doğan Güneş on 07/07/15. // Copyright (c) 2015 Taha Doğan Güneş. All rights reserved. // import UIKit extension Int { var toRadians : CGFloat { return CGFloat(self) * CGFloat(M_PI) / 180.0 } } public class TDGMessageBox: UIView { public typealias OnTapCallBack = ()->() @IBOutlet public weak var titleLabel: UILabel! @IBOutlet public weak var imageView: UIImageView! @IBOutlet public weak var bodyLabel: UILabel! public var onTap: OnTapCallBack? public var view: UIView! let height = CGFloat(52) public var orientation: Orientation? public enum Orientation { case Top case Bottom } func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "TDGMessageBox", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil).first as! UIView return view } func finalizeXibSetup() { view = loadViewFromNib() view.frame = bounds view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight addSubview(view) } public convenience init(orientation:Orientation) { self.init(frame:CGRectZero) self.orientation = orientation self.setupRecognizers() } override init(frame: CGRect) { super.init(frame: frame) finalizeXibSetup() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) finalizeXibSetup() } public func addTo(view:UIView){ self.hidden = true view.addSubview(self) self.calculateFrame() NSNotificationCenter.defaultCenter().addObserver(self, selector: "deviceOrientationDidChangeNotification:", name: UIDeviceOrientationDidChangeNotification, object: nil) } func calculateFrame() { if let oriented = self.orientation { let screenWidth = self.getScreenWidth() let statusBarHeight = self.getStatusBarHeight() switch oriented { case .Top: var viewYPosition = -self.height if (!self.hidden) { viewYPosition = statusBarHeight } self.frame = CGRectMake(CGFloat(0), statusBarHeight, screenWidth, self.height) break case .Bottom: let screenHeight = self.getScreenHeight() var viewYPosition = screenHeight if (!self.hidden) { viewYPosition -= self.height } self.frame = CGRectMake(CGFloat(0), viewYPosition, screenWidth, self.height) break } } } func setupRecognizers() { var recognizer = UITapGestureRecognizer(target: self, action: "handleTapFrom:") recognizer.numberOfTapsRequired = 1 self.addGestureRecognizer(recognizer) } func handleTapFrom(recognizer:UITapGestureRecognizer) { println("Tap to messageBox") if let callback = self.onTap { callback() } } public func toggle() { if let oriented = self.orientation { switch oriented { case .Bottom: println("animateButtomUp()") if self.hidden { self.animateBottomUp() } else { self.animateBottomDown() } break case .Top: if self.hidden { self.animateTopDown() } else { self.animateTopUp() } break } } } public func focus() { let normal:CGAffineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, 0.toRadians) let leftWooble:CGAffineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, -1.toRadians) let rightWooble:CGAffineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, 1.toRadians) self.transform = leftWooble UIView.animateWithDuration(0.120, delay: 0.0, options: UIViewAnimationOptions.Autoreverse , animations: { self.transform = rightWooble }, completion: { finished in self.transform = normal }) } public func hide() { if let oriented = self.orientation { switch oriented { case .Bottom: println("animateButtomDown()") if !self.hidden { self.animateBottomDown() } break case .Top: if !self.hidden { self.animateTopUp() } break } } } public func whiten() { self.titleLabel.textColor = UIColor.whiteColor() self.bodyLabel.textColor = UIColor.whiteColor() self.imageView.tintColor = UIColor.whiteColor() self.imageView.image = self.imageView.image!.imageWithRenderingMode(.AlwaysTemplate) } func deviceOrientationDidChangeNotification(notification:NSNotification) { self.calculateFrame() } private func animateBottomDown(){ UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.frame.origin.y += self.frame.size.height }, completion: {finished in self.hidden = true }) } private func animateBottomUp() { self.hidden = false UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.frame.origin.y -= self.frame.size.height }, completion: {finished in } ) } private func animateTopDown() { self.hidden = false UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.frame.origin.y += self.frame.size.height }, completion: {finished in } ) } private func animateTopUp() { UIView.animateWithDuration(0.5, delay: 0.1, options: UIViewAnimationOptions.CurveEaseOut, animations: { self.frame.origin.y -= self.frame.size.height }, completion: {finished in self.hidden = true }) } private func getScreenHeight() ->CGFloat { return UIScreen.mainScreen().bounds.size.height } private func getScreenWidth() ->CGFloat { return UIScreen.mainScreen().applicationFrame.width } private func getStatusBarHeight()->CGFloat { return UIApplication.sharedApplication().statusBarFrame.size.height } }
mit
a7294f33110359c80de876a6730f0f5c
28.04
176
0.559229
5.389755
false
false
false
false
jalehman/twitter-clone
TwitterClient/TweetsTableViewController.swift
1
4435
// // TweetsTableViewController.swift // TwitterClient // // Created by Josh Lehman on 2/19/15. // Copyright (c) 2015 Josh Lehman. All rights reserved. // import UIKit class TweetsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: Properties var refreshControl: UIRefreshControl! var loadingHUD: JGProgressHUD! @IBOutlet weak var tweetsTable: UITableView! private let viewModel: TweetsTableViewModel private var composeButton: UIBarButtonItem! // MARK: API init(viewModel: TweetsTableViewModel) { self.viewModel = viewModel super.init(nibName: "TweetsTableViewController", bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.tweets.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = viewModel.tweets[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("tweetCell") as! TweetTableViewCell cell.bindViewModel(item) return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = viewModel.tweets[indexPath.row] tableView.deselectRowAtIndexPath(indexPath, animated: true) viewModel.executeViewTweetDetails.execute(item) } // MARK: UIViewController Overrides override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = .None tweetsTable.dataSource = self tweetsTable.delegate = self refreshControl = UIRefreshControl() tweetsTable.registerNib(UINib(nibName: "TweetTableViewCell", bundle: nil), forCellReuseIdentifier: "tweetCell") tweetsTable.estimatedRowHeight = 88.0 tweetsTable.rowHeight = UITableViewAutomaticDimension tweetsTable.insertSubview(refreshControl, atIndex: 0) // Twitter style back button with back arrow only let newBackButton = UIBarButtonItem(title: "", style: .Bordered, target: nil, action: nil) newBackButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal) self.navigationItem.backBarButtonItem = newBackButton composeButton = UIBarButtonItem(barButtonSystemItem: .Compose, target: nil, action: "") bindViewModel() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) view.setNeedsUpdateConstraints() tweetsTable.reloadData() navigationController?.topViewController.navigationItem.rightBarButtonItem = composeButton RACObserve(viewModel, "showing").mapAs { (title: NSString) -> NSString in return title.capitalizedString }.subscribeNextAs { (title: NSString) in self.navigationController?.topViewController.navigationItem.title = title as String } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) view.setNeedsUpdateConstraints() tweetsTable.reloadData() } // MARK: Private private func bindViewModel() { composeButton.rac_command = viewModel.executeShowComposeTweet refreshControl.rac_command = viewModel.executeFetchTweets viewModel.executeFetchTweets.execute("home") let fetchTweetsExecutingSignal = viewModel.executeFetchTweets.executing fetchTweetsExecutingSignal.subscribeNext { [weak self] _ in if self!.loadingHUD == nil { self!.loadingHUD = JGProgressHUD(style: .Dark) self!.loadingHUD.textLabel.text = "Loading..." } self!.loadingHUD.showInView(self!.view) } fetchTweetsExecutingSignal.not().subscribeNext { [weak self] _ in self!.loadingHUD.dismiss() } RACObserve(viewModel, "tweets").subscribeNext {[weak self] _ in self!.tweetsTable.reloadData() } } }
gpl-2.0
7fbad5bea5ede40c7c626cc5b2a54f01
33.115385
119
0.66336
5.693196
false
false
false
false
luispadron/GradePoint
GradePoint/Controllers/Settings/GradePercentagesTableViewController.swift
1
9555
// // GradePercentagesTableViewController.swift // GradePoint // // Created by Luis Padron on 5/4/18. // Copyright © 2018 Luis Padron. All rights reserved. // import UIKit import RealmSwift class GradePercentagesTableViewController: UITableViewController { /// The rows which will contain any + or - fields private let plusRows = [0, 2, 3, 5, 6, 8, 9, 11] /// The realm notifcation token for listening to changes on the GPAScale private var notifToken: NotificationToken? /// The grade percentage views, 1 per cell that the table statically displays @IBOutlet var percentageViews: [UIGradePercentageView]! // The header view for the table, displays an info message to the user with a reset button in the middle @IBOutlet var headerView: UIView! override func viewDidLoad() { super.viewDidLoad() // UI Setup if #available(iOS 11.0, *) { self.navigationItem.largeTitleDisplayMode = .never } // TableView customization self.tableView.tableFooterView = UIView(frame: CGRect.zero) self.tableView.separatorColor = ApplicationTheme.shared.tableViewSeperatorColor self.tableView.estimatedRowHeight = 60 // Add save button self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.onSaveTapped)) // Update headerview style (self.headerView.subviews[0] as! UILabel).textColor = ApplicationTheme.shared.mainTextColor() (self.headerView.subviews[1] as! UIButton).setTitleColor(ApplicationTheme.shared.highlightColor, for: .normal) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Initialize all the grade percentage views self.updateFields() // Add header view self.tableView.tableHeaderView = self.headerView } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override var shouldAutorotate: Bool { return false } // MARK: - Table view methods override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if GPAScale.shared.scaleType == .nonPlusScale && plusRows.contains(indexPath.row) { return 0 } else { return 60 } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 13 } // MARK: - Actions @objc private func onSaveTapped(button: UIBarButtonItem) { guard let newPercentages = self.verifyPercentages() else { return } let title = NSAttributedString(string: "Save Percentages") let msg = NSAttributedString(string: "Are you sure you want to save percentages? If done incorrectly this can lead to undefined behavior") let alert = UIBlurAlertController(size: CGSize(width: 300, height: 200), title: title, message: msg) let cancelButton = UIButton(type: .custom) cancelButton.setTitle("Cancel", for: .normal) cancelButton.setTitleColor(.white, for: .normal) cancelButton.backgroundColor = .info alert.addButton(button: cancelButton, handler: nil) let resetButton = UIButton(type: .custom) resetButton.setTitle("Save", for: .normal) resetButton.setTitleColor(.white, for: .normal) resetButton.backgroundColor = .warning alert.addButton(button: resetButton, handler: { [weak self] in self?.savePercentages(newPercentages) }) alert.presentAlert(presentingViewController: self) } @IBAction func resetButtonTapped(_ sender: UIButton) { let title = NSAttributedString(string: "Reset To Default") let msg = NSAttributedString(string: "Are you sure you want to reset to default? This cant be undone") let alert = UIBlurAlertController(size: CGSize(width: 300, height: 200), title: title, message: msg) let cancelButton = UIButton(type: .custom) cancelButton.setTitle("Cancel", for: .normal) cancelButton.setTitleColor(.white, for: .normal) cancelButton.backgroundColor = .info alert.addButton(button: cancelButton, handler: nil) let resetButton = UIButton(type: .custom) resetButton.setTitle("Reset", for: .normal) resetButton.setTitleColor(.white, for: .normal) resetButton.backgroundColor = .warning alert.addButton(button: resetButton, handler: self.resetPercentages) alert.presentAlert(presentingViewController: self) } // MARK: - Heleprs private func updateFields() { // Disable the upperbound field of the A+ or A since the upperbound is anything greater than lowerbound switch GPAScale.shared.scaleType { case .plusScale: percentageViews.first?.upperLowerMode = false case .nonPlusScale: percentageViews[1].upperLowerMode = false } var rangeIndex = 0 for (index, view) in percentageViews.enumerated() { view.lowerBoundField.font = UIFont.systemFont(ofSize: 18) view.upperBoundField.font = UIFont.systemFont(ofSize: 18) view.lowerBoundField.tintColor = ApplicationTheme.shared.highlightColor view.upperBoundField.tintColor = ApplicationTheme.shared.highlightColor view.lowerBoundField.textColor = ApplicationTheme.shared.highlightColor view.upperBoundField.textColor = ApplicationTheme.shared.highlightColor let attrs = [NSAttributedString.Key.foregroundColor: ApplicationTheme.shared.secondaryTextColor(), NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)] if GPAScale.shared.scaleType == .nonPlusScale && self.plusRows.contains(index) { continue } if rangeIndex == 0 { view.lowerBoundField.attributedPlaceholder = NSAttributedString(string: "\(GradeRubric.shared.percentage(for: rangeIndex, type: .lowerBound))% +", attributes: attrs) } else { view.lowerBoundField.attributedPlaceholder = NSAttributedString(string: "\(GradeRubric.shared.percentage(for: rangeIndex, type: .lowerBound))%", attributes: attrs) } view.upperBoundField.attributedPlaceholder = NSAttributedString(string: "\(GradeRubric.shared.percentage(for: rangeIndex, type: .upperBound))%", attributes: attrs) rangeIndex += 1 } } private func resetFields() { for view in self.percentageViews { view.lowerBoundField.text = nil view.upperBoundField.text = nil } } /// Recalculates all grades associated with all class objects in Realm /// Called after reset/save private func recalculateGradesForClasses() { let classes = DatabaseManager.shared.realm.objects(Class.self) DatabaseManager.shared.write { for classObj in classes.filter({ $0.isInProgress }) { classObj.grade?.gradeLetter = Grade.gradeLetter(for: classObj.grade!.score) } } } private func resetPercentages() { GradeRubric.createRubric(type: GPAScale.shared.scaleType) self.recalculateGradesForClasses() self.resetFields() self.updateFields() } private func verifyPercentages() -> [ClosedRange<Double>]? { let percentages = DatabaseManager.shared.realm.objects(GradePercentage.self) var newPercentages = [ClosedRange<Double>]() // Verify that all ranges are valid var percentIndex = 0 for (index, view) in self.percentageViews.enumerated() { if GPAScale.shared.scaleType == .nonPlusScale && self.plusRows.contains(index) { continue } var newLowerBound: Double = percentages[percentIndex].lowerBound var newUpperBound: Double = percentages[percentIndex].upperBound if view.lowerBoundField.safeText.isValid() { newLowerBound = Double(view.lowerBoundField.safeText)! } if view.upperBoundField.safeText.isValid() { newUpperBound = Double(view.upperBoundField.safeText)! } if newLowerBound >= newUpperBound { self.presentErrorAlert(title: "Error Saving 💔", message: "Lower bound for grade #\(percentIndex + 1) must be less than upper bound") return nil } newPercentages.append(newLowerBound...newUpperBound) percentIndex += 1 } return newPercentages } /// Saves the results of percentage changes by updating percentage objects and recalculating grades for classes private func savePercentages(_ newPercentages: [ClosedRange<Double>]) { let percentages = DatabaseManager.shared.realm.objects(GradePercentage.self) DatabaseManager.shared.write { for (index, newPercentage) in newPercentages.enumerated() { percentages[index].lowerBound = newPercentage.lowerBound percentages[index].upperBound = newPercentage.upperBound } } self.recalculateGradesForClasses() self.resetFields() self.updateFields() } }
apache-2.0
7b11d1db1bcec9d2847970f5b86cb533
38.304527
181
0.659617
4.995293
false
false
false
false
OviB/my-notes
My Notes/My Notes/DetailViewController.swift
1
2108
// // DetailViewController.swift // My Notes // // Created by Ovidiu Bortas on 4/11/16. // Copyright © 2016 Ovidiu Bortas. All rights reserved. // import UIKit class DetailViewController: UIViewController, UITextViewDelegate{ @IBOutlet weak var detailDescriptionLabel: UITextView! var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if objects.count == 0 { return } if let label = self.detailDescriptionLabel { label.text = objects[currentIndex] if label.text == BLANK_NOTE { label.text = "" } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. detailViewController = self detailDescriptionLabel.becomeFirstResponder() detailDescriptionLabel.delegate = self self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if objects.count == 0 { return } // update the text typed in objects[currentIndex] = detailDescriptionLabel.text // If text is empty update with empty string if detailDescriptionLabel.text == "" { objects[currentIndex] = BLANK_NOTE } saveAndUpdate() } // Tells the master to save data func saveAndUpdate() { masterView?.save() masterView?.tableView.reloadData() } func textViewDidChange(textView: UITextView) { objects[currentIndex] = detailDescriptionLabel.text saveAndUpdate() } }
mit
5496a1eb88893a349ff905432746e973
23.218391
80
0.570005
5.530184
false
false
false
false
danielgindi/ios-charts
Source/Charts/Renderers/RadarChartRenderer.swift
1
18051
// // RadarChartRenderer.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 RadarChartRenderer: LineRadarRenderer { private lazy var accessibilityXLabels: [String] = { guard let chart = chart else { return [] } guard let formatter = chart.xAxis.valueFormatter else { return [] } let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0 return stride(from: 0, to: maxEntryCount, by: 1).map { formatter.stringForValue(Double($0), axis: chart.xAxis) } }() @objc open weak var chart: RadarChartView? @objc public init(chart: RadarChartView, animator: Animator, viewPortHandler: ViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart } open override func drawData(context: CGContext) { guard let chart = chart, let radarData = chart.data as? RadarChartData else { return } let mostEntries = radarData.maxEntryCountSet?.entryCount ?? 0 // If we redraw the data, remove and repopulate accessible elements to update label values and frames self.accessibleChartElements.removeAll() // Make the chart header the first element in the accessible elements array let element = createAccessibleHeader(usingChart: chart, andData: radarData, withDefaultDescription: "Radar Chart") self.accessibleChartElements.append(element) for case let set as RadarChartDataSetProtocol in radarData where set.isVisible { drawDataSet(context: context, dataSet: set, mostEntries: mostEntries) } } /// Draws the RadarDataSet /// /// - Parameters: /// - context: /// - dataSet: /// - mostEntries: the entry count of the dataset with the most entries internal func drawDataSet(context: CGContext, dataSet: RadarChartDataSetProtocol, mostEntries: Int) { guard let chart = chart else { return } context.saveGState() let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let entryCount = dataSet.entryCount let path = CGMutablePath() var hasMovedToPoint = false let prefix: String = chart.data?.accessibilityEntryLabelPrefix ?? "Item" let description = dataSet.label ?? "" // Make a tuple of (xLabels, value, originalIndex) then sort it // This is done, so that the labels are narrated in decreasing order of their corresponding value // Otherwise, there is no non-visual logic to the data presented let accessibilityEntryValues = Array(0 ..< entryCount).map { (dataSet.entryForIndex($0)?.y ?? 0, $0) } let accessibilityAxisLabelValueTuples = zip(accessibilityXLabels, accessibilityEntryValues).map { ($0, $1.0, $1.1) }.sorted { $0.1 > $1.1 } let accessibilityDataSetDescription: String = description + ". \(entryCount) \(prefix + (entryCount == 1 ? "" : "s")). " let accessibilityFrameWidth: CGFloat = 22.0 // To allow a tap target of 44x44 var accessibilityEntryElements: [NSUIAccessibilityElement] = [] for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } let p = center.moving(distance: CGFloat((e.y - chart.chartYMin) * Double(factor) * phaseY), atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) if p.x.isNaN { continue } if !hasMovedToPoint { path.move(to: p) hasMovedToPoint = true } else { path.addLine(to: p) } let accessibilityLabel = accessibilityAxisLabelValueTuples[j].0 let accessibilityValue = accessibilityAxisLabelValueTuples[j].1 let accessibilityValueIndex = accessibilityAxisLabelValueTuples[j].2 let axp = center.moving(distance: CGFloat((accessibilityValue - chart.chartYMin) * Double(factor) * phaseY), atAngle: sliceangle * CGFloat(accessibilityValueIndex) * CGFloat(phaseX) + chart.rotationAngle) let axDescription = description + " - " + accessibilityLabel + ": \(accessibilityValue) \(chart.data?.accessibilityEntryLabelSuffix ?? "")" let axElement = createAccessibleElement(withDescription: axDescription, container: chart, dataSet: dataSet) { (element) in element.accessibilityFrame = CGRect(x: axp.x - accessibilityFrameWidth, y: axp.y - accessibilityFrameWidth, width: 2 * accessibilityFrameWidth, height: 2 * accessibilityFrameWidth) } accessibilityEntryElements.append(axElement) } // if this is the largest set, close it if dataSet.entryCount < mostEntries { // if this is not the largest set, draw a line to the center before closing path.addLine(to: center) } path.closeSubpath() // draw filled if dataSet.isDrawFilledEnabled { if dataSet.fill != nil { drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha) } else { drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha) } } // draw the line (only if filled is disabled or alpha is below 255) if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0 { context.setStrokeColor(dataSet.color(atIndex: 0).cgColor) context.setLineWidth(dataSet.lineWidth) context.setAlpha(1.0) context.beginPath() context.addPath(path) context.strokePath() let axElement = createAccessibleElement(withDescription: accessibilityDataSetDescription, container: chart, dataSet: dataSet) { (element) in element.isHeader = true element.accessibilityFrame = path.boundingBoxOfPath } accessibleChartElements.append(axElement) accessibleChartElements.append(contentsOf: accessibilityEntryElements) } accessibilityPostLayoutChangedNotification() context.restoreGState() } open override func drawValues(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets let yoffset = CGFloat(5.0) for i in data.indices { guard let dataSet = data[i] as? RadarChartDataSetProtocol, shouldDrawValues(forDataSet: dataSet) else { continue } let angleRadians = dataSet.valueLabelAngle.DEG2RAD let entryCount = dataSet.entryCount let iconsOffset = dataSet.iconsOffset for j in 0 ..< entryCount { guard let e = dataSet.entryForIndex(j) else { continue } let p = center.moving(distance: CGFloat(e.y - chart.chartYMin) * factor * CGFloat(phaseY), atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) let valueFont = dataSet.valueFont let formatter = dataSet.valueFormatter if dataSet.isDrawValuesEnabled { context.drawText(formatter.stringForValue(e.y, entry: e, dataSetIndex: i, viewPortHandler: viewPortHandler), at: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .center, angleRadians: angleRadians, attributes: [.font: valueFont, .foregroundColor: dataSet.valueTextColorAt(j)]) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var pIcon = center.moving(distance: CGFloat(e.y) * factor * CGFloat(phaseY) + iconsOffset.y, atAngle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle) pIcon.y += iconsOffset.x context.drawImage(icon, atCenter: CGPoint(x: pIcon.x, y: pIcon.y), size: icon.size) } } } } open override func drawExtras(context: CGContext) { drawWeb(context: context) } private var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) @objc open func drawWeb(context: CGContext) { guard let chart = chart, let data = chart.data else { return } let sliceangle = chart.sliceAngle context.saveGState() // calculate the factor that is needed for transforming the value to // pixels let factor = chart.factor let rotationangle = chart.rotationAngle let center = chart.centerOffsets // draw the web lines that come from the center context.setLineWidth(chart.webLineWidth) context.setStrokeColor(chart.webColor.cgColor) context.setAlpha(chart.webAlpha) let xIncrements = 1 + chart.skipWebLineCount let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0 for i in stride(from: 0, to: maxEntryCount, by: xIncrements) { let p = center.moving(distance: CGFloat(chart.yRange) * factor, atAngle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } // draw the inner-web context.setLineWidth(chart.innerWebLineWidth) context.setStrokeColor(chart.innerWebColor.cgColor) context.setAlpha(chart.webAlpha) let labelCount = chart.yAxis.entryCount for j in 0 ..< labelCount { for i in 0 ..< data.entryCount { let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor let p1 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i) + rotationangle) let p2 = center.moving(distance: r, atAngle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y context.strokeLineSegments(between: _webLineSegmentsBuffer) } } context.restoreGState() } private var _highlightPointBuffer = CGPoint() open override func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let chart = chart, let radarData = chart.data as? RadarChartData else { return } context.saveGState() let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value pixels let factor = chart.factor let center = chart.centerOffsets for high in indices { guard let set = chart.data?[high.dataSetIndex] as? RadarChartDataSetProtocol, set.isHighlightEnabled else { continue } guard let e = set.entryForIndex(Int(high.x)) as? RadarChartDataEntry else { continue } if !isInBoundsX(entry: e, dataSet: set) { continue } context.setLineWidth(radarData.highlightLineWidth) if radarData.highlightLineDashLengths != nil { context.setLineDash(phase: radarData.highlightLineDashPhase, lengths: radarData.highlightLineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.setStrokeColor(set.highlightColor.cgColor) let y = e.y - chart.chartYMin _highlightPointBuffer = center.moving(distance: CGFloat(y) * factor * CGFloat(animator.phaseY), atAngle: sliceangle * CGFloat(high.x) * CGFloat(animator.phaseX) + chart.rotationAngle) high.setDraw(pt: _highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) if set.isDrawHighlightCircleEnabled { if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN { var strokeColor = set.highlightCircleStrokeColor if strokeColor == nil { strokeColor = set.color(atIndex: 0) } if set.highlightCircleStrokeAlpha < 1.0 { strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha) } drawHighlightCircle( context: context, atPoint: _highlightPointBuffer, innerRadius: set.highlightCircleInnerRadius, outerRadius: set.highlightCircleOuterRadius, fillColor: set.highlightCircleFillColor, strokeColor: strokeColor, strokeWidth: set.highlightCircleStrokeWidth) } } } context.restoreGState() } internal func drawHighlightCircle( context: CGContext, atPoint point: CGPoint, innerRadius: CGFloat, outerRadius: CGFloat, fillColor: NSUIColor?, strokeColor: NSUIColor?, strokeWidth: CGFloat) { context.saveGState() if let fillColor = fillColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) if innerRadius > 0.0 { context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0)) } context.setFillColor(fillColor.cgColor) context.fillPath(using: .evenOdd) } if let strokeColor = strokeColor { context.beginPath() context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0)) context.setStrokeColor(strokeColor.cgColor) context.setLineWidth(strokeWidth) context.strokePath() } context.restoreGState() } private func createAccessibleElement(withDescription description: String, container: RadarChartView, dataSet: RadarChartDataSetProtocol, modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) element.accessibilityLabel = description // The modifier allows changing of traits and frame depending on highlight, rotation, etc modifier(element) return element } }
apache-2.0
482e53740c80feca4df375342b215da0
37.488273
151
0.539139
5.819149
false
false
false
false
navneetrattanpal/IOS
StudentTeacherApp/ViewController.swift
1
2453
// // ViewController.swift // StudentTeacherApp // // Created by josna jose on 2015-12-19. // Copyright (c) 2015 Group. All rights reserved. // import UIKit import Parse import ParseUI class ViewController: UIViewController { @IBOutlet var Name: UITextField! @IBOutlet var Password: UITextField! @IBOutlet var Role: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func Loginbtn(sender: AnyObject) { login() } func login() { let user = PFUser() user.username = Name.text user.password = Password.text PFUser.logInWithUsernameInBackground(Name.text, password: Password.text, block: { (User : PFUser?, Error : NSError?) -> Void in if Error == nil{ dispatch_async(dispatch_get_main_queue()) { var Storyboard = UIStoryboard(name: "Main", bundle: nil) var MainVC : UIViewController = Storyboard.instantiateViewControllerWithIdentifier("MainVC") as! UIViewController self.presentViewController(MainVC, animated: true, completion: nil) } } else{ NSLog("wrong!!") } }) } @IBAction func Signbtn(sender: AnyObject) { } func signup() { let user = PFUser() user.username = Name.text user.password = Password.text user.setObject(Role.text, forKey: "Role") // user.addObject(roleField.text, forKey: "Role") user.saveInBackground() // other fields can be set if you want to save more information user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if error == nil { // Hooray! Let them use the app now. } else { // Examine the error object and inform the user. } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
7c33a59159fc502490ed8a11fb12c3dd
23.777778
120
0.520587
5.379386
false
false
false
false
HarrisLee/Utils
MySampleCode-master/SwiftMysterious/SwiftMysterious/LoopLabel.swift
1
983
// // LoopLabel.swift // SwiftMysterious // // Created by 张星宇 on 16/1/29. // Copyright © 2016年 zxy. All rights reserved. // import Foundation let firstNames = ["Neil","Kt","Bob"] let lastNames = ["Zhou","Zhang","Wang","Li"] func normalBreak() { print("\n正常的break循环") for firstName in firstNames { var isFound = false for lastName in lastNames { if firstName == "Kt" && lastName == "Zhang" { isFound = true break } print(firstName + " " + lastName) } if isFound { break } } } func breakWithLoopLabel() { print("\n使用循环标签的break循环") outsideloop: for firstName in firstNames { innerloop: for lastName in lastNames { if firstName == "Kt" && lastName == "Zhang" { break outsideloop } print(firstName + " " + lastName) } } }
mit
a50fd78c667d6e9661349f77c543d390
21.52381
57
0.516913
4.008475
false
false
false
false
iOSreverse/DWWB
DWWB/DWWB/Classes/Main(主要)/OAuth/UserAccountViewModel.swift
1
1092
// // UserAccountViewModel.swift // DWWB // // Created by xmg on 16/4/8. // Copyright © 2016年 NewDee. All rights reserved. // import UIKit class UserAccountViewModel { // MARK: - 姜磊设计成单例 static let shareIntance : UserAccountViewModel = UserAccountViewModel() // MARK: - 定义属性 var account : UserAccount? // MARK: - 计算属性 var accountPath : String { let accountPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! return (accountPath as NSString).stringByAppendingPathComponent("account.plist") } var isLogin : Bool { if account == nil { return false } guard let expiresDate = account?.expires_date else { return false } return expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending } // MARK: - 重写init()函数 init () { // 1.从沙盒中读取归档的信息 account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount } }
apache-2.0
3ad8c1a98cbf1e754f2613c4df40025d
22.386364
111
0.641399
4.635135
false
false
false
false
jkolb/Shkadov
Sources/Utility/Duration.swift
1
3092
/* The MIT License (MIT) Copyright (c) 2016 Justin Kolb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public struct Duration: Comparable, Equatable { public static let zero = Duration(nanoseconds: 0) public var nanoseconds: TimeType public init(seconds: Double) { precondition(seconds >= 0.0) self.nanoseconds = TimeType(seconds * Double(Time.nanosecondsPerSecond)) } public init(milliseconds: TimeType) { self.nanoseconds = milliseconds * Time.millisecondsPerNanosecond } public init(nanoseconds: TimeType) { self.nanoseconds = nanoseconds } public var milliseconds: TimeType { return nanoseconds / Time.millisecondsPerNanosecond } public var seconds: Double { return Double(nanoseconds) / Double(Time.nanosecondsPerSecond) } public static func ==(a: Duration, b: Duration) -> Bool { return a.nanoseconds == b.nanoseconds } public static func <(a: Duration, b: Duration) -> Bool { return a.nanoseconds < b.nanoseconds } public static func +(a: Duration, b: Duration) -> Duration { return Duration(nanoseconds: a.nanoseconds + b.nanoseconds) } public static func -(a: Duration, b: Duration) -> Duration { return Duration(nanoseconds: a.nanoseconds - b.nanoseconds) } public static func *(a: Duration, b: TimeType) -> Duration { return Duration(nanoseconds: a.nanoseconds * b) } public static func /(a: Duration, b: TimeType) -> Duration { return Duration(nanoseconds: a.nanoseconds / b) } public static func +=(a: inout Duration, b: Duration) { a.nanoseconds = a.nanoseconds + b.nanoseconds } public static func -=(a: inout Duration, b: Duration) { a.nanoseconds = a.nanoseconds - b.nanoseconds } public static func *=(a: inout Duration, b: TimeType) { a.nanoseconds = a.nanoseconds * b } public static func /=(a: inout Duration, b: TimeType) { a.nanoseconds = a.nanoseconds / b } }
mit
9046259f65162d8bc0a2da6e6205fc1e
33.355556
80
0.686611
4.580741
false
false
false
false
thebnich/firefox-ios
Storage/SuggestedSites.swift
14
1333
/* 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 XCGLogger import UIKit import Shared private let log = XCGLogger.defaultInstance() public class SuggestedSite: Site { public let wordmark: Favicon public let backgroundColor: UIColor let trackingId: Int init(data: SuggestedSiteData) { self.backgroundColor = UIColor(colorString: data.bgColor) self.trackingId = data.trackingId self.wordmark = Favicon(url: data.imageUrl, date: NSDate(), type: .Icon) super.init(url: data.url, title: data.title) self.icon = Favicon(url: data.faviconUrl, date: NSDate(), type: .Icon) } } public let SuggestedSites: SuggestedSitesCursor = SuggestedSitesCursor() public class SuggestedSitesCursor: ArrayCursor<SuggestedSite> { private init() { let sites = DefaultSuggestedSites.sites let tiles = sites.map({data in SuggestedSite(data: data)}) super.init(data: tiles, status: .Success, statusMessage: "Loaded") } } public struct SuggestedSiteData { var url: String var bgColor: String var imageUrl: String var faviconUrl: String var trackingId: Int var title: String }
mpl-2.0
c1df227aacb781ecb701746cb13bb2d5
30.738095
80
0.700675
4.126935
false
false
false
false
devpunk/velvet_room
Source/Controller/Connected/CConnected.swift
1
1600
import UIKit final class CConnected:Controller<ArchConnected> { //MARK: private private func confirmClose() { model.closeConnection() } //MARK: internal func close() { let alert:UIAlertController = UIAlertController( title:String.localizedController(key:"CConnected_alertCloseTitle"), message:nil, preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title:String.localizedController(key:"CConnected_alertCloseCancel"), style:UIAlertActionStyle.cancel) let actionAccept:UIAlertAction = UIAlertAction( title:String.localizedController(key:"CConnected_alertCloseAccept"), style:UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.confirmClose() } alert.addAction(actionAccept) alert.addAction(actionCancel) if let popover:UIPopoverPresentationController = alert.popoverPresentationController { popover.sourceView = view popover.sourceRect = CGRect.zero popover.permittedArrowDirections = UIPopoverArrowDirection.up } present(alert, animated:true, completion:nil) } func connectionClosed() { DispatchQueue.main.async { [weak self] in self?.parentController?.pop( horizontal:ControllerParent.Horizontal.right) } } }
mit
2ee961b77c842203baf472768959ac7b
28.090909
92
0.6125
5.714286
false
false
false
false
alex-alex/S2Geometry
Sources/S2CellId.swift
1
32305
// // S2CellId.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif /** An S2CellId is a 64-bit unsigned integer that uniquely identifies a cell in the S2 cell decomposition. It has the following format: ``` id = [face][face_pos] ``` face: a 3-bit number (range 0..5) encoding the cube face. face_pos: a 61-bit number encoding the position of the center of this cell along the Hilbert curve over this face (see the Wiki pages for details). Sequentially increasing cell ids follow a continuous space-filling curve over the entire sphere. They have the following properties: - The id of a cell at level k consists of a 3-bit face number followed by k bit pairs that recursively select one of the four children of each cell. The next bit is always 1, and all other bits are 0. Therefore, the level of a cell is determined by the position of its lowest-numbered bit that is turned on (for a cell at level k, this position is 2 * (MAX_LEVEL - k).) - The id of a parent cell is at the midpoint of the range of ids spanned by its children (or by its descendants at any level). Leaf cells are often used to represent points on the unit sphere, and this class provides methods for converting directly between these two representations. For cells that represent 2D regions rather than discrete point, it is better to use the S2Cell class. */ public struct S2CellId: Comparable, Hashable { // Although only 60 bits are needed to represent the index of a leaf // cell, we need an extra bit in order to represent the position of // the center of the leaf cell along the Hilbert curve. public static let faceBits = 3 public static let numFaces = 6 public static let maxLevel = 30 // Valid levels: 0..MAX_LEVEL public static let posBits = 2 * maxLevel + 1 public static let maxSize = 1 << maxLevel // The following lookup tables are used to convert efficiently between an // (i,j) cell index and the corresponding position along the Hilbert curve. // "lookup_pos" maps 4 bits of "i", 4 bits of "j", and 2 bits representing the // orientation of the current cell into 8 bits representing the order in which // that subcell is visited by the Hilbert curve, plus 2 bits indicating the // new orientation of the Hilbert curve within that subcell. (Cell // orientations are represented as combination of kSwapMask and kInvertMask.) // // "lookup_ij" is an inverted table used for mapping in the opposite // direction. // // We also experimented with looking up 16 bits at a time (14 bits of position // plus 2 of orientation) but found that smaller lookup tables gave better // performance. (2KB fits easily in the primary cache.) // Values for these constants are *declared* in the *.h file. Even though // the declaration specifies a value for the constant, that declaration // is not a *definition* of storage for the value. Because the values are // supplied in the declaration, we don't need the values here. Failing to // define storage causes link errors for any code that tries to take the // address of one of these values. private static let lookupBits = 4 private static let swapMask = 0x01 private static let invertMask = 0x02 private static var lookupLoaded = false private static var lookup: (pos: [Int], ij: [Int]) = { return (pos: Array(repeating: 0, count: 1 << (2 * lookupBits + 2)), ij: Array(repeating: 0, count: 1 << (2 * lookupBits + 2))) }() private static var lookupPos: [Int] { loadLookup() return lookup.pos } private static var lookupIj: [Int] { loadLookup() return lookup.ij } private static func loadLookup() { guard !lookupLoaded else { return } S2CellId.initLookupCell(level: 0, i: 0, j: 0, origOrientation: 0, pos: 0, orientation: 0) S2CellId.initLookupCell(level: 0, i: 0, j: 0, origOrientation: swapMask, pos: 0, orientation: swapMask) S2CellId.initLookupCell(level: 0, i: 0, j: 0, origOrientation: invertMask, pos: 0, orientation: invertMask) S2CellId.initLookupCell(level: 0, i: 0, j: 0, origOrientation: swapMask | invertMask, pos: 0, orientation: swapMask | invertMask) lookupLoaded = true } /** This is the offset required to wrap around from the beginning of the Hilbert curve to the end or vice versa; see next_wrap() and prev_wrap(). */ private static let wrapOffset = Int64((numFaces) << posBits) public let id: Int64 public var uid: UInt64 { return UInt64(bitPattern: id) } public init(id: Int64 = 0) { self.id = id } public init(uid: UInt64) { self.id = Int64(bitPattern: uid) } public static let none = S2CellId() public static let sentinel = S2CellId(id: .max) /** Return a cell given its face (range 0..5), 61-bit Hilbert curve position within that face, and level (range 0..MAX_LEVEL). The given position will be modified to correspond to the Hilbert curve position at the center of the returned cell. This is a static function rather than a constructor in order to give names to the arguments. */ public init(face: Int, pos: Int64, level: Int) { let id = Int64(face << S2CellId.posBits) + (pos | 1) self = S2CellId(id: id).parent(level: level) } /// Return the leaf cell containing the given point (a direction vector, not necessarily unit length). public init(point p: S2Point) { let face = S2Projections.xyzToFace(point: p) let uv = S2Projections.validFaceXyzToUv(face: face, point: p) let i = S2CellId.stToIJ(s: S2Projections.uvToST(u: uv.x)) let j = S2CellId.stToIJ(s: S2Projections.uvToST(u: uv.y)) self.init(face: face, i: i, j: j) } /// Return the leaf cell containing the given S2LatLng. public init(latlng: S2LatLng) { self.init(point: latlng.point) } public var point: S2Point { return S2Point.normalize(point: rawPoint) } /** Return the direction vector corresponding to the center of the given cell. The vector returned by ToPointRaw is not necessarily unit length. */ public var rawPoint: S2Point { // First we compute the discrete (i,j) coordinates of a leaf cell contained // within the given cell. Given that cells are represented by the Hilbert // curve position corresponding at their center, it turns out that the cell // returned by ToFaceIJOrientation is always one of two leaf cells closest // to the center of the cell (unless the given cell is a leaf cell itself, // in which case there is only one possibility). // // Given a cell of size s >= 2 (i.e. not a leaf cell), and letting (imin, // jmin) be the coordinates of its lower left-hand corner, the leaf cell // returned by ToFaceIJOrientation() is either (imin + s/2, jmin + s/2) // (imin + s/2 - 1, jmin + s/2 - 1). We can distinguish these two cases by // looking at the low bit of "i" or "j". In the first case the low bit is // zero, unless s == 2 (i.e. the level just above leaf cells) in which case // the low bit is one. // // The following calculation converts (i,j) to the (si,ti) coordinates of // the cell center. (We need to multiply the coordinates by a factor of 2 // so that the center of leaf cells can be represented exactly.) var i = 0 var j = 0 var orientation: Int? = nil let face = toFaceIJOrientation(i: &i, j: &j, orientation: &orientation) // System.out.println("i= " + i.intValue() + " j = " + j.intValue()) let delta = isLeaf ? 1 : (((i ^ (Int(id) >> 2)) & 1) != 0) ? 2 : 0 let si = (i << 1) + delta - S2CellId.maxSize let ti = (j << 1) + delta - S2CellId.maxSize return S2CellId.faceSiTiToXYZ(face: face, si: si, ti: ti) } /// Return the S2LatLng corresponding to the center of the given cell. public var latLng: S2LatLng { return S2LatLng(point: rawPoint) } /// Return true if id() represents a valid cell. public var isValid: Bool { return face < S2CellId.numFaces && ((lowestOnBit & (0x1555555555555555)) != 0) } /// Which cube face this cell belongs to, in the range 0..5. public var face: Int { return Int(uid >> UInt64(S2CellId.posBits)) } /// The position of the cell center along the Hilbert curve over this face, in the range 0..(2**kPosBits-1). public var pos: Int64 { return Int64(bitPattern: uid & (UInt64(bitPattern: -1) >> 3)) } /// Return the subdivision level of the cell (range 0..MAX_LEVEL). public var level: Int { // Fast path for leaf cells. guard !isLeaf else { return S2CellId.maxLevel } var x = Int32(truncatingBitPattern: id) var level = -1 if x != 0 { level += 16 } else { x = Int32(truncatingBitPattern: id >> Int64(32)) } // We only need to look at even-numbered bits to determine the // level of a valid cell id. x &= -x // Get lowest bit. if ((x & 0x00005555) != 0) { level += 8 } if ((x & 0x00550055) != 0) { level += 4 } if ((x & 0x05050505) != 0) { level += 2 } if ((x & 0x11111111) != 0) { level += 1 } // assert (level >= 0 && level <= MAX_LEVEL); return level } /// Return true if this is a leaf cell (more efficient than checking whether level() == MAX_LEVEL). public var isLeaf: Bool { return (id & 1) != 0 } /// Return true if this is a top-level face cell (more efficient than checking whether level() == 0). public var isFace: Bool { return (id & (S2CellId.lowestOnBit(forLevel: 0) - 1)) == 0 } /** Return the child position (0..3) of this cell's ancestor at the given level, relative to its parent. The argument should be in the range 1..MAX_LEVEL. For example, child_position(1) returns the position of this cell's level-1 ancestor within its top-level face cell. */ public func childPosition(level: Int) -> Int { return Int(id >> Int64(2 * (S2CellId.maxLevel - level) + 1)) & 3 } // Methods that return the range of cell ids that are contained // within this cell (including itself). The range is *inclusive* // (i.e. test using >= and <=) and the return values of both // methods are valid leaf cell ids. // // These methods should not be used for iteration. If you want to // iterate through all the leaf cells, call child_begin(MAX_LEVEL) and // child_end(MAX_LEVEL) instead. // // It would in fact be error-prone to define a range_end() method, // because (range_max().id() + 1) is not always a valid cell id, and the // iterator would need to be tested using "<" rather that the usual "!=". public var rangeMin: S2CellId { return S2CellId(id: id - (lowestOnBit - 1)) } public var rangeMax: S2CellId { return S2CellId(id: id + (lowestOnBit - 1)) } /// Return true if the given cell is contained within this one. public func contains(other: S2CellId) -> Bool { // assert (isValid() && other.isValid()); return other >= rangeMin && other <= rangeMax } /// Return true if the given cell intersects this one. public func intersects(with other: S2CellId) -> Bool { // assert (isValid() && other.isValid()); return other.rangeMin <= rangeMax && other.rangeMax >= rangeMin } public var parent: S2CellId { // assert (isValid() && level() > 0); let newLsb = lowestOnBit << 2 return S2CellId(id: (id & -newLsb) | newLsb); } /** Return the cell at the previous level or at the given level (which must be less than or equal to the current level). */ public func parent(level: Int) -> S2CellId { // assert (isValid() && level >= 0 && level <= this.level()); let newLsb = S2CellId.lowestOnBit(forLevel: level) return S2CellId(id: (id & -newLsb) | newLsb) } public func childBegin() -> S2CellId { // assert (isValid() && level() < MAX_LEVEL); let oldLsb = UInt64(bitPattern: lowestOnBit) return S2CellId(uid: uid - oldLsb + (oldLsb >> 2)) } public func childBegin(level: Int) -> S2CellId { // assert (isValid() && level >= this.level() && level <= MAX_LEVEL); let lsb = UInt64(bitPattern: lowestOnBit) let lsbLevel = UInt64(bitPattern: S2CellId.lowestOnBit(forLevel: level)) return S2CellId(uid: uid - lsb + lsbLevel) } public func childEnd() -> S2CellId { // assert (isValid() && level() < MAX_LEVEL); let oldLsb = UInt64(bitPattern: lowestOnBit) return S2CellId(uid: uid + oldLsb + (oldLsb >> 2)) } public func childEnd(level: Int) -> S2CellId { // assert (isValid() && level >= this.level() && level <= MAX_LEVEL); let lsb = UInt64(bitPattern: lowestOnBit) let lsbLevel = UInt64(bitPattern: S2CellId.lowestOnBit(forLevel: level)) return S2CellId(uid: uid + lsb + lsbLevel) } // Iterator-style methods for traversing the immediate children of a cell or // all of the children at a given level (greater than or equal to the current // level). Note that the end value is exclusive, just like standard STL // iterators, and may not even be a valid cell id. You should iterate using // code like this: // // for(S2CellId c = id.childBegin(); !c.equals(id.childEnd()); c = c.next()) // ... // // The convention for advancing the iterator is "c = c.next()", so be sure // to use 'equals()' in the loop guard, or compare 64-bit cell id's, // rather than "c != id.childEnd()". /** Return the next cell at the same level along the Hilbert curve. Works correctly when advancing from one face to the next, but does *not* wrap around from the last face to the first or vice versa. */ public func next() -> S2CellId { return S2CellId(id: Int64.addWithOverflow(id, lowestOnBit << 1).0) } /** Return the previous cell at the same level along the Hilbert curve. Works correctly when advancing from one face to the next, but does *not* wrap around from the last face to the first or vice versa. */ public func prev() -> S2CellId { return S2CellId(id: Int64.subtractWithOverflow(id, lowestOnBit << 1).0) } /** Like next(), but wraps around from the last face to the first and vice versa. Should *not* be used for iteration in conjunction with child_begin(), child_end(), Begin(), or End(). */ public func nextWrap() -> S2CellId { let n = next() if S2CellId.unsignedLongLessThan(lhs: n.id, rhs: S2CellId.wrapOffset) { return n } return S2CellId(id: n.id - S2CellId.wrapOffset) } /** Like prev(), but wraps around from the last face to the first and vice versa. Should *not* be used for iteration in conjunction with child_begin(), child_end(), Begin(), or End(). */ public func prevWrap() -> S2CellId { let p = prev() if p.id < S2CellId.wrapOffset { return p } return S2CellId(id: p.id + S2CellId.wrapOffset) } public static func begin(level: Int) -> S2CellId { return S2CellId(face: 0, pos: 0, level: 0).childBegin(level: level) } public static func end(level: Int) -> S2CellId { return S2CellId(face: 5, pos: 0, level: 0).childEnd(level: level) } public struct NumberFormatException: Error { public let description: String public init(_ description: String = "") { self.description = description } } /** Decodes the cell id from a compact text string suitable for display or indexing. Cells at lower levels (i.e. larger cells) are encoded into fewer characters. The maximum token length is 16. */ public init(token: String) throws { let chars = Array(token.characters) guard chars.count > 0 else { throw NumberFormatException("Empty string in S2CellId.fromToken") } guard chars.count <= 16 && token != "X" else { self = .none return } var value: UInt64 = 0 for pos in 0 ..< 16 { var digit: Int = 0 if pos < chars.count { digit = Int(strtoul(String(chars[pos]), nil, 16)) if digit == -1 { throw NumberFormatException(token) } if S2CellId.overflowInParse(current: value, digit: digit) { throw NumberFormatException("Too large for unsigned long: " + token) } } value = (value * 16) + UInt64(digit) } self = S2CellId(id: Int64(bitPattern: value)) } /** Encodes the cell id to compact text strings suitable for display or indexing. Cells at lower levels (i.e. larger cells) are encoded into fewer characters. The maximum token length is 16. Simple implementation: convert the id to hex and strip trailing zeros. We could use base-32 or base-64, but assuming the cells used for indexing regions are at least 100 meters across (level 16 or less), the savings would be at most 3 bytes (9 bytes hex vs. 6 bytes base-64). */ var token: String { guard id != 0 else { return "X" } var hex = String(uid, radix: 16).lowercased() for _ in 0 ..< max(0, 16 - hex.characters.count) { hex.insert("0", at: hex.startIndex) } let chars = hex.characters var len = chars.count for char in chars.reversed() { guard char == "0" else { break } len -= 1 } return String(chars.prefix(len)) } /** Returns true if (current * radix) + digit is a number too large to be represented by an unsigned long. This is useful for detecting overflow while parsing a string representation of a number. Does not verify whether supplied radix is valid, passing an invalid radix will give undefined results or an ArrayIndexOutOfBoundsException. */ private static func overflowInParse(current: UInt64, digit: Int, radix: Int = 10) -> Bool { if current >= 0 { if current < maxValueDivs[radix] { return false } if current > maxValueDivs[radix] { return true } // current == maxValueDivs[radix] return digit > maxValueMods[radix] } // current < 0: high bit is set return true } // calculated as 0xffffffffffffffff / radix private static let maxValueDivs: [UInt64] = [0, 0, // 0 and 1 are invalid 9223372036854775807, 6148914691236517205, 4611686018427387903, // 2-4 3689348814741910323, 3074457345618258602, 2635249153387078802, // 5-7 2305843009213693951, 2049638230412172401, 1844674407370955161, // 8-10 1676976733973595601, 1537228672809129301, 1418980313362273201, // 11-13 1317624576693539401, 1229782938247303441, 1152921504606846975, // 14-16 1085102592571150095, 1024819115206086200, 970881267037344821, // 17-19 922337203685477580, 878416384462359600, 838488366986797800, // 20-22 802032351030850070, 768614336404564650, 737869762948382064, // 23-25 709490156681136600, 683212743470724133, 658812288346769700, // 26-28 636094623231363848, 614891469123651720, 595056260442243600, // 29-31 576460752303423487, 558992244657865200, 542551296285575047, // 32-34 527049830677415760, 512409557603043100 ] // 35-36 // calculated as 0xffffffffffffffff % radix private static let maxValueMods: [Int] = [0, 0, // 0 and 1 are invalid 1, 0, 3, 0, 3, 1, 7, 6, 5, 4, 3, 2, 1, 0, 15, 0, 15, 16, 15, 15, // 2-21 15, 5, 15, 15, 15, 24, 15, 23, 15, 15, 31, 15, 17, 15, 15 ] // 22-36 /** Return the four cells that are adjacent across the cell's four edges. Neighbors are returned in the order defined by S2Cell::GetEdge. All neighbors are guaranteed to be distinct. */ public func getEdgeNeighbors() -> [S2CellId] { let level = self.level let size = 1 << (S2CellId.maxLevel - level) var i = 0, j = 0, orientation: Int? = nil let face = toFaceIJOrientation(i: &i, j: &j, orientation: &orientation) // Edges 0, 1, 2, 3 are in the S, E, N, W directions. return [ S2CellId(face: face, i: i, j: j - size, sameFace: j - size >= 0).parent(level: level), S2CellId(face: face, i: i + size, j: j, sameFace: i + size < S2CellId.maxSize).parent(level: level), S2CellId(face: face, i: i, j: j + size, sameFace: j + size < S2CellId.maxSize).parent(level: level), S2CellId(face: face, i: i - size, j: j, sameFace: i - size >= 0).parent(level: level) ] } /** Return the neighbors of closest vertex to this cell at the given level, by appending them to "output". Normally there are four neighbors, but the closest vertex may only have three neighbors if it is one of the 8 cube vertices. Requires: level < this.evel(), so that we can determine which vertex is closest (in particular, level == MAX_LEVEL is not allowed). */ public func getVertexNeighbors(level: Int) -> [S2CellId] { // "level" must be strictly less than this cell's level so that we can // determine which vertex this cell is closest to. // assert (level < this.level()); var i = 0, j = 0, orientation: Int? = nil let face = toFaceIJOrientation(i: &i, j: &j, orientation: &orientation) // Determine the i- and j-offsets to the closest neighboring cell in each // direction. This involves looking at the next bit of "i" and "j" to // determine which quadrant of this->parent(level) this cell lies in. let halfsize = 1 << (S2CellId.maxLevel - (level + 1)) let size = halfsize << 1 var isame: Bool, jsame: Bool var ioffset: Int, joffset: Int if ((i & halfsize) != 0) { ioffset = size isame = (i + size) < S2CellId.maxSize } else { ioffset = -size isame = (i - size) >= 0 } if ((j & halfsize) != 0) { joffset = size jsame = (j + size) < S2CellId.maxSize } else { joffset = -size jsame = (j - size) >= 0 } var output: [S2CellId] = [] output.append(parent(level: level)) output.append(S2CellId(face: face, i: i + ioffset, j: j, sameFace: isame).parent(level: level)) output.append(S2CellId(face: face, i: i, j: j + joffset, sameFace: jsame).parent(level: level)) // If i- and j- edge neighbors are *both* on a different face, then this // vertex only has three neighbors (it is one of the 8 cube vertices). if isame || jsame { output.append(S2CellId(face: face, i: i + ioffset, j: j + joffset, sameFace: isame && jsame).parent(level: level)) } return output } /** Append all neighbors of this cell at the given level to "output". Two cells X and Y are neighbors if their boundaries intersect but their interiors do not. In particular, two cells that intersect at a single point are neighbors. Requires: nbr_level >= this->level(). Note that for cells adjacent to a face vertex, the same neighbor may be appended more than once. */ public func getAllNeighbors(level nbrLevel: Int) -> [S2CellId] { var i = 0, j = 0, orientation: Int? = nil let face = toFaceIJOrientation(i: &i, j: &j, orientation: &orientation) // Find the coordinates of the lower left-hand leaf cell. We need to // normalize (i,j) to a known position within the cell because nbr_level // may be larger than this cell's level. let size = 1 << (S2CellId.maxLevel - level) i = i & -size j = j & -size let nbrSize = 1 << (S2CellId.maxLevel - nbrLevel) // assert (nbrSize <= size); var output: [S2CellId] = [] // We compute the N-S, E-W, and diagonal neighbors in one pass. // The loop test is at the end of the loop to avoid 32-bit overflow. var k = -nbrSize while true { let sameFace: Bool if (k < 0) { sameFace = j + k >= 0 } else if (k >= size) { sameFace = j + k < S2CellId.maxLevel } else { sameFace = true // North and South neighbors. output.append(S2CellId(face: face, i: i + k, j: j - nbrSize, sameFace: j - size >= 0).parent(level: nbrLevel)) output.append(S2CellId(face: face, i: i + k, j: j + size, sameFace: j + size < S2CellId.maxLevel).parent(level: nbrLevel)) } // East, West, and Diagonal neighbors. output.append(S2CellId(face: face, i: i - nbrSize, j: j + k, sameFace: sameFace && i - size >= 0).parent(level: nbrLevel)) output.append(S2CellId(face: face, i: i + size, j: j + k, sameFace: sameFace && i + size < S2CellId.maxLevel).parent(level: nbrLevel)) if k >= size { break } k += nbrSize } return output } // /////////////////////////////////////////////////////////////////// // Low-level methods. /// Return a leaf cell given its cube face (range 0..5) and i- and j-coordinates (see s2.h). public init(face: Int, i: Int, j: Int, sameFace: Bool = true) { if sameFace { // Optimization notes: // - Non-overlapping bit fields can be combined with either "+" or "|". // Generally "+" seems to produce better code, but not always. // gcc doesn't have very good code generation for 64-bit operations. // We optimize this by computing the result as two 32-bit integers // and combining them at the end. Declaring the result as an array // rather than local variables helps the compiler to do a better job // of register allocation as well. Note that the two 32-bits halves // get shifted one bit to the left when they are combined. var n: [Int64] = [0, Int64(face << (S2CellId.posBits - 33))] // Alternating faces have opposite Hilbert curve orientations; this // is necessary in order for all faces to have a right-handed // coordinate system. var bits = (face & S2CellId.swapMask) // Each iteration maps 4 bits of "i" and "j" into 8 bits of the Hilbert // curve position. The lookup table transforms a 10-bit key of the form // "iiiijjjjoo" to a 10-bit value of the form "ppppppppoo", where the // letters [ijpo] denote bits of "i", "j", Hilbert curve position, and // Hilbert curve orientation respectively. for k in (0 ..< 8).reversed() { bits = S2CellId.getBits(n: &n, i: i, j: j, k: k, bits: bits) } self.init(id: (((n[1] << 32) + n[0]) << 1) + 1) } else { // Given (i, j) coordinates that may be out of bounds, normalize them by // returning the corresponding neighbor cell on an adjacent face. // Convert i and j to the coordinates of a leaf cell just beyond the // boundary of this face. This prevents 32-bit overflow in the case // of finding the neighbors of a face cell, and also means that we // don't need to worry about the distinction between (s,t) and (u,v). var i = i, j = j, face = face i = max(-1, min(S2CellId.maxSize, i)) j = max(-1, min(S2CellId.maxSize, j)) // Find the (s,t) coordinates corresponding to (i,j). At least one // of these coordinates will be just outside the range [0, 1]. let kScale = 1.0 / Double(S2CellId.maxSize) let s = kScale * Double((i << 1) + 1 - S2CellId.maxSize) let t = kScale * Double((j << 1) + 1 - S2CellId.maxSize) // Find the leaf cell coordinates on the adjacent face, and convert // them to a cell id at the appropriate level. let p = S2Projections.faceUvToXyz(face: face, u: s, v: t) face = S2Projections.xyzToFace(point: p) let st = S2Projections.validFaceXyzToUv(face: face, point: p) self.init(face: face, i: S2CellId.stToIJ(s: st.x), j: S2CellId.stToIJ(s: st.y)) } } private static func getBits(n: inout [Int64], i: Int, j: Int, k: Int, bits: Int) -> Int { let mask = (1 << lookupBits) - 1 var bits = bits bits += (((i >> (k * lookupBits)) & mask) << (lookupBits + 2)) bits += (((j >> (k * lookupBits)) & mask) << 2) bits = lookupPos[bits] n[k >> 2] |= ((Int64(bits) >> 2) << Int64((k & 3) * 2 * lookupBits)) bits &= (swapMask | invertMask) return bits } /** * Return the (face, i, j) coordinates for the leaf cell corresponding to this * cell id. Since cells are represented by the Hilbert curve position at the * center of the cell, the returned (i,j) for non-leaf cells will be a leaf * cell adjacent to the cell center. If "orientation" is non-NULL, also return * the Hilbert curve orientation for the current cell. */ public func toFaceIJOrientation(i: inout Int, j: inout Int, orientation: inout Int?) -> Int { // System.out.println("Entering toFaceIjorientation"); let face = self.face var bits = face & S2CellId.swapMask // System.out.println("face = " + face + " bits = " + bits); // Each iteration maps 8 bits of the Hilbert curve position into // 4 bits of "i" and "j". The lookup table transforms a key of the // form "ppppppppoo" to a value of the form "iiiijjjjoo", where the // letters [ijpo] represents bits of "i", "j", the Hilbert curve // position, and the Hilbert curve orientation respectively. // // On the first iteration we need to be careful to clear out the bits // representing the cube face. for k in (0 ..< 8).reversed() { bits = getBits1(i: &i, j: &j, k: k, bits: bits) // System.out.println("pi = " + pi + " pj= " + pj + " bits = " + bits); } if orientation != nil { // The position of a non-leaf cell at level "n" consists of a prefix of // 2*n bits that identifies the cell, followed by a suffix of // 2*(MAX_LEVEL-n)+1 bits of the form 10*. If n==MAX_LEVEL, the suffix is // just "1" and has no effect. Otherwise, it consists of "10", followed // by (MAX_LEVEL-n-1) repetitions of "00", followed by "0". The "10" has // no effect, while each occurrence of "00" has the effect of reversing // the kSwapMask bit. // assert (S2.POS_TO_ORIENTATION[2] == 0); // assert (S2.POS_TO_ORIENTATION[0] == S2.SWAP_MASK); if (lowestOnBit & 0x1111111111111110) != 0 { bits ^= S2.swapMask } orientation = bits } return face } private func getBits1(i: inout Int, j: inout Int, k: Int, bits: Int) -> Int { let nbits = (k == 7) ? (S2CellId.maxLevel - 7 * S2CellId.lookupBits) : S2CellId.lookupBits var bits = bits bits += (Int((id >> Int64(k * 2 * S2CellId.lookupBits + 1))) & ((1 << (2 * nbits)) - 1)) << 2 bits = S2CellId.lookupIj[bits] i += ((bits >> (S2CellId.lookupBits + 2)) << (k * S2CellId.lookupBits)) j += ((((bits >> 2) & ((1 << S2CellId.lookupBits) - 1))) << (k * S2CellId.lookupBits)) bits &= (S2CellId.swapMask | S2CellId.invertMask) return bits } /// Return the lowest-numbered bit that is on for cells at the given level. public var lowestOnBit: Int64 { return id & -id } public var hashValue: Int { // UInt64 return Int(truncatingBitPattern: (uid >> 32) + uid) } /** Return the lowest-numbered bit that is on for this cell id, which is equal to (uint64(1) << (2 * (MAX_LEVEL - level))). So for example, a.lsb() <= b.lsb() if and only if a.level() >= b.level(), but the first test is more efficient. */ public static func lowestOnBit(forLevel level: Int) -> Int64 { return 1 << Int64(2 * (maxLevel - level)) } /// Return the i- or j-index of the leaf cell containing the given s- or t-value. private static func stToIJ(s: Double) -> Int { // Converting from floating-point to integers via static_cast is very slow // on Intel processors because it requires changing the rounding mode. // Rounding to the nearest integer using FastIntRound() is much faster. let m = Double(maxSize / 2) // scaling multiplier let x = round(m * s + (m - 0.5)) return Int(max(0, min(2 * m - 1, x))) } /// Convert (face, si, ti) coordinates (see s2.h) to a direction vector (not necessarily unit length). private static func faceSiTiToXYZ(face: Int, si: Int, ti: Int) -> S2Point { let kScale = 1.0 / Double(maxSize) let u = S2Projections.stToUV(s: kScale * Double(si)) let v = S2Projections.stToUV(s: kScale * Double(ti)) return S2Projections.faceUvToXyz(face: face, u: u, v: v) } /// Returns true if x1 < x2, when both values are treated as unsigned. public static func unsignedLongLessThan(lhs: Int64, rhs: Int64) -> Bool { // return (lhs + .min) < (rhs + .min) return UInt64(bitPattern: lhs) < UInt64(bitPattern: rhs) } /// Returns true if x1 > x2, when both values are treated as unsigned. public static func unsignedLongGreaterThan(lhs: Int64, rhs: Int64) -> Bool { // return (lhs + .min) > (rhs + .min) return UInt64(bitPattern: lhs) > UInt64(bitPattern: rhs) } private static func initLookupCell(level: Int, i: Int, j: Int, origOrientation: Int, pos: Int, orientation: Int) { if level == lookupBits { let ij = (i << lookupBits) + j lookup.pos[(ij << 2) + origOrientation] = (pos << 2) + orientation lookup.ij[(pos << 2) + origOrientation] = (ij << 2) + orientation } else { var level = level, i = i, j = j, pos = pos level += 1 i <<= 1 j <<= 1 pos <<= 2 // Initialize each sub-cell recursively. for subPos in 0 ..< 4 { let ij = S2.posToIJ(orientation: orientation, position: subPos) let orientationMask = S2.posToOrientation(position: subPos) initLookupCell(level: level, i: i + (ij >> 1), j: j + (ij & 1), origOrientation: origOrientation, pos: pos + subPos, orientation: orientation ^ orientationMask) } } } } public func ==(lhs: S2CellId, rhs: S2CellId) -> Bool { return lhs.id == rhs.id } public func <(lhs: S2CellId, rhs: S2CellId) -> Bool { return S2CellId.unsignedLongLessThan(lhs: lhs.id, rhs: rhs.id) }
mit
cff28e5add8cb7ff4a94f1a0b680a319
37.229586
164
0.671651
3.176714
false
false
false
false