repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
graham-perks-snap/JSONViewControllers
refs/heads/master
Pod/Classes/TableViewHelp.swift
mit
1
// // TableViewHelp.swift // SnapKitchen // // Created by Graham Perks on 4/21/16. // Copyright © 2016 Snap Kitchen. All rights reserved. // import UIKit public protocol TableCellConfigurer { func configureIn(_ definition: TableRow, indexPath: IndexPath) } public extension TableCellConfigurer { func configureIn(_ definition: TableRow, indexPath: IndexPath) { definition.configureIn(self, indexPath: indexPath) } } public enum TableRowSource { case nib(String) case `class`(String) case prototype } //MARK: Table Row // Implement TableRow, add rows to sections to build the table public protocol TableRow: class { // Need either a nib or a class to register with var source: TableRowSource {get} var reuseIdentifier: String { get } var height: CGFloat { get } var action: String? { get } func configureIn(_ cell: TableCellConfigurer, indexPath: IndexPath) } public protocol TableSection { var rows: [TableRow] { get set } } // A section with header or footer public protocol TableSectionWithSupplementaryViews: TableSection { var headerHeight: CGFloat { get } func headerViewForTableView(_ tableView: UITableView) -> UIView? } // A regular section with no headers or footers open class DefaultTableSection: TableSection { open var rows = [TableRow]() public init() {} } // MARK: - Table view data source open class TableViewDataSourceHelper: NSObject, UITableViewDataSource { open var sections = [TableSection]() // Iterate through all the rows ensuring each cell's NIB and class is registered with the table open func registerConfigurers(_ tableView: UITableView) { for section in sections { for row in section.rows { switch row.source { case .nib(let nibName): let nib = UINib(nibName: nibName, bundle: nil) tableView.register(nib, forCellReuseIdentifier: row.reuseIdentifier) case .class(let className): let clazz:AnyClass = className.classFromClassName() tableView.register(clazz, forCellReuseIdentifier: row.reuseIdentifier) case .prototype: // Prototype cells are registered by storyboard loader. break } } } } /// Register nib with name identical to its reuse ID static public func registerNib(_ tableView: UITableView, name: String) { let nib = UINib(nibName: name, bundle: nil) tableView.register(nib, forCellReuseIdentifier: name) } @objc open func numberOfSections(in tableView: UITableView) -> Int { return sections.count } @objc open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } @objc open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = sections[indexPath.section] let row = section.rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.reuseIdentifier, for: indexPath) if let configurer = cell as? TableCellConfigurer { configurer.configureIn(row, indexPath: indexPath) } return cell } } // MARK: - Table view delegate open class TableViewDelegateHelper: NSObject, UITableViewDelegate { public init(actionTarget: NSObjectProtocol) { self.target = actionTarget super.init() } public weak var target: NSObjectProtocol? @objc open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let dataSource = tableView.dataSource as! TableViewDataSourceHelper let section = dataSource.sections[indexPath.section] let row = section.rows[indexPath.row] if let action = row.action, let target = target { if action.hasSuffix("::") { target.perform(Selector(action), with: row, with: indexPath) } else { target.perform(Selector(action), with: row) } } } } open class TableViewDelegateVariableRowHeightHelper: TableViewDelegateHelper { public override init(actionTarget: NSObjectProtocol) { super.init(actionTarget: actionTarget) } @objc open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let dataSource = tableView.dataSource as! TableViewDataSourceHelper let section = dataSource.sections[indexPath.section] let row = section.rows[indexPath.row] return row.height } } // Table with section header or footers open class TableViewDelegateWithSupplementaryViewsHelper: TableViewDelegateVariableRowHeightHelper { public override init(actionTarget: NSObjectProtocol) { super.init(actionTarget: actionTarget) } @objc open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let dataSource = tableView.dataSource as! TableViewDataSourceHelper let section = dataSource.sections[section] as! TableSectionWithSupplementaryViews return section.headerViewForTableView(tableView) } @objc open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let dataSource = tableView.dataSource as! TableViewDataSourceHelper let section = dataSource.sections[section] as! TableSectionWithSupplementaryViews return section.headerHeight } }
22963ea1bfcb9ede06dfde446f2bacc5
30.668539
111
0.679439
false
true
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/SchemeHandler/SchemeHandler+APIHandler.swift
mit
3
import Foundation extension SchemeHandler { final class APIHandler: BaseSubHandler, RemoteSubHandler { let session: Session override class var basePath: String? { return "APIProxy" } required init(session: Session) { self.session = session } func urlForPathComponents(_ pathComponents: [String], requestURL: URL) -> URL? { guard pathComponents.count == 5 else { assertionFailure("Expected 5 components when using APIProxy base path") return nil } guard var apiProxyURLComponents = URLComponents(url: requestURL, resolvingAgainstBaseURL: false) else { return nil } // APIURL is APIProxyURL with components[3] as the host, components[4..5] as the path. apiProxyURLComponents.path = NSString.path(withComponents: ["/", pathComponents[3], pathComponents[4]]) apiProxyURLComponents.host = pathComponents[2] apiProxyURLComponents.scheme = "https" return apiProxyURLComponents.url } func dataTaskForURL(_ url: URL, callback: Session.Callback) -> URLSessionTask { var request = URLRequest(url: url) request.setValue(WikipediaAppUtils.versionedUserAgent(), forHTTPHeaderField: "User-Agent") let apiRequestTask = session.dataTask(with: request, callback: callback) apiRequestTask.priority = URLSessionTask.lowPriority return apiRequestTask } } }
44fd52e4edfdf221f8e70cb158c908e5
36.886364
115
0.590282
false
false
false
false
inkyfox/KRWordWrapLabel
refs/heads/master
Sources/KRWordWrapLabel.swift
mit
1
// // KRWordWrapLabel.swift // KRWordWrapLabel // // Created by Yoo YongHa on 2016. 3. 5.. // Copyright © 2016년 Gen X Hippies Company. All rights reserved. // import UIKit @IBDesignable open class KRWordWrapLabel: UILabel { @IBInspectable open var ellipsis: String = "..." { didSet { self.updateWords() } } override open var text: String? { didSet { self.updateWords() } } override open var font: UIFont! { didSet { self.updateWords() } } override open var textColor: UIColor! { didSet { self.updateWords() } } @IBInspectable open var lineSpace: CGFloat = 0 { didSet { _ = self.updateWordLayout() } } override open var bounds: CGRect { didSet { _ = self.updateWordLayout() } } override open var numberOfLines: Int { didSet { _ = self.updateWordLayout() } } override open var textAlignment: NSTextAlignment { didSet { _ = self.updateWordLayout() } } fileprivate var intrinsicSize: CGSize = CGSize.zero override open func awakeFromNib() { super.awakeFromNib() self.updateWords() } override open var intrinsicContentSize : CGSize { if self.lineBreakMode == .byWordWrapping && self.doWordWrap { return intrinsicSize } else { return super.intrinsicContentSize } } // MARK: - Codes for Word Wrap fileprivate class Word { let text: NSAttributedString let size: CGSize let precedingSpace: CGFloat var origin: CGPoint = CGPoint.zero var visible: Bool = true init(text: NSAttributedString, size: CGSize, precedingSpaceWidth: CGFloat) { self.text = text self.size = size self.precedingSpace = precedingSpaceWidth } } fileprivate var ellipsisWord: Word! fileprivate var paragraphs: [[Word]]? fileprivate var doWordWrap = true override open func draw(_ rect: CGRect) { if self.lineBreakMode == .byWordWrapping && self.doWordWrap { guard let paragraphs = self.paragraphs else { return } if self.ellipsisWord.visible { self.ellipsisWord.text.draw(at: self.ellipsisWord.origin) } for words in paragraphs { for word in words { if !word.visible { return } word.text.draw(at: word.origin) } } } else { super.draw(rect) } } fileprivate func updateWords() { let maxFontSize = self.font.pointSize let minFontSize = self.adjustsFontSizeToFitWidth || self.minimumScaleFactor > 0 ? maxFontSize * self.minimumScaleFactor : maxFontSize for size in stride(from: maxFontSize, through: minFontSize, by: -0.5) { if updateWords(size) { return } } } fileprivate func updateWords(_ fontSize: CGFloat) -> Bool { guard let text = self.text else { return true } let font = self.font.withSize(fontSize) var w = 0 self.paragraphs = text .split(omittingEmptySubsequences: false) { (c: Character) -> Bool in return c == "\n" || c == "\r\n" } .map(String.init) .map { (paragraph: String) -> [KRWordWrapLabel.Word] in return paragraph.split(separator: " ", omittingEmptySubsequences: false) .map(String.init) .map { s -> NSAttributedString? in return s == "" ? nil : NSAttributedString(string: s, attributes: [.font : font, .foregroundColor: self.textColor]) } .compactMap { t -> Word? in if let text = t { let size = text.size() let spaceWidth = NSAttributedString(string: String(repeating: " ", count: w), attributes: [.font : font]).size().width w = 1 return Word( text: text, size: CGSize(width: ceil(size.width), height: ceil(size.height)), precedingSpaceWidth: ceil(spaceWidth)) } else { w += 1 return nil } } } .compactMap { words -> [KRWordWrapLabel.Word] in if words.count > 0 { return words } else { let text = NSAttributedString(string: " ", attributes: [.font : font]) let size = text.size() return [Word( text: text, size: CGSize(width: ceil(size.width), height: ceil(size.height)), precedingSpaceWidth: 0)] } } do { let text = NSAttributedString(string: self.ellipsis, attributes: [.font : font, .foregroundColor: self.textColor]) let size = text.size() self.ellipsisWord = Word( text: text, size: CGSize(width: ceil(size.width), height: ceil(size.height)), precedingSpaceWidth: 0) } return self.updateWordLayout() } fileprivate func updateWordLayout() -> Bool { guard let paragraphs = self.paragraphs else { return true } self.doWordWrap = true let width = self.bounds.width var totalSize:CGSize = CGSize.zero var rowSize: CGSize = CGSize.zero var rowCount = 1 var colCount = 0 var colWords: [Word] = [] func newRow() { var x = self.textAlignment == .center ? (width - rowSize.width) / 2 : self.textAlignment == .right ? width - rowSize.width : 0 let y = totalSize.height + rowSize.height for (index, word) in colWords.enumerated() { if index > 0 { x += word.precedingSpace } word.origin.x = x x += word.size.width word.origin.y = y - word.size.height } totalSize.width = max(totalSize.width, rowSize.width); totalSize.height += rowSize.height colWords.removeAll() rowSize = CGSize.zero colCount = 0 rowCount += 1 } let maxLines = self.numberOfLines > 0 ? self.numberOfLines : Int.max var truncate = false for words in paragraphs { words[0].visible = false } loop: for (index, words) in paragraphs.enumerated() { for word in words { var x = rowSize.width if word.size.width > width { self.doWordWrap = false invalidateIntrinsicContentSize() return true } else if colCount > 0 && x + word.precedingSpace + word.size.width > width { // new Row if rowCount == maxLines { truncate = true word.visible = false break loop } newRow() x = 0 } if colCount == 0 { totalSize.height += lineSpace } word.visible = true colWords.append(word) rowSize.width += (colCount == 0 ? 0 : word.precedingSpace) + word.size.width rowSize.height = max(rowSize.height, word.size.height) colCount += 1 } if rowCount == maxLines && index < paragraphs.count - 1 { truncate = true break loop } newRow() } self.ellipsisWord.visible = false if colCount > 0 { if truncate { if rowSize.width + self.ellipsisWord.size.width <= width { colWords.append(self.ellipsisWord) self.ellipsisWord.visible = true rowSize.width += self.ellipsisWord.size.width } else if colWords.count > 1 { let old = colWords[colWords.count - 1] old.visible = false rowSize.width -= old.size.width colWords[colWords.count - 1] = self.ellipsisWord rowSize.width += self.ellipsisWord.size.width self.ellipsisWord.visible = true } } newRow() } let adjustY = max(0, (bounds.height - totalSize.height) / 2) for words in paragraphs { for word in words { word.origin.y += adjustY } } if self.ellipsisWord.visible { self.ellipsisWord.origin.y += adjustY } if self.intrinsicSize != totalSize { self.intrinsicSize = totalSize invalidateIntrinsicContentSize() } return !truncate } }
7775208e141aea4b4e03b03493f63fe7
34.810409
146
0.483961
false
false
false
false
bojan/Device
refs/heads/develop
Sources/Model/Family.swift
mit
2
// // Family // Thingy // // Created by Bojan Dimovski on 21.11.16. // Copyright © 2017 Bojan Dimovski. All rights reserved. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // Version 2, December 2004 // // Copyright (C) 2004 Sam Hocevar <[email protected]> // // Everyone is permitted to copy and distribute verbatim or modified // copies of this license document, and changing it is allowed as long // as the name is changed. // // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION // // 0. You just DO WHAT THE FUCK YOU WANT TO. // // import Foundation /// A type that describes the product family. public enum Family: String { /// - phone: iPhone product family. case phone = "iPhone" /// - pod: iPod touch product family. case pod = "iPod" /// - pad: iPad product family. case pad = "iPad" /// - tv: Apple TV product family. case tv = "AppleTV" /// - watch: Apple Watch product family. case watch = "Watch" } // MARK: - Marketing protocol extension Family: MarketingProtocol { /// The marketing name of the product family, e.g. "iPhone", "Apple TV". public var marketingName: String { switch self { case .phone: return "iPhone" case .pod: return "iPod" case .pad: return "iPad" case .tv: return "Apple TV" case .watch: return "Watch" } } }
f9fd638c030161051d1447eb0a88bc73
22.3
73
0.654506
false
false
false
false
cplaverty/KeitaiWaniKani
refs/heads/master
AlliCrab/AppDelegate.swift
mit
1
// // AppDelegate.swift // AlliCrab // // Copyright © 2017 Chris Laverty. All rights reserved. // import AVFoundation import os import UIKit import UserNotifications import WaniKaniKit import WebKit struct ApplicationURL { static let launchLessons = URL(string: "kwk://launch/lessons")! static let launchReviews = URL(string: "kwk://launch/reviews")! } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private var rootNavigationController: UINavigationController! { return window?.rootViewController as? UINavigationController } override init() { databaseConnectionFactory = AppGroupDatabaseConnectionFactory() databaseManager = DatabaseManager(factory: databaseConnectionFactory) notificationManager = NotificationManager() super.init() notificationManager.delegate = self } // MARK: - Properties private let databaseConnectionFactory: DatabaseConnectionFactory private let databaseManager: DatabaseManager let notificationManager: NotificationManager private var shouldSendNotifications = true var resourceRepository: ResourceRepository? { didSet { guard let resourceRepository = resourceRepository else { UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalNever) notificationManager.unregisterForNotifications() return } if shouldSendNotifications { notificationManager.registerForNotifications(resourceRepository: resourceRepository) } UIApplication.shared.setMinimumBackgroundFetchInterval(5 * .oneMinute) } } lazy var webKitProcessPool = WKProcessPool() // MARK: - UIApplicationDelegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().tintColor = .globalTintColor UINavigationBar.appearance().barTintColor = .globalBarTintColor UIToolbar.appearance().tintColor = .globalTintColor UIToolbar.appearance().barTintColor = .globalBarTintColor #if targetEnvironment(simulator) // Check if we've been launched by Snapshot if UserDefaults.standard.bool(forKey: "FASTLANE_SNAPSHOT") { os_log("Detected snapshot run: setting login cookie and disabling notification prompts", type: .info) if let loginCookieValue = UserDefaults.standard.string(forKey: "LOGIN_COOKIE") { let loginCookie = HTTPCookie(properties: [ .domain: "www.wanikani.com", .name: "remember_user_token", .path: "/", .secure: "TRUE", .value: loginCookieValue ])! if #available(iOS 11.0, *) { WKWebsiteDataStore.default().httpCookieStore.setCookie(loginCookie) { os_log("Login cookie set", type: .info) } } else { HTTPCookieStorage.shared.setCookie(loginCookie) os_log("Login cookie set", type: .info) } } else { os_log("Not setting login cookie (LOGIN_COOKIE not found)", type: .info) } shouldSendNotifications = false } #endif if ApplicationSettings.purgeCaches { os_log("Clearing caches directory", type: .info) ApplicationSettings.purgeCaches = false let fileManager = FileManager.default let cachesDir = try! fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) do { try fileManager.contentsOfDirectory(at: cachesDir, includingPropertiesForKeys: nil, options: []) .forEach(fileManager.removeItem(at:)) } catch { os_log("Failed to purge caches directory: %@", type: .error, error as NSError) } } if ApplicationSettings.purgeDatabase { os_log("Purging database", type: .info) try! databaseConnectionFactory.destroyDatabase() ApplicationSettings.purgeDatabase = false } if !databaseManager.open() { os_log("Failed to open database!", type: .fault) fatalError("Failed to open database!") } let session = AVAudioSession.sharedInstance() do { try session.setCategory(.ambient, mode: .default, options: [.interruptSpokenAudioAndMixWithOthers]) os_log("Audio session category assigned", type: .debug) } catch { os_log("Failed to set audio session category", type: .error, error as NSError) } if let apiKey = ApplicationSettings.apiKey, !apiKey.isEmpty { resourceRepository = makeResourceRepository(forAPIKey: apiKey) initialiseDashboardViewController(rootNavigationController.viewControllers[0] as! DashboardTableViewController) UIApplication.shared.shortcutItems = makeShortcutItems() return true } else { notificationManager.clearBadgeNumberAndRemoveAllNotifications() presentLoginViewController(animated: false) return false } } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { os_log("Handling url %@", type: .info, url as NSURL) guard let rootViewController = rootNavigationController else { return false } switch url { case ApplicationURL.launchLessons: presentLessonViewController(on: rootViewController.topPresentedViewController, animated: true) return true case ApplicationURL.launchReviews: presentReviewViewController(on: rootViewController.topPresentedViewController, animated: true) return true default: return false } } // MARK: - Background Fetch func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { os_log("In background fetch handler", type: .debug) guard let resourceRepository = self.resourceRepository else { os_log("Background fetch result = .noData (No resource repository)", type: .debug) completionHandler(.noData) return } os_log("Updating app data from background fetch handler", type: .info) resourceRepository.updateAppData(minimumFetchInterval: 15 * .oneMinute) { result in switch result { case .success: os_log("Background fetch result = .newData", type: .debug) completionHandler(.newData) case .noData: self.notificationManager.updateDeliveredNotifications(resourceRepository: resourceRepository) { didScheduleNotification in if didScheduleNotification { os_log("Background fetch result = .newData", type: .debug) completionHandler(.newData) } else { os_log("Background fetch result = .noData", type: .debug) completionHandler(.noData) } } case let .error(error): os_log("Background fetch result = .failed (%@)", type: .error, error as NSError) completionHandler(.failed) } } } // MARK: - Application Shortcuts enum ShortcutItemType: String { case lesson case review } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { os_log("Handling shortcut item of type %@", type: .info, shortcutItem.type) guard let shortcutItemType = ShortcutItemType(rawValue: shortcutItem.type), let rootViewController = rootNavigationController else { completionHandler(false) return } switch shortcutItemType { case .lesson: presentLessonViewController(on: rootViewController.topPresentedViewController, animated: true) { completionHandler(true) } case .review: presentReviewViewController(on: rootViewController.topPresentedViewController, animated: true) { completionHandler(true) } } } func makeShortcutItems() -> [UIApplicationShortcutItem] { return [ UIApplicationShortcutItem(type: ShortcutItemType.lesson.rawValue, localizedTitle: "Lessons"), UIApplicationShortcutItem(type: ShortcutItemType.review.rawValue, localizedTitle: "Reviews") ] } // MARK: - Login func presentLoginViewController(animated: Bool) { let storyboard = Storyboard.login.instance let vc = storyboard.instantiateViewController(withIdentifier: "Login") as! LoginRootViewController rootNavigationController.setViewControllers([vc], animated: animated) } func presentDashboardViewController(animated: Bool) { let storyboard = Storyboard.main.instance let vc = storyboard.instantiateViewController(withIdentifier: "Main") as! DashboardTableViewController initialiseDashboardViewController(vc) rootNavigationController.setViewControllers([vc], animated: animated) } func presentLessonViewController(on viewController: UIViewController, animated: Bool, completion: (() -> Void)? = nil) { let vc = WaniKaniReviewPageWebViewController.wrapped(url: WaniKaniURL.lessonSession) viewController.present(vc, animated: true, completion: completion) } func presentReviewViewController(on viewController: UIViewController, animated: Bool, completion: (() -> Void)? = nil) { let vc = WaniKaniReviewPageWebViewController.wrapped(url: WaniKaniURL.reviewSession) viewController.present(vc, animated: true, completion: completion) } private func initialiseDashboardViewController(_ viewController: DashboardTableViewController) { viewController.resourceRepository = resourceRepository } func makeResourceRepository(forAPIKey apiKey: String) -> ResourceRepository { return ResourceRepository(databaseManager: databaseManager, apiKey: apiKey, networkActivityDelegate: NetworkIndicatorController.shared) } func logOut() { // Reset app settings ApplicationSettings.resetToDefaults() // Clear web cookies let cookieStorage = HTTPCookieStorage.shared cookieStorage.removeCookies(since: Date(timeIntervalSince1970: 0)) WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date(timeIntervalSince1970: 0)) { self.webKitProcessPool = WKProcessPool() } // Notifications notificationManager.clearBadgeNumberAndRemoveAllNotifications() // Purge database resourceRepository = nil databaseManager.close() try! databaseConnectionFactory.destroyDatabase() if !databaseManager.open() { os_log("Failed to open database!", type: .fault) fatalError("Failed to open database!") } presentLoginViewController(animated: true) } } // MARK: - UNUserNotificationCenterDelegate extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { defer { completionHandler() } os_log("Received notification with identifier %@, action identifier %@", type: .debug, response.notification.request.identifier, response.actionIdentifier) guard let rootViewController = rootNavigationController else { return } let identifier = response.notification.request.identifier switch response.actionIdentifier { case UNNotificationDefaultActionIdentifier: os_log("Showing review page in response to notification interaction", type: .info) presentReviewViewController(on: rootViewController.topPresentedViewController, animated: true) case UNNotificationDismissActionIdentifier: os_log("Removing any pending review count notifications due to notification dismissal", type: .info) notificationManager.removePendingNotificationRequests(withIdentifier: identifier) default: break } } }
6409ac9769d316a294c7716dfcb9e837
40.297214
177
0.639853
false
false
false
false
WaterReporter/WaterReporter-iOS
refs/heads/master
WaterReporter/WaterReporter/OrganizationTableViewController.swift
agpl-3.0
1
// // OrganizationTableViewController.swift // // Created by Viable Industries on 11/6/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import Foundation import Kingfisher import SwiftyJSON import UIKit class OrganizationTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate { // // @IBOUTLETS // @IBOutlet weak var imageViewGroupProfileImage: UIImageView! @IBOutlet weak var labelGroupProfileName: UILabel! @IBOutlet weak var labelGroupProfileDescription: UILabel! @IBOutlet weak var buttonGroupProfileSubmissionsCount: UIButton! @IBOutlet weak var buttonGroupProfileSubmissionsLabel: UIButton! @IBOutlet weak var buttonGroupProfileActionsCount: UIButton! @IBOutlet weak var buttonGroupProfileActionsLabel: UIButton! @IBOutlet weak var buttonGroupProfileUsersCount: UIButton! @IBOutlet weak var buttonGroupProfileUsersLabel: UIButton! @IBOutlet weak var submissionTableView: UITableView! @IBOutlet weak var actionTableView: UITableView! @IBOutlet weak var memberTableView: UITableView! // // MARK: @IBActions // @IBAction func openSubmissionsLikesList(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("LikesTableViewController") as! LikesTableViewController let report = self.groupSubmissionsObjects[(sender.tag)] nextViewController.report = report self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openActionsLikesList(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("LikesTableViewController") as! LikesTableViewController let report = self.groupActionsObjects[(sender.tag)] nextViewController.report = report self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openSubmissionOpenGraphURL(sender: UIButton) { let reportId = sender.tag let report = JSON(self.groupSubmissionsObjects[reportId]) let reportURL = "\(report["properties"]["social"][0]["properties"]["og_url"])" print("openOpenGraphURL \(reportURL)") UIApplication.sharedApplication().openURL(NSURL(string: "\(reportURL)")!) } @IBAction func openActionsOpenGraphURL(sender: UIButton) { let reportId = sender.tag let report = JSON(self.groupActionsObjects[reportId]) let reportURL = "\(report["properties"]["social"][0]["properties"]["og_url"])" print("openOpenGraphURL \(reportURL)") UIApplication.sharedApplication().openURL(NSURL(string: "\(reportURL)")!) } @IBAction func changeGroupProfileTab(sender: UIButton) { if (sender.restorationIdentifier == "buttonTabActionNumber" || sender.restorationIdentifier == "buttonTabActionLabel") { print("Show the Actions tab") self.actionTableView.hidden = false self.submissionTableView.hidden = true self.memberTableView.hidden = true // // Restyle the form Log In Navigation button to appear with an underline // let buttonWidth = self.buttonGroupProfileActionsLabel.frame.width*0.6 let borderWidth = buttonWidth self.groupActionsUnderline.borderColor = CGColor.colorBrand() self.groupActionsUnderline.borderWidth = 3.0 self.groupActionsUnderline.frame = CGRectMake(self.buttonGroupProfileActionsLabel.frame.width*0.2, self.buttonGroupProfileActionsLabel.frame.size.height - 3.0, borderWidth, self.buttonGroupProfileActionsLabel.frame.size.height) self.buttonGroupProfileActionsLabel.layer.addSublayer(self.groupActionsUnderline) self.buttonGroupProfileActionsLabel.layer.masksToBounds = true self.groupUsersUnderline.removeFromSuperlayer() self.groupSubmissionsUnderline.removeFromSuperlayer() } else if (sender.restorationIdentifier == "buttonTabGroupNumber" || sender.restorationIdentifier == "buttonTabGroupLabel") { print("Show the Groups tab") self.actionTableView.hidden = true self.submissionTableView.hidden = true self.memberTableView.hidden = false // // Restyle the form Log In Navigation button to appear with an underline // let buttonWidth = self.buttonGroupProfileUsersLabel.frame.width*0.6 let borderWidth = buttonWidth self.groupUsersUnderline.borderColor = CGColor.colorBrand() self.groupUsersUnderline.borderWidth = 3.0 self.groupUsersUnderline.frame = CGRectMake(self.buttonGroupProfileUsersLabel.frame.width*0.2, self.buttonGroupProfileUsersLabel.frame.size.height - 3.0, borderWidth, self.buttonGroupProfileUsersLabel.frame.size.height) self.buttonGroupProfileUsersLabel.layer.addSublayer(self.groupUsersUnderline) self.buttonGroupProfileUsersLabel.layer.masksToBounds = true self.groupActionsUnderline.removeFromSuperlayer() self.groupSubmissionsUnderline.removeFromSuperlayer() } else if (sender.restorationIdentifier == "buttonTabSubmissionNumber" || sender.restorationIdentifier == "buttonTabSubmissionLabel") { print("Show the Subsmissions tab") self.actionTableView.hidden = true self.submissionTableView.hidden = false self.memberTableView.hidden = true // // Restyle the form Log In Navigation button to appear with an underline // let buttonWidth = self.buttonGroupProfileSubmissionsLabel.frame.width*0.8 let borderWidth = buttonWidth self.groupSubmissionsUnderline.borderColor = CGColor.colorBrand() self.groupSubmissionsUnderline.borderWidth = 3.0 self.groupSubmissionsUnderline.frame = CGRectMake(self.buttonGroupProfileSubmissionsLabel.frame.width*0.1, self.buttonGroupProfileSubmissionsLabel.frame.size.height - 3.0, borderWidth, self.buttonGroupProfileSubmissionsLabel.frame.size.height) self.buttonGroupProfileSubmissionsLabel.layer.addSublayer(self.groupSubmissionsUnderline) self.buttonGroupProfileSubmissionsLabel.layer.masksToBounds = true self.groupUsersUnderline.removeFromSuperlayer() self.groupActionsUnderline.removeFromSuperlayer() } } @IBAction func toggleUILableNumberOfLines(sender: UITapGestureRecognizer) { let field: UILabel = sender.view as! UILabel switch field.numberOfLines { case 0: if sender.view?.restorationIdentifier == "labelGroupProfileDescription" { field.numberOfLines = 3 } else { field.numberOfLines = 1 } break default: field.numberOfLines = 0 break } } @IBAction func openUserSubmissionDirectionsURL(sender: UIButton) { let _submissions = JSON(self.groupSubmissionsObjects) let reportCoordinates = _submissions[sender.tag]["geometry"]["geometries"][0]["coordinates"] UIApplication.sharedApplication().openURL(NSURL(string: "https://www.google.com/maps/dir//\(reportCoordinates[1]),\(reportCoordinates[0])")!) } @IBAction func openUserActionDirectionsURL(sender: UIButton) { let _actions = JSON(self.groupActionsObjects) let reportCoordinates = _actions[sender.tag]["geometry"]["geometries"][0]["coordinates"] UIApplication.sharedApplication().openURL(NSURL(string: "https://www.google.com/maps/dir//\(reportCoordinates[1]),\(reportCoordinates[0])")!) } @IBAction func shareSubmissionsButtonClicked(sender: UIButton) { let _thisReport = JSON(self.groupSubmissionsObjects[(sender.tag)]) let reportId: String = "\(_thisReport["id"])" var objectsToShare: [AnyObject] = [AnyObject]() let reportURL = NSURL(string: "https://www.waterreporter.org/community/reports/" + reportId) var reportImageURL:NSURL! let tmpImageView: UIImageView = UIImageView() // SHARE > REPORT > TITLE // objectsToShare.append("\(_thisReport["properties"]["report_description"])") // SHARE > REPORT > URL // objectsToShare.append(reportURL!) // SHARE > REPORT > IMAGE // let thisReportImageURL = _thisReport["properties"]["images"][0]["properties"]["square"] if thisReportImageURL != nil { reportImageURL = NSURL(string: String(thisReportImageURL)) } tmpImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { objectsToShare.append(Image(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up)) let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender self.presentViewController(activityVC, animated: true, completion: nil) } else { let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender self.presentViewController(activityVC, animated: true, completion: nil) } }) } @IBAction func shareActionsButtonClicked(sender: UIButton) { let _thisReport = JSON(self.groupActionsObjects[(sender.tag)]) let reportId: String = "\(_thisReport["id"])" var objectsToShare: [AnyObject] = [AnyObject]() let reportURL = NSURL(string: "https://www.waterreporter.org/community/reports/" + reportId) var reportImageURL:NSURL! let tmpImageView: UIImageView = UIImageView() // SHARE > REPORT > TITLE // objectsToShare.append("\(_thisReport["properties"]["report_description"])") // SHARE > REPORT > URL // objectsToShare.append(reportURL!) // SHARE > REPORT > IMAGE // let thisReportImageURL = _thisReport["properties"]["images"][0]["properties"]["square"] if thisReportImageURL != nil { reportImageURL = NSURL(string: String(thisReportImageURL)) } tmpImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { objectsToShare.append(Image(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up)) let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender self.presentViewController(activityVC, animated: true, completion: nil) } else { let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = sender self.presentViewController(activityVC, animated: true, completion: nil) } }) } @IBAction func openUserSubmissionMapView(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ActivityMapViewController") as! ActivityMapViewController nextViewController.reportObject = self.groupSubmissionsObjects[sender.tag] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openUserSubmissionCommentsView(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ReportCommentsTableViewController") as! ReportCommentsTableViewController nextViewController.report = self.groupSubmissionsObjects[sender.tag] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openUserActionMapView(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ActivityMapViewController") as! ActivityMapViewController nextViewController.reportObject = self.groupActionsObjects[sender.tag] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openUserActionCommentsView(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ReportCommentsTableViewController") as! ReportCommentsTableViewController nextViewController.report = self.groupActionsObjects[sender.tag] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func loadReportSubmissionOwnerProfile(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController let _thisReport = JSON(self.groupSubmissionsObjects[(sender.tag)]) nextViewController.userId = "\(_thisReport["properties"]["owner"]["id"])" nextViewController.userObject = _thisReport["properties"]["owner"] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func loadReportActionOwnerProfile(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController let _thisReport = JSON(self.groupActionsObjects[(sender.tag)]) nextViewController.userId = "\(_thisReport["properties"]["owner"]["id"])" nextViewController.userObject = _thisReport["properties"]["owner"] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openUserMemberView(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("ProfileTableViewController") as! ProfileTableViewController let _members = JSON(self.groupMembersObjects) nextViewController.userId = "\(_members[sender.tag]["id"])" nextViewController.userObject = _members[sender.tag] self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func loadTerritoryProfileFromSubmissions(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("TerritoryViewController") as! TerritoryViewController var _thisReport: JSON! _thisReport = JSON(self.groupSubmissionsObjects[(sender.tag)]) if "\(_thisReport["properties"]["territory_id"])" != "" && "\(_thisReport["properties"]["territory_id"])" != "null" { nextViewController.territory = "\(_thisReport["properties"]["territory"]["properties"]["huc_8_name"])" nextViewController.territoryId = "\(_thisReport["properties"]["territory_id"])" nextViewController.territoryHUC8Code = "\(_thisReport["properties"]["territory"]["properties"]["huc_8_code"])" self.navigationController?.pushViewController(nextViewController, animated: true) } } @IBAction func loadTerritoryProfileFromActions(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("TerritoryViewController") as! TerritoryViewController var _thisReport: JSON! _thisReport = JSON(self.groupActionsObjects[(sender.tag)]) if "\(_thisReport["properties"]["territory_id"])" != "" && "\(_thisReport["properties"]["territory_id"])" != "null" { nextViewController.territory = "\(_thisReport["properties"]["territory"]["properties"]["huc_8_name"])" nextViewController.territoryId = "\(_thisReport["properties"]["territory_id"])" nextViewController.territoryHUC8Code = "\(_thisReport["properties"]["territory"]["properties"]["huc_8_code"])" self.navigationController?.pushViewController(nextViewController, animated: true) } } @IBAction func emptyMessageAddReport(sender: UIButton) { self.tabBarController?.selectedIndex = 2 } @IBAction func emptyMessageUpdateProfile(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("UserProfileEditTableViewController") as! UserProfileEditTableViewController self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func emptyMessageJoinGroup(sender: UIButton) { let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("GroupsTableViewController") as! GroupsTableViewController self.navigationController?.pushViewController(nextViewController, animated: true) } @IBAction func openNewReportForm(sender: UIButton){ self.tabBarController?.selectedIndex = 2 } // // MARK: Variables // let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) var groupId: String! var groupObject: JSON? var groupProfile: JSON? var groupMembers: JSON? var groupMembersObjects = [AnyObject]() var groupMembersPage: Int = 1 var groupMembersRefreshControl: UIRefreshControl = UIRefreshControl() var groupSubmissions: JSON? var groupSubmissionsObjects = [AnyObject]() var groupSubmissionsPage: Int = 1 var groupSubmissionsRefreshControl: UIRefreshControl = UIRefreshControl() var groupActions: JSON? var groupActionsObjects = [AnyObject]() var groupActionsPage: Int = 1 var groupActionsRefreshControl: UIRefreshControl = UIRefreshControl() var groupSubmissionsUnderline = CALayer() var groupActionsUnderline = CALayer() var groupUsersUnderline = CALayer() var likeDelay: NSTimer = NSTimer() var unlikeDelay: NSTimer = NSTimer() // // MARK: UIKit Overrides // override func viewDidLoad() { super.viewDidLoad() if groupObject != nil && self.groupProfile == nil { self.groupProfile = self.groupObject print("Group Profile \(self.groupProfile)") // Show the Group Name as the title self.navigationItem.title = "Group Profile" // Show the group profile data on screen self.displayGroupProfileInformation() } else if groupObject != nil && self.groupProfile != nil { print("Group Profile \(self.groupProfile!)") // Show the Group Name as the title self.navigationItem.title = "Group Profile" // Show the group profile data on screen self.displayGroupProfileInformation() } // Set dynamic row heights self.submissionTableView.rowHeight = UITableViewAutomaticDimension; self.submissionTableView.estimatedRowHeight = 368.0; self.actionTableView.rowHeight = UITableViewAutomaticDimension; self.actionTableView.estimatedRowHeight = 368.0; self.memberTableView.rowHeight = UITableViewAutomaticDimension; self.memberTableView.estimatedRowHeight = 368.0; // // // self.labelGroupProfileDescription.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(OrganizationTableViewController.toggleUILableNumberOfLines(_:)))) // // SETUP SUBMISSION TABLE // self.submissionTableView.delegate = self self.submissionTableView.dataSource = self groupSubmissionsRefreshControl.restorationIdentifier = "submissionRefreshControl" groupSubmissionsRefreshControl.addTarget(self, action: #selector(OrganizationTableViewController.refreshSubmissionsTableView(_:)), forControlEvents: .ValueChanged) self.submissionTableView.addSubview(groupSubmissionsRefreshControl) // // SETUP SUBMISSION TABLE // self.actionTableView.delegate = self self.actionTableView.dataSource = self groupActionsRefreshControl.restorationIdentifier = "actionRefreshControl" groupActionsRefreshControl.addTarget(self, action: #selector(OrganizationTableViewController.refreshactionTableView(_:)), forControlEvents: .ValueChanged) self.actionTableView.addSubview(groupActionsRefreshControl) // // SETUP SUBMISSION TABLE // self.memberTableView.delegate = self self.memberTableView.dataSource = self groupMembersRefreshControl.restorationIdentifier = "groupRefreshControl" groupMembersRefreshControl.addTarget(self, action: #selector(OrganizationTableViewController.refreshMembersTableView(_:)), forControlEvents: .ValueChanged) self.memberTableView.addSubview(groupMembersRefreshControl) // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up self.view.setNeedsLayout() self.view.layoutIfNeeded() // SET THE DEFAULT TAB // self.actionTableView.hidden = true self.submissionTableView.hidden = false self.memberTableView.hidden = true // // Restyle the form Log In Navigation button to appear with an underline // let buttonWidth = self.buttonGroupProfileSubmissionsLabel.frame.width*0.8 let borderWidth = buttonWidth self.groupSubmissionsUnderline.borderColor = CGColor.colorBrand() self.groupSubmissionsUnderline.borderWidth = 3.0 self.groupSubmissionsUnderline.frame = CGRectMake(self.buttonGroupProfileSubmissionsLabel.frame.width*0.1, self.buttonGroupProfileSubmissionsLabel.frame.size.height - 3.0, borderWidth, self.buttonGroupProfileSubmissionsLabel.frame.size.height) self.buttonGroupProfileSubmissionsLabel.layer.addSublayer(self.groupSubmissionsUnderline) self.buttonGroupProfileSubmissionsLabel.layer.masksToBounds = true self.groupUsersUnderline.removeFromSuperlayer() self.groupActionsUnderline.removeFromSuperlayer() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) self.navigationController?.navigationBarHidden = false } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(true) if (self.isMovingFromParentViewController()) { if (self.navigationController?.viewControllers.last?.restorationIdentifier! == "SearchTableViewController") { self.navigationController?.navigationBarHidden = true } else { self.navigationController?.navigationBarHidden = false } } else { self.navigationController?.navigationBarHidden = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // // MARK: Custom Functionality // func refreshSubmissionsTableView(sender: UIRefreshControl) { self.groupSubmissionsPage = 1 self.groupSubmissions = nil self.groupSubmissionsObjects = [] self.attemptLoadGroupSubmissions(true) } func refreshactionTableView(sender: UIRefreshControl) { self.groupActionsPage = 1 self.groupActions = nil self.groupActionsObjects = [] self.attemptLoadGroupActions(true) } func refreshMembersTableView(sender: UIRefreshControl) { self.groupMembersPage = 1 self.groupMembers = nil self.groupMembersObjects = [] self.attemptLoadGroupUsers(true) } func displayGroupProfileInformation() { // Ensure we have loaded the user profile guard (self.groupProfile != nil) else { return } // Display group's organization name if let _organization_name = self.groupProfile!["properties"]["organization"]["properties"]["name"].string { self.labelGroupProfileName.text = _organization_name } else if let _organization_name = self.groupProfile!["properties"]["name"].string { self.labelGroupProfileName.text = _organization_name } // Display group's organization name if let _organization_description = self.groupProfile!["properties"]["organization"]["properties"]["description"].string { self.labelGroupProfileDescription.text = _organization_description } else if let _organization_description = self.groupProfile!["properties"]["description"].string { self.labelGroupProfileDescription.text = _organization_description } // Display user's profile picture var groupProfileImageURL: NSURL! if let thisGroupProfileImageURLString = self.groupProfile!["properties"]["organization"]["properties"]["picture"].string { groupProfileImageURL = NSURL(string: String(thisGroupProfileImageURLString)) } else if let thisGroupProfileImageURLString = self.groupProfile!["properties"]["picture"].string { groupProfileImageURL = NSURL(string: String(thisGroupProfileImageURLString)) } self.imageViewGroupProfileImage.kf_indicatorType = .Activity self.imageViewGroupProfileImage.kf_showIndicatorWhenLoading = true self.imageViewGroupProfileImage.kf_setImageWithURL(groupProfileImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { self.imageViewGroupProfileImage.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } self.imageViewGroupProfileImage.clipsToBounds = true }) // // Load and display other user information // self.attemptLoadGroupSubmissions() self.attemptLoadGroupActions() self.attemptLoadGroupUsers() } // // MARK: HTTP Request/Response functionality // func buildRequestHeaders() -> [String: String] { let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") return [ "Authorization": "Bearer " + (accessToken! as! String) ] } func attemptLoadGroupUsers(isRefreshingReportsList: Bool = false) { // Set headers let _headers = self.buildRequestHeaders() let GET_GROUP_MEMBERS_ENDPOINT = Endpoints.GET_MANY_ORGANIZATIONS + "/\(self.groupId)/users" let _parameters = [ "page": "\(self.groupMembersPage)" ] Alamofire.request(.GET, GET_GROUP_MEMBERS_ENDPOINT, headers: _headers, parameters: _parameters).responseJSON { response in print("response.result \(response.result)") switch response.result { case .Success(let value): print("Request Success: \(value)") // Assign response to groups variable if (isRefreshingReportsList) { self.groupMembers = JSON(value) self.groupMembersObjects = value["features"] as! [AnyObject] self.groupMembersRefreshControl.endRefreshing() } else { self.groupMembers = JSON(value) self.groupMembersObjects += value["features"] as! [AnyObject] } // Set the number on the profile page let _group_count = self.groupMembers!["properties"]["num_results"] if (_group_count != "") { self.buttonGroupProfileUsersCount.setTitle("\(_group_count)", forState: .Normal) } // Refresh the data in the table so the newest items appear self.memberTableView.reloadData() self.groupMembersPage += 1 break case .Failure(let error): print("Request Failure: \(error)") // Stop showing the loading indicator //self.status("doneLoadingWithError") break } } } func attemptLoadGroupSubmissions(isRefreshingReportsList: Bool = false) { let _parameters = [ "q": "{\"filters\":[{\"name\":\"groups__id\",\"op\":\"any\",\"val\":\"\(self.groupId)\"}],\"order_by\": [{\"field\":\"created\",\"direction\":\"desc\"}]}", "page": "\(self.groupSubmissionsPage)" ] print("_parameters \(_parameters)") Alamofire.request(.GET, Endpoints.GET_MANY_REPORTS, parameters: _parameters) .responseJSON { response in switch response.result { case .Success(let value): // print("Request Success \(Endpoints.GET_MANY_REPORTS) \(value)") if (value.objectForKey("code") != nil) { break } // Assign response to groups variable if (isRefreshingReportsList) { self.groupSubmissions = JSON(value) self.groupSubmissionsObjects = value["features"] as! [AnyObject] self.groupSubmissionsRefreshControl.endRefreshing() } else { self.groupSubmissions = JSON(value) self.groupSubmissionsObjects += value["features"] as! [AnyObject] } // Set visible button count let _submission_count = self.groupSubmissions!["properties"]["num_results"] if (_submission_count != "") { self.buttonGroupProfileSubmissionsCount.setTitle("\(_submission_count)", forState: .Normal) } // Refresh the data in the table so the newest items appear self.submissionTableView.reloadData() self.groupSubmissionsPage += 1 break case .Failure(let error): print("Request Failure: \(error)") // Stop showing the loading indicator //self.status("doneLoadingWithError") break } } } func attemptLoadGroupActions(isRefreshingReportsList: Bool = false) { let _parameters = [ "q": "{\"filters\":[{\"name\":\"groups__id\",\"op\":\"any\",\"val\":\"\(self.groupId)\"},{\"name\":\"state\", \"op\":\"eq\", \"val\":\"closed\"}],\"order_by\": [{\"field\":\"created\",\"direction\":\"desc\"}]}", "page": "\(self.groupActionsPage)" ] Alamofire.request(.GET, Endpoints.GET_MANY_REPORTS, parameters: _parameters) .responseJSON { response in switch response.result { case .Success(let value): print("attemptLoadGroupActions::Request Success \(Endpoints.GET_MANY_REPORTS) \(value)") if (value.objectForKey("code") != nil) { break } // Assign response to groups variable if (isRefreshingReportsList) { self.groupActions = JSON(value) self.groupActionsObjects = value["features"] as! [AnyObject] self.groupActionsRefreshControl.endRefreshing() } else { self.groupActions = JSON(value) self.groupActionsObjects += value["features"] as! [AnyObject] } // Set visible button count let _action_count = self.groupActions!["properties"]["num_results"] if (_action_count != "") { self.buttonGroupProfileActionsCount.setTitle("\(_action_count)", forState: .Normal) } // Refresh the data in the table so the newest items appear self.actionTableView.reloadData() self.groupActionsPage += 1 break case .Failure(let error): print("Request Failure: \(error)") // Stop showing the loading indicator //self.status("doneLoadingWithError") break } } } // // PROTOCOL REQUIREMENT: UITableViewDelegate // func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (tableView.restorationIdentifier == "submissionsTableView") { guard (JSON(self.groupSubmissionsObjects) != nil) else { return 0 } if self.groupSubmissionsObjects.count == 0 { return 1 } return (self.groupSubmissionsObjects.count) } else if (tableView.restorationIdentifier == "actionsTableView") { guard (JSON(self.groupActionsObjects) != nil) else { return 0 } if self.groupActionsObjects.count == 0 { return 1 } return (self.groupActionsObjects.count) } else if (tableView.restorationIdentifier == "membersTableView") { guard (JSON(self.groupMembersObjects) != nil) else { return 0 } if self.groupMembersObjects.count == 0 { return 1 } return (self.groupMembersObjects.count) } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let emptyCell = tableView.dequeueReusableCellWithIdentifier("emptyTableViewCell", forIndexPath: indexPath) as! EmptyTableViewCell print("cellForRowAtIndexPath") if (tableView.restorationIdentifier == "submissionsTableView") { // // Submissions // let cell = tableView.dequeueReusableCellWithIdentifier("userProfileSubmissionCell", forIndexPath: indexPath) as! UserProfileSubmissionTableViewCell guard (JSON(self.groupSubmissionsObjects) != nil) else { return emptyCell } let _submission = JSON(self.groupSubmissionsObjects) let _thisSubmission = _submission[indexPath.row]["properties"] print("Show _thisSubmission SUBMISSION \(_thisSubmission)") if _thisSubmission == nil { emptyCell.emptyMessageDescription.text = "Looks like this group hasn't posted anything yet. Join their group and share a report to get them started!" emptyCell.emptyMessageAction.hidden = false emptyCell.emptyMessageAction.addTarget(self, action: #selector(self.emptyMessageAddReport(_:)), forControlEvents: UIControlEvents.TouchUpInside) return emptyCell } // Report > Owner > Image // cell.reportOwnerImageButton.tag = indexPath.row cell.reportOwnerImageButton.addTarget(self, action: #selector(self.loadReportSubmissionOwnerProfile(_:)), forControlEvents: .TouchUpInside) if let _report_owner_url = _thisSubmission["owner"]["properties"]["picture"].string { let reportOwnerProfileImageURL: NSURL! = NSURL(string: _report_owner_url) cell.imageViewReportOwnerImage.kf_indicatorType = .Activity cell.imageViewReportOwnerImage.kf_showIndicatorWhenLoading = true cell.imageViewReportOwnerImage.kf_setImageWithURL(reportOwnerProfileImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.imageViewReportOwnerImage.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } else { cell.imageViewReportOwnerImage.image = nil } // Report > Owner > Name // if let _first_name = _thisSubmission["owner"]["properties"]["first_name"].string, let _last_name = _thisSubmission["owner"]["properties"]["last_name"].string { cell.reportOwnerName.text = "\(_first_name) \(_last_name)" } else { cell.reportOwnerName.text = "Unknown Reporter" } // Report > Territory > Name // if let _territory_name = _thisSubmission["territory"]["properties"]["huc_8_name"].string { cell.reportTerritoryName.text = "\(_territory_name) Watershed" } else { cell.reportTerritoryName.text = "Unknown Watershed" } // Report > Date // let reportDate = _thisSubmission["report_date"].string if (reportDate != nil) { let dateString: String = reportDate! let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let stringToFormat = dateFormatter.dateFromString(dateString) dateFormatter.dateFormat = "MMM d, yyyy" let displayDate = dateFormatter.stringFromDate(stringToFormat!) if let thisDisplayDate: String? = displayDate { cell.reportDate.text = thisDisplayDate } } else { cell.reportDate.text = "" } // Report > Description // let reportDescription = "\(_thisSubmission["report_description"])" if "\(reportDescription)" != "null" || "\(reportDescription)" != "" { cell.labelReportDescription.text = "\(reportDescription)" cell.labelReportDescription.enabledTypes = [.Hashtag, .URL] cell.labelReportDescription.hashtagColor = UIColor.colorBrand() cell.labelReportDescription.hashtagSelectedColor = UIColor.colorDarkGray() cell.labelReportDescription.handleHashtagTap { hashtag in print("Success. You just tapped the \(hashtag) hashtag") let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("HashtagTableViewController") as! HashtagTableViewController nextViewController.hashtag = hashtag self.navigationController?.pushViewController(nextViewController, animated: true) } cell.labelReportDescription.handleURLTap { url in print("Success. You just tapped the \(url) url") UIApplication.sharedApplication().openURL(NSURL(string: "\(url)")!) } } else { cell.labelReportDescription.text = "" } if _thisSubmission["social"] != nil && _thisSubmission["social"].count != 0 { cell.buttonOpenGraphLink.hidden = false cell.buttonOpenGraphLink.tag = indexPath.row cell.buttonOpenGraphLink.addTarget(self, action: #selector(self.openSubmissionOpenGraphURL(_:)), forControlEvents: .TouchUpInside) cell.buttonOpenGraphLink.layer.cornerRadius = 10.0 cell.buttonOpenGraphLink.clipsToBounds = true cell.reportDate.hidden = true } else { cell.buttonOpenGraphLink.hidden = true cell.reportDate.hidden = false } // Report > Groups // cell.labelReportGroups.text = "Report Group Names" // Report > Image // // var reportImageURL:NSURL! // // if let thisReportImageURL = _thisSubmission["images"][0]["properties"]["square"].string { // reportImageURL = NSURL(string: String(thisReportImageURL)) // } // // cell.reportImageView.kf_indicatorType = .Activity // cell.reportImageView.kf_showIndicatorWhenLoading = true // // cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { // (image, error, cacheType, imageUrl) in // // if (image != nil) { // cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) // } // }) // Report > Image // let reportImages = _thisSubmission["images"] if (reportImages != nil && reportImages.count != 0) { print("Show report image \(reportImages)") var reportImageURL:NSURL! if let thisReportImageURL = _thisSubmission["images"][0]["properties"]["square"].string { reportImageURL = NSURL(string: String(thisReportImageURL)) } cell.reportImageView.kf_indicatorType = .Activity cell.reportImageView.kf_showIndicatorWhenLoading = true cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } else if (_thisSubmission["social"] != nil && _thisSubmission["social"].count != 0) { print("Show open graph image \(_thisSubmission["social"])") if let reportImageURL = NSURL(string: String(_thisSubmission["social"][0]["properties"]["og_image_url"])) { cell.reportImageView.kf_indicatorType = .Activity cell.reportImageView.kf_showIndicatorWhenLoading = true cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } } else { print("No image to show") cell.reportImageView.image = nil } // Report > Group > Name // let reportGroups = _thisSubmission["groups"] var reportGroupsNames: String? = "" let reportGroupsTotal = reportGroups.count var reportGroupsIncrementer = 1 for _group in reportGroups { let thisGroupName = _group.1["properties"]["name"] if reportGroupsTotal == 1 || reportGroupsIncrementer == 1 { reportGroupsNames = "\(thisGroupName)" } else if (reportGroupsTotal > 1 && reportGroupsIncrementer > 1) { reportGroupsNames = reportGroupsNames! + ", " + "\(thisGroupName)" } reportGroupsIncrementer += 1 } cell.labelReportGroups.text = reportGroupsNames // Buttons > Share // cell.buttonReportShare.tag = indexPath.row // Buttons > Map // cell.buttonReportMap.tag = indexPath.row // Buttons > Directions // cell.buttonReportDirections.tag = indexPath.row // Buttons > Comments // cell.buttonReportComments.tag = indexPath.row let reportComments = _thisSubmission["comments"] var reportCommentsCountText: String = "0 comments" if reportComments.count == 1 { reportCommentsCountText = "1 comment" } else if reportComments.count >= 1 { reportCommentsCountText = String(reportComments.count) + " comments" } else { reportCommentsCountText = "0 comments" } cell.buttonReportComments.setTitle(reportCommentsCountText, forState: UIControlState.Normal) if (_thisSubmission["closed_by"] != nil) { let badgeImage: UIImage = UIImage(named: "icon--Badge")! cell.buttonReportComments.setImage(badgeImage, forState: .Normal) cell.buttonReportComments.imageView?.contentMode = .ScaleAspectFit } else { let badgeImage: UIImage = UIImage(named: "icon--comment")! cell.buttonReportComments.setImage(badgeImage, forState: .Normal) cell.buttonReportComments.imageView?.contentMode = .ScaleAspectFit } cell.buttonReportTerritory.tag = indexPath.row // Report Like Button // cell.buttonReportLike.tag = indexPath.row var _user_id_integer: Int = 0 if let _user_id_number = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber { _user_id_integer = _user_id_number.integerValue } print("_user_id_integer \(_user_id_integer)") if _user_id_integer != 0 { print("Setup the like stuff") let _hasLiked = self.userHasLikedReport(_thisSubmission, _current_user_id: _user_id_integer) cell.buttonReportLike.setImage(UIImage(named: "icon--heart"), forState: .Normal) if (_hasLiked) { cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) cell.buttonReportLike.addTarget(self, action: #selector(unlikeCurrentReport(_:)), forControlEvents: .TouchUpInside) cell.buttonReportLike.setImage(UIImage(named: "icon--heartred"), forState: .Normal) } else { cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) cell.buttonReportLike.addTarget(self, action: #selector(likeCurrentReport(_:)), forControlEvents: .TouchUpInside) } cell.buttonReportLikeCount.tag = indexPath.row cell.buttonReportLikeCount.addTarget(self, action: #selector(self.openSubmissionsLikesList(_:)), forControlEvents: .TouchUpInside) // Update the total likes count // let _report_likes_count: Int = _thisSubmission["likes"].count // Check if we have previously liked this photo. If so, we need to take // that into account when adding a new like. // let _report_likes_updated_total: Int! = _report_likes_count var reportLikesCountText: String = "" if _report_likes_updated_total == 1 { reportLikesCountText = "1 like" cell.buttonReportLikeCount.hidden = false } else if _report_likes_updated_total >= 1 { reportLikesCountText = "\(_report_likes_updated_total) likes" cell.buttonReportLikeCount.hidden = false } else { reportLikesCountText = "0 likes" cell.buttonReportLikeCount.hidden = false } cell.buttonReportLikeCount.setTitle(reportLikesCountText, forState: .Normal) } if (indexPath.row == self.groupSubmissionsObjects.count - 2 && self.groupSubmissionsObjects.count < self.groupSubmissions!["properties"]["num_results"].int) { self.attemptLoadGroupSubmissions() } return cell } else if (tableView.restorationIdentifier == "actionsTableView") { print("cellForRowAtIndex Actions") // // Actions // let cell = tableView.dequeueReusableCellWithIdentifier("userProfileActionCell", forIndexPath: indexPath) as! UserProfileActionsTableViewCell guard (self.groupActions != nil) else { return emptyCell } let _actions = JSON(self.groupActionsObjects) let _thisSubmission = _actions[indexPath.row]["properties"] print("Show _thisSubmission ACTION \(_thisSubmission)") if _thisSubmission == nil { emptyCell.emptyMessageDescription.text = "Looks like this group hasn't posted anything yet. Join their group and share a report to get them started!" emptyCell.emptyMessageAction.hidden = false emptyCell.emptyMessageAction.addTarget(self, action: #selector(self.emptyMessageAddReport(_:)), forControlEvents: UIControlEvents.TouchUpInside) return emptyCell } // Report > Owner > Image // cell.reportOwnerImageButton.tag = indexPath.row cell.reportOwnerImageButton.addTarget(self, action: #selector(self.loadReportActionOwnerProfile(_:)), forControlEvents: .TouchUpInside) if let _report_owner_url = _thisSubmission["owner"]["properties"]["picture"].string { let reportOwnerProfileImageURL: NSURL! = NSURL(string: _report_owner_url) cell.imageViewReportOwnerImage.kf_indicatorType = .Activity cell.imageViewReportOwnerImage.kf_showIndicatorWhenLoading = true cell.imageViewReportOwnerImage.kf_setImageWithURL(reportOwnerProfileImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.imageViewReportOwnerImage.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } else { cell.imageViewReportOwnerImage.image = nil } // Report > Owner > Name // if let _first_name = _thisSubmission["owner"]["properties"]["first_name"].string, let _last_name = _thisSubmission["owner"]["properties"]["last_name"].string { cell.reportOwnerName.text = "\(_first_name) \(_last_name)" } else { cell.reportOwnerName.text = "Unknown Reporter" } // Report > Territory > Name // if let _territory_name = _thisSubmission["territory"]["properties"]["huc_8_name"].string { cell.reportTerritoryName.text = "\(_territory_name) Watershed" } else { cell.reportTerritoryName.text = "Unknown Watershed" } // Report > Date // let reportDate = _thisSubmission["report_date"].string if (reportDate != nil) { let dateString: String = reportDate! let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" let stringToFormat = dateFormatter.dateFromString(dateString) dateFormatter.dateFormat = "MMM d, yyyy" let displayDate = dateFormatter.stringFromDate(stringToFormat!) if let thisDisplayDate: String? = displayDate { cell.reportDate.text = thisDisplayDate } } else { cell.reportDate.text = "" } // Report > Description // let reportDescription = "\(_thisSubmission["report_description"])" if "\(reportDescription)" != "null" || "\(reportDescription)" != "" { cell.labelReportDescription.text = "\(reportDescription)" cell.labelReportDescription.enabledTypes = [.Hashtag, .URL] cell.labelReportDescription.hashtagColor = UIColor.colorBrand() cell.labelReportDescription.hashtagSelectedColor = UIColor.colorDarkGray() cell.labelReportDescription.handleHashtagTap { hashtag in print("Success. You just tapped the \(hashtag) hashtag") let nextViewController = self.storyBoard.instantiateViewControllerWithIdentifier("HashtagTableViewController") as! HashtagTableViewController nextViewController.hashtag = hashtag self.navigationController?.pushViewController(nextViewController, animated: true) } cell.labelReportDescription.handleURLTap { url in print("Success. You just tapped the \(url) url") UIApplication.sharedApplication().openURL(NSURL(string: "\(url)")!) } } else { cell.labelReportDescription.text = "" } if _thisSubmission["social"] != nil && _thisSubmission["social"].count != 0 { cell.buttonOpenGraphLink.hidden = false cell.buttonOpenGraphLink.tag = indexPath.row cell.buttonOpenGraphLink.addTarget(self, action: #selector(self.openActionsOpenGraphURL(_:)), forControlEvents: .TouchUpInside) cell.buttonOpenGraphLink.layer.cornerRadius = 10.0 cell.buttonOpenGraphLink.clipsToBounds = true cell.reportDate.hidden = true } else { cell.buttonOpenGraphLink.hidden = true cell.reportDate.hidden = false } // Report > Group > Name // let reportGroups = _thisSubmission["groups"] var reportGroupsNames: String? = "" let reportGroupsTotal = reportGroups.count var reportGroupsIncrementer = 1 for _group in reportGroups { let thisGroupName = _group.1["properties"]["name"] if reportGroupsTotal == 1 || reportGroupsIncrementer == 1 { reportGroupsNames = "\(thisGroupName)" } else if (reportGroupsTotal > 1 && reportGroupsIncrementer > 1) { reportGroupsNames = reportGroupsNames! + ", " + "\(thisGroupName)" } reportGroupsIncrementer += 1 } cell.labelReportGroups.text = reportGroupsNames // // Report > Image // // // // // // REPORT > IMAGE // // // var reportImageURL:NSURL! // // if let thisReportImageURL = _thisSubmission["images"][0]["properties"]["square"].string { // reportImageURL = NSURL(string: String(thisReportImageURL)) // } // // cell.reportImageView.kf_indicatorType = .Activity // cell.reportImageView.kf_showIndicatorWhenLoading = true // // cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { // (image, error, cacheType, imageUrl) in // // if (image != nil) { // cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) // } // }) // Report > Image // let reportImages = _thisSubmission["images"] if (reportImages != nil && reportImages.count != 0) { print("Show report image \(reportImages)") var reportImageURL:NSURL! if let thisReportImageURL = _thisSubmission["images"][0]["properties"]["square"].string { reportImageURL = NSURL(string: String(thisReportImageURL)) } cell.reportImageView.kf_indicatorType = .Activity cell.reportImageView.kf_showIndicatorWhenLoading = true cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } else if (_thisSubmission["social"] != nil && _thisSubmission["social"].count != 0) { print("Show open graph image \(_thisSubmission["social"])") if let reportImageURL = NSURL(string: String(_thisSubmission["social"][0]["properties"]["og_image_url"])) { cell.reportImageView.kf_indicatorType = .Activity cell.reportImageView.kf_showIndicatorWhenLoading = true cell.reportImageView.kf_setImageWithURL(reportImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.reportImageView.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) } } else { print("No image to show") cell.reportImageView.image = nil } // Buttons > Territory // if cell.buttonReportTerritory != nil { cell.buttonReportTerritory.tag = indexPath.row } // Buttons > Share // cell.buttonReportShare.tag = indexPath.row // Buttons > Map // cell.buttonReportMap.tag = indexPath.row // Buttons > Directions // cell.buttonReportDirections.tag = indexPath.row // Buttons > Comments // cell.buttonReportComments.tag = indexPath.row let reportComments = _thisSubmission["comments"] var reportCommentsCountText: String = "0 comments" if reportComments.count == 1 { reportCommentsCountText = "1 comment" } else if reportComments.count >= 1 { reportCommentsCountText = String(reportComments.count) + " comments" } else { reportCommentsCountText = "0 comments" } cell.buttonReportComments.setTitle(reportCommentsCountText, forState: UIControlState.Normal) if (_thisSubmission["closed_by"] != nil) { let badgeImage: UIImage = UIImage(named: "icon--Badge")! cell.buttonReportComments.setImage(badgeImage, forState: .Normal) cell.buttonReportComments.imageView?.contentMode = .ScaleAspectFit } else { let badgeImage: UIImage = UIImage(named: "icon--comment")! cell.buttonReportComments.setImage(badgeImage, forState: .Normal) cell.buttonReportComments.imageView?.contentMode = .ScaleAspectFit } // Report Like Button // cell.buttonReportLike.tag = indexPath.row var _user_id_integer: Int = 0 if let _user_id_number = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber { _user_id_integer = _user_id_number.integerValue } print("_user_id_integer \(_user_id_integer)") if _user_id_integer != 0 { print("Setup the like stuff") let _hasLiked = self.userHasLikedReport(_thisSubmission, _current_user_id: _user_id_integer) cell.buttonReportLike.setImage(UIImage(named: "icon--heart"), forState: .Normal) if (_hasLiked) { cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) cell.buttonReportLike.addTarget(self, action: #selector(unlikeCurrentReport(_:)), forControlEvents: .TouchUpInside) cell.buttonReportLike.setImage(UIImage(named: "icon--heartred"), forState: .Normal) } else { cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) cell.buttonReportLike.addTarget(self, action: #selector(likeCurrentReport(_:)), forControlEvents: .TouchUpInside) } cell.buttonReportLikeCount.tag = indexPath.row cell.buttonReportLikeCount.addTarget(self, action: #selector(self.openActionsLikesList(_:)), forControlEvents: .TouchUpInside) // Update the total likes count // let _report_likes_count: Int = _thisSubmission["likes"].count // Check if we have previously liked this photo. If so, we need to take // that into account when adding a new like. // let _report_likes_updated_total: Int! = _report_likes_count var reportLikesCountText: String = "" if _report_likes_updated_total == 1 { reportLikesCountText = "1 like" cell.buttonReportLikeCount.hidden = false } else if _report_likes_updated_total >= 1 { reportLikesCountText = "\(_report_likes_updated_total) likes" cell.buttonReportLikeCount.hidden = false } else { reportLikesCountText = "0 likes" cell.buttonReportLikeCount.hidden = false } cell.buttonReportLikeCount.setTitle(reportLikesCountText, forState: .Normal) } if (indexPath.row == self.groupActionsObjects.count - 2 && self.groupActionsObjects.count < self.groupActions!["properties"]["num_results"].int) { self.attemptLoadGroupActions() } return cell } else if (tableView.restorationIdentifier == "membersTableView") { // // Groups // let cell = tableView.dequeueReusableCellWithIdentifier("userProfileMemberCell", forIndexPath: indexPath) as! UserProfileMembersTableViewCell guard (JSON(self.groupMembersObjects) != nil) else { return emptyCell } let _members = JSON(self.groupMembersObjects) let _thisSubmission = _members[indexPath.row]["properties"] print("Show _thisSubmission GROUP \(_thisSubmission)") if _thisSubmission == nil { emptyCell.emptyMessageDescription.text = "No members yet but you can always join!" emptyCell.emptyMessageAction.hidden = false emptyCell.emptyMessageAction.setTitle("Join this group", forState: .Normal) emptyCell.emptyMessageAction.addTarget(self, action: #selector(self.emptyMessageJoinGroup(_:)), forControlEvents: UIControlEvents.TouchUpInside) return emptyCell } // Display Member Name if let _first_name = _thisSubmission["first_name"].string, let _last_name = _thisSubmission["last_name"].string{ cell.labelGroupMemberName.text = "\(_first_name) \(_last_name)" } // Display Member Image var groupProfileImageURL:NSURL! = NSURL(string: "https://www.waterreporter.org/community/images/badget--MissingUser.png") if let _group_image_url = _thisSubmission["picture"].string { groupProfileImageURL = NSURL(string: _group_image_url) } cell.imageViewGroupMemberProfileImage.kf_indicatorType = .Activity cell.imageViewGroupMemberProfileImage.kf_showIndicatorWhenLoading = true cell.imageViewGroupMemberProfileImage.kf_setImageWithURL(groupProfileImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: { (image, error, cacheType, imageUrl) in if (image != nil) { cell.imageViewGroupMemberProfileImage.image = UIImage(CGImage: (image?.CGImage)!, scale: (image?.scale)!, orientation: UIImageOrientation.Up) } }) // Link to Member profile cell.buttonMemberSelection.tag = indexPath.row if (indexPath.row == self.groupMembersObjects.count - 2 && self.groupMembersObjects.count < self.groupMembers!["properties"]["num_results"].int) { self.attemptLoadGroupUsers() } return cell } print("Not showing anything, returing an empty cell") return emptyCell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("row tapped \(indexPath)") } // // MARK: Like Functionality // func userHasLikedReport(_report: JSON, _current_user_id: Int) -> Bool { if (_report["likes"].count != 0) { for _like in _report["likes"] { if (_like.1["properties"]["owner_id"].intValue == _current_user_id) { return true } } } return false } func updateReportLikeCount(indexPathRow: Int, addLike: Bool = true) { print("LikeController::updateReportLikeCount") let _indexPath = NSIndexPath(forRow: indexPathRow, inSection: 0) var _report: JSON! if (self.actionTableView.hidden == false) { var _cell = self.actionTableView.cellForRowAtIndexPath(_indexPath) as! UserProfileActionsTableViewCell _report = JSON(self.groupActionsObjects[(indexPathRow)].objectForKey("properties")!) // Change the Heart icon to red // if (addLike) { _cell.buttonReportLike.setImage(UIImage(named: "icon--heartred"), forState: .Normal) _cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) _cell.buttonReportLike.addTarget(self, action: #selector(unlikeCurrentReport(_:)), forControlEvents: .TouchUpInside) } else { _cell.buttonReportLike.setImage(UIImage(named: "icon--heart"), forState: .Normal) _cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) _cell.buttonReportLike.addTarget(self, action: #selector(likeCurrentReport(_:)), forControlEvents: .TouchUpInside) } // Update the total likes count // let _report_likes_count: Int = _report["likes"].count // Check if we have previously liked this photo. If so, we need to take // that into account when adding a new like. // let _previously_liked: Bool = self.hasPreviouslyLike(_report["likes"]) var _report_likes_updated_total: Int! = _report_likes_count if (addLike) { if (_previously_liked) { _report_likes_updated_total = _report_likes_count } else { _report_likes_updated_total = _report_likes_count+1 } } else { if (_previously_liked) { _report_likes_updated_total = _report_likes_count-1 } else { _report_likes_updated_total = _report_likes_count } } var reportLikesCountText: String = "" if _report_likes_updated_total == 1 { reportLikesCountText = "1 like" _cell.buttonReportLikeCount.hidden = false } else if _report_likes_updated_total >= 1 { reportLikesCountText = "\(_report_likes_updated_total) likes" _cell.buttonReportLikeCount.hidden = false } else { reportLikesCountText = "0 likes" _cell.buttonReportLikeCount.hidden = false } _cell.buttonReportLikeCount.setTitle(reportLikesCountText, forState: .Normal) } else if (self.submissionTableView.hidden == false) { var _cell = self.submissionTableView.cellForRowAtIndexPath(_indexPath) as! UserProfileSubmissionTableViewCell _report = JSON(self.groupSubmissionsObjects[(indexPathRow)].objectForKey("properties")!) // Change the Heart icon to red // if (addLike) { _cell.buttonReportLike.setImage(UIImage(named: "icon--heartred"), forState: .Normal) _cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) _cell.buttonReportLike.addTarget(self, action: #selector(unlikeCurrentReport(_:)), forControlEvents: .TouchUpInside) } else { _cell.buttonReportLike.setImage(UIImage(named: "icon--heart"), forState: .Normal) _cell.buttonReportLike.removeTarget(nil, action: nil, forControlEvents: .AllEvents) _cell.buttonReportLike.addTarget(self, action: #selector(likeCurrentReport(_:)), forControlEvents: .TouchUpInside) } // Update the total likes count // let _report_likes_count: Int = _report["likes"].count // Check if we have previously liked this photo. If so, we need to take // that into account when adding a new like. // let _previously_liked: Bool = self.hasPreviouslyLike(_report["likes"]) var _report_likes_updated_total: Int! = _report_likes_count if (addLike) { if (_previously_liked) { _report_likes_updated_total = _report_likes_count } else { _report_likes_updated_total = _report_likes_count+1 } } else { if (_previously_liked) { _report_likes_updated_total = _report_likes_count-1 } else { _report_likes_updated_total = _report_likes_count } } var reportLikesCountText: String = "" if _report_likes_updated_total == 1 { reportLikesCountText = "1 like" _cell.buttonReportLikeCount.hidden = false } else if _report_likes_updated_total >= 1 { reportLikesCountText = "\(_report_likes_updated_total) likes" _cell.buttonReportLikeCount.hidden = false } else { reportLikesCountText = "0 likes" _cell.buttonReportLikeCount.hidden = false } _cell.buttonReportLikeCount.setTitle(reportLikesCountText, forState: .Normal) } else { return; } } func hasPreviouslyLike(likes: JSON) -> Bool { print("hasPreviouslyLike::likes \(likes)") // LOOP OVER PREVIOUS LIKES AND SEE IF CURRENT USER ID IS ONE OF THE OWNER IDS let _user_id_number = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as! NSNumber for _like in likes { if (_like.1["properties"]["owner_id"].intValue == _user_id_number.integerValue) { print("_like.1 \(_like.1)") return true } } return false } func likeCurrentReport(sender: UIButton) { print("LikeController::likeCurrentReport Incrementing Report Likes by 1") // Update the visible "# like" count of likes // self.updateReportLikeCount(sender.tag) // Restart delay // self.likeDelay.invalidate() let infoDict : [String : AnyObject] = ["sender": sender.tag] self.likeDelay = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: #selector(self.attemptLikeCurrentReport(_:)), userInfo: infoDict, repeats: false) } func attemptLikeCurrentReport(timer: NSTimer) { print("userInfo \(timer.userInfo!)") let _arguments = timer.userInfo as! [String : AnyObject] if let _sender_tag = _arguments["sender"] { let senderTag = _sender_tag.integerValue print("_sender_tag \(senderTag)") // Create necessary Authorization header for our request // let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let _headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] // // PARAMETERS // var _report: JSON! if (self.actionTableView.hidden == false) { _report = JSON(self.groupActionsObjects[(senderTag)]) } else if (self.submissionTableView.hidden == false) { _report = JSON(self.groupSubmissionsObjects[(senderTag)]) } else { return; } let _report_id: String = "\(_report["id"])" let _parameters: [String:AnyObject] = [ "report_id": _report_id ] Alamofire.request(.POST, Endpoints.POST_LIKE, parameters: _parameters, headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): // print("Response Success \(value)") self.updateReportLikes(_report_id, reportSenderTag: senderTag) break case .Failure(let error): print("Response Failure \(error)") break } } } } func unlikeCurrentReport(sender: UIButton) { print("LikeController::unlikeCurrentReport Decrementing Report Likes by 1") // Update the visible "# like" count of likes // self.updateReportLikeCount(sender.tag, addLike: false) // Restart delay // self.unlikeDelay.invalidate() let infoDict : [String : AnyObject] = ["sender": sender.tag] self.unlikeDelay = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(1), target: self, selector: #selector(self.attemptUnikeCurrentReport(_:)), userInfo: infoDict, repeats: false) } func attemptUnikeCurrentReport(timer: NSTimer) { print("userInfo \(timer.userInfo!)") let _arguments = timer.userInfo as! [String : AnyObject] if let _sender_tag = _arguments["sender"] { let senderTag = _sender_tag.integerValue print("_sender_tag \(senderTag)") // Create necessary Authorization header for our request // let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let _headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] // // PARAMETERS // var _report: JSON! if (self.actionTableView.hidden == false) { _report = JSON(self.groupActionsObjects[(senderTag)]) } else if (self.submissionTableView.hidden == false) { _report = JSON(self.groupSubmissionsObjects[(senderTag)]) } else { return; } let _report_id: String = "\(_report["id"])" let _parameters: [String:AnyObject] = [ "report_id": _report_id ] // // ENDPOINT // var _like_id: String = "" let _user_id_number = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as! NSNumber if (_report["properties"]["likes"].count != 0) { for _like in _report["properties"]["likes"] { if (_like.1["properties"]["owner_id"].intValue == _user_id_number.integerValue) { print("_like.1 \(_like.1)") _like_id = "\(_like.1["id"])" } } } let _endpoint: String = Endpoints.DELETE_LIKE + "/\(_like_id)" // // REQUEST // Alamofire.request(.DELETE, _endpoint, parameters: _parameters, headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): // print("Response Success \(value)") self.updateReportLikes(_report_id, reportSenderTag: senderTag) break case .Failure(let error): print("Response Failure \(error)") break } } } } func updateReportLikes(_report_id: String, reportSenderTag: Int) { // Create necessary Authorization header for our request // let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken") let _headers = [ "Authorization": "Bearer " + (accessToken! as! String) ] Alamofire.request(.GET, Endpoints.GET_MANY_REPORTS + "/\(_report_id)", headers: _headers, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): print("Response value \(value)") if (self.actionTableView.hidden == false) { self.groupActionsObjects[(reportSenderTag)] = value } else if (self.submissionTableView.hidden == false) { self.groupSubmissionsObjects[(reportSenderTag)] = value } else { return; } break case .Failure(let error): print("Response Failure \(error)") break } } } }
4464e8c9bc78d77ce7ea081227212cc9
41.088496
255
0.561326
false
false
false
false
steve-holmes/music-app-2
refs/heads/master
MusicApp/Modules/MusicCenter/MusicNotification.swift
mit
1
// // MusicNotification.swift // MusicApp // // Created by Hưng Đỗ on 6/12/17. // Copyright © 2017 HungDo. All rights reserved. // import Foundation import RxSwift import NSObject_Rx protocol MusicNotification { func onStartPlaying() func onControlPress() } class MAMusicNotification: NSObject, MusicNotification { var center: MusicCenter init(center: MusicCenter) { self.center = center super.init() onStartPlaying() onControlPress() center.currentTimeOutput .subscribe(onNext: { [weak self] currentTime in self?.onResponse(.didGetCurrentTime(currentTime)) }) .addDisposableTo(rx_disposeBag) center.durationTimeOutput .subscribe(onNext: { [weak self] duration in self?.onResponse(.didGetDuration(duration)) }) .addDisposableTo(rx_disposeBag) center.trackOutput .subscribe(onNext: { [weak self] track in self?.onResponse(.didGetTrack(track)) }) .addDisposableTo(rx_disposeBag) center.modeOutput .subscribe(onNext: { [weak self] mode in self?.onResponse(.didGetMode(mode)) }) .addDisposableTo(rx_disposeBag) center.didPlayOutput .subscribe(onNext: { [weak self] _ in self?.onResponse(.didPlay) }) .addDisposableTo(rx_disposeBag) center.didPauseOutput .subscribe(onNext: { [weak self] _ in self?.onResponse(.didPause) }) .addDisposableTo(rx_disposeBag) center.didStopOutput .subscribe(onNext: { [weak self] _ in self?.onResponse(.didStop) }) .addDisposableTo(rx_disposeBag) } fileprivate func subscribe(_ name: Notification.Name, onNext: @escaping (MusicCenter, Notification) -> Void) { NotificationCenter.default.rx.notification(name) .subscribe(onNext: { [weak self] notification in guard let this = self else { return } onNext(this.center, notification) }) .addDisposableTo(self.rx_disposeBag) } } // MARK: Playing extension MAMusicNotification { func onStartPlaying() { subscribe(.MusicCenterPlaying) { center, notification in center.onPlaying() .subscribe(onNext: { response in self.onResponse(response) }) .addDisposableTo(self.rx_disposeBag) } subscribe(.MusicCenterPlaylistPlaying) { center, notification in let playlist = notification.userInfo![kMusicCenterPlaylist] as! Playlist center.onPlaylistPlaying(playlist) .subscribe(onNext: { response in self.onResponse(response) }) .addDisposableTo(self.rx_disposeBag) } subscribe(.MusicCenterTracksPlaying) { center, notification in let tracks = notification.userInfo![kMusicCenterTracks] as! [Track] let selectedTrack = notification.userInfo![kMusicCenterSelectedTrack] as! Track center.onTracks(tracks, selectedTrack: selectedTrack) .subscribe(onNext: { response in self.onResponse(response) }) .addDisposableTo(self.rx_disposeBag) } subscribe(.MusicCenterSongPlaying) { center, notification in let song = notification.userInfo![kMusicCenterSong] as! Song center.onSongPlaying(song) .subscribe(onNext: { response in self.onResponse(response) }) .addDisposableTo(self.rx_disposeBag) } subscribe(.MusicCenterPlayerIsPlaying) { center, notification in self.onResponse(.didGetIsPlaying(center.isPlaying)) } } } // MARK: Controls extension MAMusicNotification { func onControlPress() { subscribe(.MusicCenterPlay) { center, notification in center.onPlay() } subscribe(.MusicCenterPlaySong) { center, notification in let track = notification.userInfo![kMusicCenterTrack] as! Track center.onPlay(track: track) } subscribe(.MusicCenterSeek) { center, notification in let currentTime = notification.userInfo![kMusicCenterCurrentTime] as! Int center.onSeek(currentTime) } subscribe(.MusicCenterPause) { center, notification in center.onPause() } subscribe(.MusicCenterRefresh) { center, notification in center.onRefresh() } subscribe(.MusicCenterBackward) { center, notification in center.onBackward() } subscribe(.MusicCenterForward) { center, notification in center.onForward() } subscribe(.MusicCenterRepeat) { center, notification in center.onRepeat() } } } // MARK: Response extension MAMusicNotification { fileprivate func onResponse(_ response: MusicCenterResponse) { let center = NotificationCenter.default switch response { case .willPreparePlaying: center.post(name: .MusicCenterWillPreparePlaying, object: self) case .didPreparePlaying: center.post(name: .MusicCenterDidPreparePlaying, object: self) case .didGetTracks(let track): center.post(name: .MusicCenterDidGetTracks, object: self, userInfo: [kMusicCenterTracks: track]) case .didGetDuration(let duration): center.post(name: .MusicCenterDidGetDuration, object: self, userInfo: [kMusicCenterDuration: duration]) case .didGetCurrentTime(let currentTime): center.post(name: .MusicCenterDidGetCurrentTime, object: self, userInfo: [kMusicCenterCurrentTime: currentTime]) case .didGetTrack(let track): center.post(name: .MusicCenterDidGetTrack, object: self, userInfo: [kMusicCenterTrack: track]) case .didGetMode(let mode): center.post(name: .MusicCenterDidGetMode, object: self, userInfo: [kMusicCenterMode: mode]) case .didGetIsPlaying(let isPlaying): center.post(name: .MusicCenterDidGetIsPlaying, object: self, userInfo: [kMusicCenterIsPlaying: isPlaying]) case .didPlay: center.post(name: .MusicCenterDidPlay, object: self) case .didPause: center.post(name: .MusicCenterDidPause, object: self) case .didStop: center.post(name: .MusicCenterDidStop, object: self) } } }
d1cea9623086f6b11a9f35cd4cd10ee5
31.804651
124
0.58344
false
false
false
false
crazypoo/PTools
refs/heads/master
Pods/JXSegmentedView/Sources/Dot/JXSegmentedDotCell.swift
mit
1
// // JXSegmentedDotCell.swift // JXSegmentedView // // Created by jiaxin on 2018/12/28. // Copyright © 2018 jiaxin. All rights reserved. // import UIKit open class JXSegmentedDotCell: JXSegmentedTitleCell { open var dotView = UIView() open override func commonInit() { super.commonInit() contentView.addSubview(dotView) } open override func layoutSubviews() { super.layoutSubviews() guard let myItemModel = itemModel as? JXSegmentedDotItemModel else { return } dotView.center = CGPoint(x: titleLabel.frame.maxX + myItemModel.dotOffset.x, y: titleLabel.frame.minY + myItemModel.dotOffset.y) } open override func reloadData(itemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) { super.reloadData(itemModel: itemModel, selectedType: selectedType ) guard let myItemModel = itemModel as? JXSegmentedDotItemModel else { return } dotView.backgroundColor = myItemModel.dotColor dotView.bounds = CGRect(x: 0, y: 0, width: myItemModel.dotSize.width, height: myItemModel.dotSize.height) dotView.isHidden = !myItemModel.dotState dotView.layer.cornerRadius = myItemModel.dotCornerRadius } }
d4f9affdc9bd2cae5fb258761a851ab8
29.47619
136
0.69375
false
false
false
false
janukobytsch/cardiola
refs/heads/master
cardiola/cardiola/PlanRepository.swift
mit
1
// // PlanRepository.swift // cardiola // // Created by Janusch Jacoby on 30/01/16. // Copyright © 2016 BPPolze. All rights reserved. // import RealmSwift class PlanRepository { private var _currentPlan: MeasurementPlan? var currentPlan: MeasurementPlan { if (_currentPlan == nil) { // attempt to load from database var entries = [MeasurementPlanEntry]() let realm = try! Realm() let dbEntries = realm.objects(MeasurementPlanEntry) entries.appendContentsOf(dbEntries.asArray()) if entries.count == 0 { // generate mock data entries = PlanRepository.createRandomEntries() } let plan = MeasurementPlan(entries: entries) self._currentPlan = plan } return self._currentPlan! } /** Factory method to create a random plan for demo purposes. - returns: plan for next week */ static func createRandomEntries() -> [MeasurementPlanEntry] { var entries = [MeasurementPlanEntry]() for index in 0...3 { let timeInterval = NSTimeInterval(5 * 64 + index * 86400) let date = NSDate(timeIntervalSinceNow: timeInterval) let entry = MeasurementPlanEntry(dueDate: date) entry.isBloodPressureEntry = random(min: 0, max: 1) == 0 entry.isHeartRateEntry = random(min: 0, max: 1) == 0 entry.pending() entry.save() entries.append(entry) } return entries } }
0efde8d68d48a9ff7944ecae85c58e62
27.568966
69
0.558575
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILGen/keypath_application.swift
apache-2.0
12
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class A {} class B {} protocol P {} protocol Q {} // CHECK-LABEL: sil hidden [ossa] @{{.*}}loadable func loadable(readonly: A, writable: inout A, value: B, kp: KeyPath<A, B>, wkp: WritableKeyPath<A, B>, rkp: ReferenceWritableKeyPath<A, B>) { // CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY:%0]] : // CHECK: [[KP_COPY:%.*]] = copy_value [[KP:%3]] // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: kp] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE:%1]] : // CHECK: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]] // CHECK: end_access [[ACCESS]] // CHECK: [[KP_COPY:%.*]] = copy_value [[KP]] // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = writable[keyPath: kp] // CHECK: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] : // CHECK: [[KP_COPY:%.*]] = copy_value [[WKP:%4]] // CHECK: [[KP_UPCAST:%.*]] = upcast [[KP_COPY]] : $WritableKeyPath<A, B> to $KeyPath<A, B> // CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A // CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]] // CHECK: [[GET:%.*]] = function_ref @swift_getAtKeyPath : // CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B // CHECK: apply [[GET]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_UPCAST]]) // CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]] // CHECK: destroy_value [[RESULT]] _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath _ = writable[keyPath: rkp] // CHECK: [[KP_COPY:%.*]] = copy_value [[WKP]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE:%2]] : $B // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[WRITABLE]] : // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ACCESS]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] writable[keyPath: wkp] = value // CHECK-NEXT: [[ROOT_COPY:%.*]] = copy_value [[READONLY]] : // CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B // CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A // CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]] // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_addr [[ROOT_TEMP]] // CHECK-NEXT: dealloc_stack [[ROOT_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] readonly[keyPath: rkp] = value // CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [unknown] [[WRITABLE]] : // CHECK-NEXT: [[ROOT_COPY:%.*]] = load [copy] [[ACCESS]] : // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: [[KP_COPY:%.*]] = copy_value [[RKP:%5]] // CHECK-NEXT: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] : $B // CHECK-NEXT: [[ROOT_TEMP:%.*]] = alloc_stack $A // CHECK-NEXT: store [[ROOT_COPY]] to [init] [[ROOT_TEMP]] // CHECK-NEXT: [[VALUE_TEMP:%.*]] = alloc_stack $B // CHECK-NEXT: store [[VALUE_COPY]] to [init] [[VALUE_TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SET:%.*]] = function_ref @swift_setAtReferenceWritableKeyPath : // CHECK-NEXT: apply [[SET]]<A, B>([[ROOT_TEMP]], [[KP_COPY]], [[VALUE_TEMP]]) // CHECK-NEXT: dealloc_stack [[VALUE_TEMP]] // CHECK-NEXT: destroy_addr [[ROOT_TEMP]] // CHECK-NEXT: dealloc_stack [[ROOT_TEMP]] // CHECK-NEXT: destroy_value [[KP_COPY]] writable[keyPath: rkp] = value } // CHECK-LABEL: } // end sil function '{{.*}}loadable // CHECK-LABEL: sil hidden [ossa] @{{.*}}addressOnly func addressOnly(readonly: P, writable: inout P, value: Q, kp: KeyPath<P, Q>, wkp: WritableKeyPath<P, Q>, rkp: ReferenceWritableKeyPath<P, Q>) { // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: rkp] // CHECK: function_ref @swift_setAtWritableKeyPath : writable[keyPath: wkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : readonly[keyPath: rkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden [ossa] @{{.*}}reabstracted func reabstracted(readonly: @escaping () -> (), writable: inout () -> (), value: @escaping (A) -> B, kp: KeyPath<() -> (), (A) -> B>, wkp: WritableKeyPath<() -> (), (A) -> B>, rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) { // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: kp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: wkp] // CHECK: function_ref @swift_getAtKeyPath : _ = readonly[keyPath: rkp] // CHECK: function_ref @swift_getAtKeyPath : _ = writable[keyPath: rkp] // CHECK: function_ref @swift_setAtWritableKeyPath : writable[keyPath: wkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : readonly[keyPath: rkp] = value // CHECK: function_ref @swift_setAtReferenceWritableKeyPath : writable[keyPath: rkp] = value } // CHECK-LABEL: sil hidden [ossa] @{{.*}}partial func partial<A>(valueA: A, valueB: Int, pkpA: PartialKeyPath<A>, pkpB: PartialKeyPath<Int>, akp: AnyKeyPath) { // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath : // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath : // CHECK: apply [[PROJECT]]<A> _ = valueA[keyPath: pkpA] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtAnyKeyPath : // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: akp] // CHECK: [[PROJECT:%.*]] = function_ref @swift_getAtPartialKeyPath : // CHECK: apply [[PROJECT]]<Int> _ = valueB[keyPath: pkpB] } extension Int { var b: Int { get { return 0 } set { } } var u: Int { get { return 0 } set { } } var tt: Int { get { return 0 } set { } } } // CHECK-LABEL: sil hidden [ossa] @{{.*}}writebackNesting func writebackNesting(x: inout Int, y: WritableKeyPath<Int, Int>, z: WritableKeyPath<Int, Int>, w: Int) -> Int { // -- get 'b' // CHECK: function_ref @$sSi19keypath_applicationE1bSivg // -- apply keypath y // CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath : // CHECK: ([[Y_ADDR:%.*]], [[Y_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int> // -- get 'u' // CHECK: function_ref @$sSi19keypath_applicationE1uSivg // -- apply keypath z // CHECK: [[PROJECT_FN:%.*]] = function_ref @swift_modifyAtWritableKeyPath : // CHECK: ([[Z_ADDR:%.*]], [[Z_TOKEN:%.*]]) = begin_apply [[PROJECT_FN]]<Int, Int> // -- set 'tt' // CHECK: function_ref @$sSi19keypath_applicationE2ttSivs // -- destroy owner for keypath projection z // CHECK: end_apply [[Z_TOKEN]] // -- set 'u' // CHECK: function_ref @$sSi19keypath_applicationE1uSivs // -- destroy owner for keypath projection y // CHECK: end_apply [[Y_TOKEN]] // -- set 'b' // CHECK: function_ref @$sSi19keypath_applicationE1bSivs x.b[keyPath: y].u[keyPath: z].tt = w }
1af3c47dff9448c20e8a1bb4ba635fe7
39.511211
93
0.58313
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
Storage/PageMetadata.swift
mpl-2.0
2
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SDWebImage enum MetadataKeys: String { case imageURL = "image" case imageDataURI = "image_data_uri" case pageURL = "url" case title = "title" case description = "description" case type = "type" case provider = "provider" case favicon = "icon" case keywords = "keywords" } /* * Value types representing a page's metadata */ public struct PageMetadata { public let id: Int? public let siteURL: String public let mediaURL: String? public let title: String? public let description: String? public let type: String? public let providerName: String? public let faviconURL: String? public let keywordsString: String? public var keywords: Set<String> { guard let string = keywordsString else { return Set() } let strings = string.split(separator: ",", omittingEmptySubsequences: true).map(String.init) return Set(strings) } public init(id: Int?, siteURL: String, mediaURL: String?, title: String?, description: String?, type: String?, providerName: String?, mediaDataURI: String?, faviconURL: String? = nil, keywords: String? = nil, cacheImages: Bool = true) { self.id = id self.siteURL = siteURL self.mediaURL = mediaURL self.title = title self.description = description self.type = type self.providerName = providerName self.faviconURL = faviconURL self.keywordsString = keywords if let urlString = mediaURL, let url = URL(string: urlString), cacheImages { self.cacheImage(fromDataURI: mediaDataURI, forURL: url) } } public static func fromDictionary(_ dict: [String: Any]) -> PageMetadata? { guard let siteURL = dict[MetadataKeys.pageURL.rawValue] as? String else { return nil } return PageMetadata(id: nil, siteURL: siteURL, mediaURL: dict[MetadataKeys.imageURL.rawValue] as? String, title: dict[MetadataKeys.title.rawValue] as? String, description: dict[MetadataKeys.description.rawValue] as? String, type: dict[MetadataKeys.type.rawValue] as? String, providerName: dict[MetadataKeys.provider.rawValue] as? String, mediaDataURI: dict[MetadataKeys.imageDataURI.rawValue] as? String, faviconURL: dict[MetadataKeys.favicon.rawValue] as? String, keywords: dict[MetadataKeys.keywords.rawValue] as? String) } fileprivate func cacheImage(fromDataURI dataURI: String?, forURL url: URL) { let manager = SDWebImageManager.shared() func cacheUsingURLOnly() { manager.cachedImageExists(for: url) { exists in if !exists { self.downloadAndCache(fromURL: url) } } } guard let dataURI = dataURI, let dataURL = URL(string: dataURI) else { cacheUsingURLOnly() return } manager.cachedImageExists(for: dataURL) { exists in if let data = try? Data(contentsOf: dataURL), let image = UIImage(data: data), !exists { self.cache(image: image, forURL: url) } else { cacheUsingURLOnly() } } } fileprivate func downloadAndCache(fromURL webUrl: URL) { let manager = SDWebImageManager.shared() manager.loadImage(with: webUrl, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in if let image = image { self.cache(image: image, forURL: webUrl) } } } fileprivate func cache(image: UIImage, forURL url: URL) { SDWebImageManager.shared().saveImage(toCache: image, for: url) } }
18cf20e32e5d3d6809559173a1738d9f
36.67619
327
0.628918
false
false
false
false
ZeldaIV/TDC2015-FP
refs/heads/master
Carthage/Checkouts/RxSwift/RxSwift/Observables/Implementations/Filter.swift
gpl-3.0
17
// // Filter.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class FilterSink<O : ObserverType>: Sink<O>, ObserverType { typealias Element = O.E typealias Parent = Filter<Element> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { switch event { case .Next(let value): do { let satisfies = try self.parent.predicate(value) if satisfies { observer?.on(.Next(value)) } } catch let e { observer?.on(.Error(e)) self.dispose() } case .Completed: fallthrough case .Error: observer?.on(event) self.dispose() } } } class Filter<Element> : Producer<Element> { typealias Predicate = (Element) throws -> Bool let source: Observable<Element> let predicate: Predicate init(source: Observable<Element>, predicate: Predicate) { self.source = source self.predicate = predicate } override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = FilterSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } }
f61133112d2834c61c8261f27de0fd8d
26.766667
139
0.547147
false
false
false
false
vincentherrmann/multilinear-math
refs/heads/master
Sources/LinearRegression.swift
apache-2.0
1
// // LinearRegression.swift // MultilinearMath // // Created by Vincent Herrmann on 25.04.16. // Copyright © 2016 Vincent Herrmann. All rights reserved. // import Foundation public func linearRegression(x: Tensor<Float>, y: Tensor<Float>) -> Tensor<Float> { let example = TensorIndex.a let feature = TensorIndex.b let exampleCount = x.modeSizes[0] let featureCount = x.modeSizes[1] var samples = Tensor<Float>(modeSizes: [exampleCount, featureCount + 1], repeatedValue: 1) samples[all, 1...featureCount] = x // formula: w = (X^T * X)^-1 * X * y let sampleCovariance = samples[example, feature] * samples[example, .k] let inverseCovariance = inverse(sampleCovariance, rowMode: 0, columnMode: 1) let parameters = inverseCovariance[feature, .k] * samples[example, .k] * y[example] return parameters } open class LinearRegressionEstimator: ParametricTensorFunction { open var parameters: [Tensor<Float>] var currentInput: Tensor<Float> = zeros() fileprivate let example = TensorIndex.a fileprivate let feature = TensorIndex.b public init(featureCount: Int) { parameters = [zeros(featureCount), zeros()] parameters[0].indices = [feature] } open func output(_ input: Tensor<Float>) -> Tensor<Float> { if(input.modeCount == 1) { currentInput = Tensor<Float>(modeSizes: [1, input.modeSizes[0]], values: input.values) currentInput.indices = [example, feature] } else { currentInput = input[example, feature] } let hypothesis = (currentInput * parameters[0]) + parameters[1] return hypothesis } open func gradients(_ gradientWrtOutput: Tensor<Float>) -> (wrtInput: Tensor<Float>, wrtParameters: [Tensor<Float>]) { let parameter0Gradient = gradientWrtOutput * currentInput let parameter1Gradient = sum(gradientWrtOutput, overModes: [0]) let inputGradient = sum(gradientWrtOutput * parameters[0], overModes: [0]) return (inputGradient, [parameter0Gradient, parameter1Gradient]) } open func updateParameters(_ subtrahends: [Tensor<Float>]) { parameters[0] = parameters[0] - subtrahends[0] parameters[1] = parameters[1] - subtrahends[1] } } /// Squared error cost for linear regression open class LinearRegressionCost: CostFunction { open var estimator: ParametricTensorFunction open var regularizers: [ParameterRegularizer?] = [nil, nil] public init(featureCount: Int) { estimator = LinearRegressionEstimator(featureCount: featureCount) } open func costForEstimate(_ estimate: Tensor<Float>, target: Tensor<Float>) -> Float { let exampleCount = Float(target.elementCount) let distance = estimate - target let cost = (0.5 / exampleCount) * (distance * distance) return cost.values[0] } open func gradientForEstimate(_ estimate: Tensor<Float>, target: Tensor<Float>) -> Tensor<Float> { if(estimate.indices != target.indices) { print("abstract indices of estimate and target should be the same!") } let exampleCount = Float(target.elementCount) let gradient = (1/exampleCount) * (estimate - target) return gradient } }
aac8b63f28f0b4e15ad475c2be7514ff
34.431579
122
0.651812
false
false
false
false
lyimin/EyepetizerApp
refs/heads/master
EyepetizerApp/EyepetizerApp/Views/ChoiceView/EYEChoiceHeaderView.swift
mit
1
// // EYEChoiceHeaderView.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/16. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit class EYEChoiceHeaderView: UICollectionReusableView, Reusable { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() self.addSubview(titleLabel) self.addSubview(imageView) titleLabel.snp_makeConstraints { [unowned self](make) -> Void in make.edges.equalTo(self) } imageView.snp_makeConstraints { [unowned self](make) -> Void in make.leading.trailing.equalTo(self) make.top.equalTo(self).offset(self.height*0.25) make.height.equalTo(self.height*0.5) } } var title : String? { didSet { if let _ = title { self.imageView.hidden = true self.titleLabel.hidden = false self.titleLabel.text = title! } else { self.imageView.hidden = false self.titleLabel.hidden = true } } } var image : String? { didSet { if let _ = image { self.titleLabel.hidden = true self.imageView.hidden = false self.imageView.yy_setImageWithURL(NSURL(string: image!)!, options: .ProgressiveBlur) } else { self.titleLabel.hidden = false self.imageView.hidden = true } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var titleLabel : UILabel = { var titleLabel : UILabel = UILabel() titleLabel.textAlignment = .Center titleLabel.font = UIFont.customFont_Lobster(fontSize: UIConstant.UI_FONT_16) return titleLabel }() private lazy var imageView : UIImageView = { var imageView : UIImageView = UIImageView () imageView.contentMode = .ScaleAspectFit return imageView }() }
9b71090452619dada7a71a4d1c7ad968
28.597222
100
0.565931
false
false
false
false
egnwd/ic-bill-hack
refs/heads/master
MondoKit/MondoCategory.swift
mit
2
// // MondoCategory.swift // MondoKit // // Created by Mike Pollard on 26/01/2016. // Copyright © 2016 Mike Pollard. All rights reserved. // import Foundation import SwiftyJSON import SwiftyJSONDecodable public enum MondoCategory : String { case Mondo = "mondo" case General = "general" case EatingOut = "eating_out" case Expenses = "expenses" case Transport = "transport" case Cash = "cash" case Bills = "bills" case Entertainment = "entertainment" case Shopping = "shopping" case Holidays = "holidays" case Groceries = "groceries" } extension MondoCategory : SwiftyJSONDecodable { }
9d05c6a598b062dabb731508090a9051
22.555556
55
0.688679
false
false
false
false
aliceatlas/daybreak
refs/heads/master
Classes/SBPopUpButton.swift
bsd-2-clause
1
/* SBPopUpButton.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class SBPopUpButton: NSPopUpButton { var backgroundImage: NSImage? var operation: ((NSMenuItem) -> Void)? override var menu: NSMenu? { didSet { if menu != nil { for item in menu!.itemArray { item.target = self item.action = #selector(executeAction(_:)) } } } } override class func initialize() { SBPopUpButton.setCellClass(SBPopUpButtonCell.self) } // MARK: Actions func executeAction(sender: AnyObject) { if let item = sender as? NSMenuItem { selectItem(representedObject: item.representedObject) setNeedsDisplayInRect(bounds) if let item = sender as? NSMenuItem { operation?(item) } } } func selectItem(representedObject object: AnyObject?) { if let menu = menu { menu.selectItem(representedObject: object) setNeedsDisplayInRect(bounds) } } func deselectItem() { if let menu = menu { menu.deselectItem() setNeedsDisplayInRect(bounds) } } } class SBPopUpButtonCell: NSPopUpButtonCell { override func drawWithFrame(cellFrame: NSRect, inView controlView: NSView) { let view = controlView as! SBPopUpButton if let image = view.backgroundImage { SBPreserveGraphicsState { let transform = NSAffineTransform() transform.translateXBy(0.0, yBy: view.bounds.size.height) transform.scaleXBy(1.0, yBy:-1.0) transform.concat() image.drawInRect(view.bounds, fromRect: .zero, operation: .CompositeSourceOver, fraction: 1.0) } } if let itemTitle: NSString = view.menu?.selectedItem?.title.ifNotEmpty { var r = view.bounds let padding: CGFloat = 10.0 let shadow = NSShadow() shadow.shadowOffset = NSMakeSize(0.0, -1.0) shadow.shadowColor = .whiteColor() let style = NSMutableParagraphStyle() style.lineBreakMode = .ByTruncatingTail let attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(11.0), NSForegroundColorAttributeName: NSColor.blackColor(), NSShadowAttributeName: shadow, NSParagraphStyleAttributeName: style] r.size = itemTitle.sizeWithAttributes(attributes) r.size.width.constrain(max: view.bounds.size.width - padding * 2) r.origin.x = padding r.origin.y = (view.bounds.size.height - r.size.height) / 2 itemTitle.drawInRect(r, withAttributes: attributes) } } } /* @implementation SBPopUpButton @synthesize menu; - (void)dealloc { [menu release]; [super dealloc]; } #pragma mark Setter - (void)setMenu:(NSMenu *)inMenu { if (menu != inMenu) { [inMenu retain]; [menu release]; menu = inMenu; for (NSMenuItem *item in [menu itemArray]) { [item setTarget:self]; [item setAction:@selector(executeAction:)]; } } } #pragma mark NSCoding Protocol - (id)initWithCoder:(NSCoder *)decoder { [super initWithCoder:decoder]; if ([decoder allowsKeyedCoding]) { if ([decoder containsValueForKey:@"menu"]) { self.menu = [decoder decodeObjectForKey:@"menu"]; } } return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; if (menu) [coder encodeObject:menu forKey:@"menu"]; } #pragma mark Actions - (void)executeAction:(id)sender { [self selectItemWithRepresentedObject:[sender representedObject]]; [self setNeedsDisplayInRect:self.bounds]; if (target && action) { if ([target respondsToSelector:action]) { [target performSelector:action withObject:sender]; } } } - (void)selectItemWithRepresentedObject:(id)representedObject { if (menu) { [menu selectItemWithRepresentedObject:representedObject]; [self setNeedsDisplayInRect:self.bounds]; } } - (void)deselectItem { if (menu) { [menu deselectItem]; [self setNeedsDisplayInRect:self.bounds]; } } - (void)showMenu:(NSEvent *)theEvent { if (menu) { NSPoint location = [theEvent locationInWindow]; NSPoint point = [self convertPoint:location fromView:nil]; NSPoint newLocation = NSMakePoint(location.x - point.x, location.y - point.y); NSEvent *event = [NSEvent mouseEventWithType:[theEvent type] location:newLocation modifierFlags:[theEvent modifierFlags] timestamp:[theEvent timestamp] windowNumber:[theEvent windowNumber] context:[theEvent context] eventNumber:[theEvent eventNumber] clickCount:[theEvent clickCount] pressure:[theEvent pressure]]; [NSMenu popUpContextMenu:menu withEvent:event forView:self]; } } #pragma mark Event - (void)mouseDragged:(NSEvent *)theEvent { } - (void)mouseUp:(NSEvent *)theEvent { if (enabled) { NSPoint location = [theEvent locationInWindow]; NSPoint point = [self convertPoint:location fromView:nil]; if (NSPointInRect(point, self.bounds)) { self.pressed = NO; [self showMenu:theEvent]; } } } #pragma mark Drawing - (void)drawRect:(NSRect)rect { [super drawRect:rect]; if (menu) { NSMenuItem *item = [menu selectedItem]; NSString *itemTitle = [item title]; if ([itemTitle length] > 0) { NSRect r = self.bounds; NSDictionary *attributes = nil; NSShadow *shadow = nil; NSMutableParagraphStyle *style = nil; CGFloat padding = 10.0; shadow = [[NSShadow alloc] init]; [shadow setShadowOffset:NSMakeSize(0.0, -1.0)]; [shadow setShadowColor:[NSColor whiteColor]]; style = [[NSMutableParagraphStyle alloc] init]; [style setLineBreakMode:NSLineBreakByTruncatingTail]; attributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSFont boldSystemFontOfSize:11.0], NSFontAttributeName, [NSColor blackColor], NSForegroundColorAttributeName, shadow, NSShadowAttributeName, style, NSParagraphStyleAttributeName, nil]; r.size = [itemTitle sizeWithAttributes:attributes]; if (r.size.width > (self.bounds.size.width - padding * 2)) r.size.width = (self.bounds.size.width - padding * 2); r.origin.x = padding; r.origin.y = (self.bounds.size.height - r.size.height) / 2; [itemTitle drawInRect:r withAttributes:attributes]; [shadow release]; [style release]; } } } @end */ /* @interface SBPopUpButton : SBButton <NSCoding> { NSMenu *menu; } @property (retain) NSMenu *menu; // Setter - (void)setMenu:(NSMenu *)inMenu; // Actions - (void)executeAction:(id)sender; - (void)selectItemWithRepresentedObject:(id)representedObject; - (void)deselectItem; - (void)showMenu:(NSEvent *)theEvent; @end */
35d63a3d81136d6d282881c7b50e7225
30.085409
322
0.629379
false
false
false
false
andriitishchenko/vkLibManage
refs/heads/master
vkLibManage/AppDelegate.swift
mit
1
// // AppDelegate.swift // vkLibManage // // Created by Andrii Tiischenko on 10/5/16. // Copyright © 2016 Andrii Tiischenko. All rights reserved. // import UIKit import VK_ios_sdk //= "notificationProgress" //let notificationProgress: String = "notificationProgress" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var backgroundSessionCompletionHandler : (() -> Void)? /* private func application(application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool { let wasHandled:Bool = VKSdk.processOpen(url, fromApplication: sourceApplication) return wasHandled } */ func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { let wasHandled:Bool = VKSdk.processOpen(url, fromApplication: "com.vkLibManage") return wasHandled } /* func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool{ return true } */ func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let s = Player.sharedInstance return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. DBManager.sharedInstance.saveContext() } func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { backgroundSessionCompletionHandler = completionHandler } }
64c4a1ca3560d0e907155799d7b625ce
40.011494
285
0.709922
false
false
false
false
wangwugang1314/weiBoSwift
refs/heads/master
weiBoSwift/weiBoSwift/Tool/YBNetworking.swift
apache-2.0
1
// // YBNetworking.swift // weiBoSwift // // Created by MAC on 15/11/27. // Copyright © 2015年 MAC. All rights reserved. // import UIKit import AFNetworking /// 返回参数 typealias YBNetworkingFinish = (result: [String: AnyObject]?, error: NSError?) -> () class YBNetworking: NSObject { // MARK: - 属性 /// 单利 static let sharedInstance = YBNetworking() /// AppKey static let client_id = "2811696621" /// App Secret static let client_secret = "283af988db3ec9bbb6fbb8cd41ec9d7c" /// 回调地址 static let redirect_uri = "https://www.baidu.com/" // MARK: - 发微博 /// 发微博(带图片) func sendWeiBo(text: String, image: UIImage, finish: (isSeccess: Bool) -> ()){ let path = "https://upload.api.weibo.com/2/statuses/upload.json" let dic = ["access_token": YBUserModel.userModel()!.access_token!, "status": text] POST(path, image: image, parameters: dic) { (result, error) -> () in if error != nil { finish(isSeccess: false) }else{ finish(isSeccess: true) } } } /// 发微博(不带图片) func sendWeiBo(text: String, finish: (isSeccess: Bool) -> ()){ let path = "/2/statuses/update.json" let dic = ["access_token": YBUserModel.userModel()!.access_token!, "status": text] POST(path, parameters: dic) { (result, error) -> () in if error != nil { finish(isSeccess: false) }else{ finish(isSeccess: true) } } } /// MARK: - 加载微博数据 func loadWeiBoData(newData: Int ,max_id:Int ,finish: (result: [[String: AnyObject]]?, error: NSError?) -> ()) { let path = "/2/statuses/home_timeline.json" let dic = ["access_token": YBUserModel.userModel()!.access_token!, "since_id": newData, "max_id": max_id]; // 加载数据 GET(path, parameters: dic as? [String : AnyObject]) { (result, error) -> () in finish(result: result?["statuses"] as? [[String: AnyObject]], error: error) } } /// 加载用户登录信息 func loadUserLoginData(code: String, finish: YBNetworkingFinish) { let path = "/oauth2/access_token" let dic = ["client_id": YBNetworking.client_id, "client_secret": YBNetworking.client_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": YBNetworking.redirect_uri] // 加载网络数据 POST(path, parameters: dic) { (result, error) -> () in finish(result: result, error: error) } } /// 加载用户信息 func loadUserData(finish: YBNetworkingFinish){ let path = "/2/users/show.json" let dic = ["access_token": YBUserModel.userModel()!.access_token!, "uid": YBUserModel.userModel()!.uid!] // 加载网络数据 GET(path, parameters: dic as [String: AnyObject]) { (result, error) -> () in finish(result: result, error: error) } } // MARK: - 封装网络请求 /// 封装POST(带图片) private func POST(URLString: String, image: UIImage, parameters: [String: AnyObject]?, finish: YBNetworkingFinish) { // POST请求 netManager.POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in let data = UIImagePNGRepresentation(image)! formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png") }, success: { (_, data) -> Void in // 成功调用 finish(result: data as? [String : AnyObject], error: nil) }) { (_, error) -> Void in // 失败调用 finish(result: nil, error: error) } } /// 封装POST private func POST(URLString: String, parameters: [String: AnyObject]?, finish: YBNetworkingFinish) { // POST请求 netManager.POST(URLString, parameters: parameters, success: { (_, data) -> Void in // 成功调用 finish(result: data as? [String : AnyObject], error: nil) }) { (_, error) -> Void in // 失败调用 finish(result: nil, error: error) } } /// 封装GET private func GET(URLString: String, parameters: [String: AnyObject]?, finish: YBNetworkingFinish) { // GET请求 netManager.GET(URLString, parameters: parameters, success: { (_, data) -> Void in // 成功调用 finish(result: data as? [String : AnyObject], error: nil) }) { (_, error) -> Void in // 失败调用 finish(result: nil, error: error) } } // MAEK: - 懒加载 /// 网络工具 private let netManager: AFHTTPSessionManager = { // 创建并设置baseURL let manager = AFHTTPSessionManager(baseURL: NSURL(string: "https://api.weibo.com/")) // 添加解析类型 manager.responseSerializer.acceptableContentTypes?.insert("text/plain") return manager }() }
f785f72d3bedd476480b91f78b4920b6
34.906475
120
0.552795
false
false
false
false
shnhrrsn/ImagePalette
refs/heads/master
demo/Palette/Album.swift
apache-2.0
1
// // Album.swift // Palette // // Created by Shaun Harrison on 8/16/17. // Copyright © 2017 shnhrrsn. All rights reserved. // import UIKit struct Album { var name: String var rank: Int var artworkUrl: URL var artwork: UIImage? func loadArtwork(completion: @escaping (UIImage?) -> Void) { if let artwork = self.artwork { return completion(artwork) } URLSession.shared.dataTask(with: self.artworkUrl) { (data, response, error) in guard let data = data, let image = UIImage(data: data) else { print("Failed to load album artwork: \(self) - \(String(describing: error))") return completion(nil) } completion(image) }.resume() } } extension Album: Comparable { static func ==(lhs: Album, rhs: Album) -> Bool { return lhs.rank == rhs.rank } static func <(lhs: Album, rhs: Album) -> Bool { return lhs.rank < rhs.rank } }
4af804a3b691124b30568ec953de6d0b
18.377778
81
0.658257
false
false
false
false
netguru/inbbbox-ios
refs/heads/develop
Inbbbox/Source Files/Managers/Animators/TabBarAnimator.swift
gpl-3.0
1
// // TabBarAnimator.swift // Inbbbox // // Created by Patryk Kaczmarek on 21/01/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import PromiseKit class TabBarAnimator { fileprivate let centerButton = RoundedButton() fileprivate let tabBarView = CenterButtonTabBarView() fileprivate var tabBarHeight: CGFloat { return tabBarView.intrinsicContentSize.height } init(view: LoginView) { let tabBarHeight = tabBarView.intrinsicContentSize.height tabBarView.layer.shadowColor = UIColor(white: 0, alpha: 0.03).cgColor tabBarView.layer.shadowRadius = 1 tabBarView.layer.shadowOpacity = 0.6 view.addSubview(tabBarView) tabBarView.frame = CGRect( x: 0, y: view.frame.maxY, width: view.frame.width, height: tabBarHeight ) tabBarView.layoutIfNeeded() centerButton.setImage(UIImage(named: "ic-ball-active"), for: .normal) centerButton.backgroundColor = .white tabBarView.addSubview(centerButton) centerButton.frame = CGRect( x: tabBarView.frame.width / 2 - centerButton.intrinsicContentSize.width / 2, y: -centerButton.intrinsicContentSize.height - 8, width: centerButton.intrinsicContentSize.width, height: centerButton.intrinsicContentSize.height ) } func animateTabBar() -> Promise<Void> { return Promise<Void> { fulfill, _ in firstly { prepare() }.then { self.fadeCenterButtonIn() }.then { when(fulfilled: [self.slideTabBar(), self.slideTabBarItemsSubsequently(), self.positionCenterButton()]) }.then { fulfill() }.catch { _ in } } } } private extension TabBarAnimator { func slideTabBarItemsSubsequently() -> Promise<Void> { return Promise<Void> { fulfill, _ in UIView.animateKeyframes(withDuration: 1, delay: 0, options: .layoutSubviews, animations: { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.25, animations: { self.tabBarView.likesItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.25, relativeDuration: 0.25, animations: { self.tabBarView.bucketsItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.25, animations: { self.tabBarView.followingItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) UIView.addKeyframe(withRelativeStartTime: 0.75, relativeDuration: 0.25, animations: { self.tabBarView.accountItemViewVerticalConstraint?.constant -= self.tabBarHeight self.tabBarView.layoutIfNeeded() }) }, completion: { _ in fulfill() }) } } func slideTabBar() -> Promise<Void> { var frame = tabBarView.frame frame.origin.y -= tabBarHeight return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, animations: { self.tabBarView.frame = frame }, completion: { _ in fulfill() }) } } func positionCenterButton() -> Promise<Void> { var frame = centerButton.frame frame.origin.y += tabBarHeight return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, animations: { self.centerButton.frame = frame }, completion: { _ in fulfill() }) } } func fadeCenterButtonIn() -> Promise<Void> { return Promise<Void> { fulfill, _ in UIView.animate(withDuration: 0.5, delay: 0.1, options: [], animations: { self.centerButton.alpha = 1 }, completion: { _ in fulfill() }) } } func prepare() -> Promise<Void> { tabBarView.likesItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.bucketsItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.followingItemViewVerticalConstraint?.constant += tabBarHeight tabBarView.accountItemViewVerticalConstraint?.constant += tabBarHeight centerButton.alpha = 0.0 return Promise<Void>(value:Void()) } }
6b844e1c5cd16cb745ce4f3943c41c1f
32.921986
119
0.593561
false
false
false
false
ryuichis/swift-ast
refs/heads/master
Sources/AST/Declaration/Block/GetterSetterKeywordBlock.swift
apache-2.0
2
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ public struct GetterSetterKeywordBlock { public struct GetterKeywordClause { public let attributes: Attributes public let mutationModifier: MutationModifier? public init( attributes: Attributes = [], mutationModifier: MutationModifier? = nil ) { self.attributes = attributes self.mutationModifier = mutationModifier } } public struct SetterKeywordClause { public let attributes: Attributes public let mutationModifier: MutationModifier? public init( attributes: Attributes = [], mutationModifier: MutationModifier? = nil ) { self.attributes = attributes self.mutationModifier = mutationModifier } } public let getter: GetterKeywordClause public let setter: SetterKeywordClause? public init(getter: GetterKeywordClause, setter: SetterKeywordClause? = nil) { self.getter = getter self.setter = setter } } extension GetterSetterKeywordBlock.GetterKeywordClause : ASTTextRepresentable { public var textDescription: String { let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) " let modifierText = mutationModifier.map({ "\($0.textDescription) " }) ?? "" return "\(attrsText)\(modifierText)get" } } extension GetterSetterKeywordBlock.SetterKeywordClause : ASTTextRepresentable { public var textDescription: String { let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) " let modifierText = mutationModifier.map({ "\($0.textDescription) " }) ?? "" return "\(attrsText)\(modifierText)set" } } extension GetterSetterKeywordBlock : ASTTextRepresentable { public var textDescription: String { // no matter the original sequence, we always output getter first, // and then the setter if exists let setterStr = setter.map({ "\n\($0.textDescription)" }) ?? "" return "{\n\(getter.textDescription)\(setterStr)\n}" } }
dcaeb5499e5b0d485c01099dd2673d5c
32.710526
85
0.720921
false
false
false
false
beneiltis/SwiftCharts
refs/heads/master
SwiftCharts/Layers/ChartPointsViewsLayer.swift
apache-2.0
7
// // ChartPointsViewsLayer.swift // SwiftCharts // // Created by ischuetz on 27/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartPointsViewsLayer<T: ChartPoint, U: UIView>: ChartPointsLayer<T> { typealias ChartPointViewGenerator = (chartPointModel: ChartPointLayerModel<T>, layer: ChartPointsViewsLayer<T, U>, chart: Chart) -> U? typealias ViewWithChartPoint = (view: U, chartPointModel: ChartPointLayerModel<T>) private(set) var viewsWithChartPoints: [ViewWithChartPoint] = [] private let delayBetweenItems: Float = 0 let viewGenerator: ChartPointViewGenerator private var conflictSolver: ChartViewsConflictSolver<T, U>? public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints:[T], viewGenerator: ChartPointViewGenerator, conflictSolver: ChartViewsConflictSolver<T, U>? = nil, displayDelay: Float = 0, delayBetweenItems: Float = 0) { self.viewGenerator = viewGenerator self.conflictSolver = conflictSolver super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, displayDelay: displayDelay) } override func display(#chart: Chart) { super.display(chart: chart) self.viewsWithChartPoints = self.generateChartPointViews(chartPointModels: self.chartPointsModels, chart: chart) if self.delayBetweenItems == 0 { for v in self.viewsWithChartPoints {chart.addSubview(v.view)} } else { var next: (Int, dispatch_time_t) -> () = {_, _ in} // no-op closure, workaround for local recursive function. See http://stackoverflow.com/a/24272256 next = {index, delay in if index < self.viewsWithChartPoints.count { dispatch_after(delay, dispatch_get_main_queue()) {() -> Void in let view = self.viewsWithChartPoints[index].view chart.addSubview(view) next(index + 1, ChartUtils.toDispatchTime(self.delayBetweenItems)) } } } next(0, 0) } } private func generateChartPointViews(#chartPointModels: [ChartPointLayerModel<T>], chart: Chart) -> [ViewWithChartPoint] { let viewsWithChartPoints = self.chartPointsModels.reduce(Array<ViewWithChartPoint>()) {viewsWithChartPoints, model in if let view = self.viewGenerator(chartPointModel: model, layer: self, chart: chart) { return viewsWithChartPoints + [(view: view, chartPointModel: model)] } else { return viewsWithChartPoints } } self.conflictSolver?.solveConflicts(views: viewsWithChartPoints) return viewsWithChartPoints } override public func chartPointsForScreenLoc(screenLoc: CGPoint) -> [T] { return self.filterChartPoints{self.inXBounds(screenLoc.x, view: $0.view) && self.inYBounds(screenLoc.y, view: $0.view)} } override public func chartPointsForScreenLocX(x: CGFloat) -> [T] { return self.filterChartPoints{self.inXBounds(x, view: $0.view)} } override public func chartPointsForScreenLocY(y: CGFloat) -> [T] { return self.filterChartPoints{self.inYBounds(y, view: $0.view)} } private func filterChartPoints(filter: (ViewWithChartPoint) -> Bool) -> [T] { return self.viewsWithChartPoints.reduce([]) {arr, viewWithChartPoint in if filter(viewWithChartPoint) { return arr + [viewWithChartPoint.chartPointModel.chartPoint] } else { return arr } } } private func inXBounds(x: CGFloat, view: UIView) -> Bool { return (x > view.frame.origin.x) && (x < (view.frame.origin.x + view.frame.width)) } private func inYBounds(y: CGFloat, view: UIView) -> Bool { return (y > view.frame.origin.y) && (y < (view.frame.origin.y + view.frame.height)) } }
e191843273f14ca68eeaab09f1d04566
41.091837
250
0.63297
false
false
false
false
Flinesoft/HandyUIKit
refs/heads/main
Frameworks/HandyUIKit/Extensions/NSAttributedStringExt.swift
mit
1
// Copyright © 2017 Flinesoft. All rights reserved. import UIKit private let scriptedTextSizeRatio: CGFloat = 0.618 extension NSAttributedString { /// Calculates and returns the height needed to fit the text into a width-constrained rect. /// /// - Parameters: /// - fixedWidth: The fixed width of the rect. /// - font: The font of the text to calculate for. /// - Returns: The height needed to fit the text into a width-constrained rect. public func height(forFixedWidth fixedWidth: CGFloat, font: UIFont) -> CGFloat { let constraintSize = CGSize(width: fixedWidth, height: .greatestFiniteMagnitude) return rect(for: constraintSize, font: font).height } /// Calculates and returns the width needed to fit the text into a height-constrained rect. /// /// - Parameters: /// - fixedHeight: The fixed height of the rect. /// - font: The font of the text to calculate for. /// - Returns: The width needed to fit the text into a height-constrained rect. public func width(forFixedHeight fixedHeight: CGFloat, font: UIFont) -> CGFloat { let constraintSize = CGSize(width: .greatestFiniteMagnitude, height: fixedHeight) return rect(for: constraintSize, font: font).width } private func rect(for constraintSize: CGSize, font: UIFont) -> CGRect { let copy = mutableCopy() as! NSMutableAttributedString // swiftlint:disable:this force_cast copy.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: length)) return copy.boundingRect(with: constraintSize, options: .usesLineFragmentOrigin, context: nil) } /// Superscripts substrings of structure ^{substring} and subscripts substrings of structure _{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// - applyFont: Specify if the font shall be applied to the resulting attributed string. Defaults to `true`. /// /// - Returns: The resulting attributed string with superscripted and subscripted substrings. public func superAndSubscripted(font: UIFont, applyFont: Bool = true) -> NSAttributedString { subscripted(font: font).superscripted(font: font, applyFont: false) } /// Superscripts substrings of structure ^{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// - applyFont: Specify if the font shall be applied to the resulting attributed string. Defaults to `true`. /// /// - Returns: The resulting attributed string with superscripted substrings. public func superscripted(font: UIFont, applyFont: Bool = true) -> NSAttributedString { scripted( font: font, regex: try! NSRegularExpression(pattern: "\\^\\{([^\\}]*)\\}"), // swiftlint:disable:this force_try captureBaselineOffset: font.pointSize * (1.0 - scriptedTextSizeRatio), applyFont: applyFont ) } /// Subscripts substrings of structure _{substring}. /// /// - Parameters: /// - font: The base font size for the resulting attributed string. /// - applyFont: Specify if the font shall be applied to the resulting attributed string. Defaults to `true`. /// /// - Returns: The resulting attributed string with subscripted substrings. public func subscripted(font: UIFont, applyFont: Bool = true) -> NSAttributedString { scripted( font: font, regex: try! NSRegularExpression(pattern: "\\_\\{([^\\}]*)\\}"), // swiftlint:disable:this force_try captureBaselineOffset: font.pointSize * -(scriptedTextSizeRatio / 5), applyFont: applyFont ) } // swiftlint:disable force_cast private func scripted(font: UIFont, regex: NSRegularExpression, captureBaselineOffset: CGFloat, applyFont: Bool = true) -> NSAttributedString { // apply font to entire string let unprocessedString = self.mutableCopy() as! NSMutableAttributedString if applyFont { unprocessedString.addAttribute(.font, value: font, range: NSRange(location: 0, length: unprocessedString.length)) } // start reading in the string part by part let attributedString = NSMutableAttributedString() while let match = regex.firstMatch( in: unprocessedString.string, options: .reportCompletion, range: NSRange(location: 0, length: unprocessedString.length) ) { // add substring before match let substringBeforeMatch = unprocessedString.attributedSubstring(from: NSRange(location: 0, length: match.range.location)) attributedString.append(substringBeforeMatch) // add match with subscripted style let capturedSubstring = unprocessedString.attributedSubstring(from: match.range(at: 1)).mutableCopy() as! NSMutableAttributedString let captureFullRange = NSRange(location: 0, length: capturedSubstring.length) capturedSubstring.addAttribute(.font, value: font.withSize(font.pointSize * scriptedTextSizeRatio), range: captureFullRange) capturedSubstring.addAttribute(.baselineOffset, value: captureBaselineOffset, range: captureFullRange) attributedString.append(capturedSubstring) // strip off the processed part unprocessedString.deleteCharacters(in: NSRange(location: 0, length: match.range.location + match.range.length)) } // add substring after last match attributedString.append(unprocessedString) return attributedString.copy() as! NSAttributedString } // swiftlint:enable force_cast }
71bebfba310567121e212212c2d688d4
48.324786
147
0.678565
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureKYC/Sources/FeatureKYCUI/CountrySelector/KYCCountrySelectionPresenter.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import RxSwift import ToolKit /// Protocol definition for the country selection view during the KYC flow protocol KYCCountrySelectionView: AnyObject { /// Method invoked once the user selects a native KYC-supported country func continueKycFlow(country: CountryData) /// Method invoked when the user selects a country that is not supported /// for exchanging crypto-to-crypto func showExchangeNotAvailable(country: CountryData) } class KYCCountrySelectionPresenter { // MARK: - Private Properties private let interactor: KYCCountrySelectionInteractor private weak var view: KYCCountrySelectionView? private let disposables = CompositeDisposable() // MARK: - Initializer init( view: KYCCountrySelectionView, interactor: KYCCountrySelectionInteractor = KYCCountrySelectionInteractor() ) { self.view = view self.interactor = interactor } deinit { disposables.dispose() } // MARK: - Public Methods func selected(country: CountryData) { // Notify server of user's selection let interactorDisposable = interactor.selected(country: country) _ = disposables.insert(interactorDisposable) // There are 3 scenarios once a user picks a country: // 1. if the country is supported by our native KYC OR if the country has states, proceed if country.isKycSupported || country.states.count != 0 { Logger.shared.info("Selected country is supported by our native KYC.") view?.continueKycFlow(country: country) return } view?.showExchangeNotAvailable(country: country) } }
6ed9baca705268b52d44dc9c9ee22c17
29.362069
97
0.696763
false
false
false
false
StachkaConf/ios-app
refs/heads/develop
StachkaIOS/StachkaIOS/Classes/Application/Coordinator/ApplicationCoordinatorImplementation.swift
mit
1
// // ApplicationCoordinatorImplementation.swift // StachkaIOS // // Created by m.rakhmanov on 25.03.17. // Copyright © 2017 m.rakhmanov. All rights reserved. // import UIKit import RectangleDissolve import RxSwift import RxCocoa class ApplicationCoordinatorImplementation: ApplicationCoordinator, CoordinatorWithDependencies { enum Constants { static let animationDelay = 0.5 static let animatorConfiguration = RectangleDissolveAnimatorConfiguration(rectanglesVertical: 14, rectanglesHorizontal: 8, batchSize: 10, fadeAnimationDuration: 0.5, tempo: 1000.0) } private weak var window: UIWindow? private var tabBarController: UITabBarController private var onboardingModuleAssembly: ModuleAssembly private var initialUserStoriesCoordinatorsFactory: InitialUserStoriesCoordinatorsFactory var childCoordinators: [Coordinator] = [] private let disposeBag = DisposeBag() init(window: UIWindow?, rootTabBarController: UITabBarController, onboardingModuleAssembly: ModuleAssembly, initialUserStoriesCoordinatorsFactory: InitialUserStoriesCoordinatorsFactory) { self.window = window self.tabBarController = rootTabBarController self.onboardingModuleAssembly = onboardingModuleAssembly self.initialUserStoriesCoordinatorsFactory = initialUserStoriesCoordinatorsFactory } func start() { let talksNavigationController = UINavigationController() //tabBarController.embed(viewController: talksNavigationController) let talksCoordinator = initialUserStoriesCoordinatorsFactory.talksCoordinator(rootNavigationController: talksNavigationController) add(coordinator: talksCoordinator) talksCoordinator.start() // let favouritesNavigationController = UINavigationController() // tabBarController.embed(viewController: favouritesNavigationController) // let favouritesCoordinator = initialUserStoriesCoordinatorsFactory.favouritesCoordinator(rootNavigationController: favouritesNavigationController) // add(coordinator: favouritesCoordinator) // favouritesCoordinator.start() createDismissOnboarding(andShow: talksNavigationController) .subscribe() .disposed(by: disposeBag) } // MARK: Private private func createDismissOnboarding(andShow viewController: UIViewController) -> Observable<Void> { return Observable.create { [weak self] observer in guard let strongSelf = self else { observer.onCompleted() return Disposables.create() } let onboarding = strongSelf.onboardingModuleAssembly.module() let animator = RectangleDissolveAnimator(configuration: Constants.animatorConfiguration) strongSelf.window?.rootViewController = onboarding strongSelf.window?.makeKeyAndVisible() DispatchQueue.main.asyncAfter(deadline: .now() + Constants.animationDelay) { viewController.transitioningDelegate = animator onboarding.present(viewController, animated: true, completion: { observer.onCompleted() }) } return Disposables.create() } } }
28c4ed12820f678c59b5cbd2eaffa7ec
41.104651
155
0.657829
false
false
false
false
aleph7/BrainCore
refs/heads/master
Source/Evaluator.swift
mit
1
// Copyright © 2016 Venture Media Labs. All rights reserved. // // This file is part of BrainCore. The full BrainCore copyright notice, // including terms governing use, modification, and redistribution, is // contained in the file LICENSE at the root of the source code distribution // tree. import Foundation import Metal /// A `Runner` that performs feed-forward passes on a network. /// /// `Evaluator` is optimized for running a single pass at a time (batch size of one). It maximizes GPU parallelism by enqueuing sequential runs a few at a time. /// /// - SeeAlso: `Runner`, `Trainer` open class Evaluator: Runner { /// The maximum number of instances to enqueue to the GPU at a time. let instanceCount = 3 var instances = [Instance]() var nextInstanceIndex = 0 var inflightSemaphore: DispatchSemaphore var queue: DispatchQueue /// Creates an `Evaluator` for the given network definition. /// /// - Parameter net: network definition. /// - Parameter device: Metal device to use when running. public init(net: Net, device: MTLDevice) throws { queue = DispatchQueue(label: "BrainCore.Evaluator", attributes: []) inflightSemaphore = DispatchSemaphore(value: instanceCount) try super.init(net: net, device: device, batchSize: 1, backwards: false) for _ in 0..<instanceCount { let forwardInstance = Instance(buffers: net.buffers, device: device, batchSize: 1) instances.append(forwardInstance) } } /// Executes a particular `Invocation` on the GPU. /// /// This is used to perform operations on the GPU. Usually you would not perform invocations directly, but this can be used to perform updates to the buffers outside of a feed-forward pass. /// /// - Parameter invocations: array of invocations to execute. /// - Parameter completion: closure to execute when the invocation completes. open func call(_ invocations: [Invocation], completion: (() -> Void)?) { queue.sync { self.callInQueue(invocations, completion: completion) } } func callInQueue(_ invocations: [Invocation], completion: (() -> Void)?) { let buffer = commandQueue.makeCommandBuffer() for invocation in invocations { try! Runner.encode(invocation: invocation, commandBuffer: buffer) } buffer.addCompletedHandler() { commandBuffer in self.queue.async { completion?() } } buffer.commit() } /// Performs a feed-forward pass on the network. /// /// - Important: Always call this method from the same serial queue. /// /// - Parameter completion: closure to execute when the evaluation finishes. It gets passed a snapshot of the network results. open func evaluate(_ completion: @escaping ((Snapshot) -> Void)) { _ = inflightSemaphore.wait(timeout: DispatchTime.distantFuture) let instance = instances[nextInstanceIndex] instance.reset() nextInstanceIndex = (nextInstanceIndex + 1) % instanceCount commandQueue.insertDebugCaptureBoundary() // Collect all data for n in net.dataNodes.values { let dataLayer = n.layer as! DataLayer if let netBuffer = n.outputBuffer { guard let buffer = instance.buffers[netBuffer.id] else { fatalError("Output buffer for \(dataLayer.name) not found.") } fillBuffer(buffer, start: n.outputRange.lowerBound, withElements: dataLayer.nextBatch(1)) } instance.closeNode(n) instance.openOutputsOf(n) instance.finishNode(n) } queue.sync { self.processNodesOfInstance(instance, completion: completion) } } func processNodesOfInstance(_ instance: Instance, completion: @escaping ((Snapshot) -> Void)) { while !instance.openNodes.isEmpty { let node = instance.openNodes.popLast()! if instance.isClosed(node) { continue } guard let forwardLayer = node.layer as? ForwardLayer else { continue } guard let _ = node.inputBuffer, let _ = node.outputBuffer else { preconditionFailure("Layer '\(node.layer.name)' is missing a buffer") } let buffer = commandQueue.makeCommandBuffer() for invocation in forwardLayer.forwardInvocations { for buffer in invocation.buffers { guard let netBuffer = buffer.netBuffer else { continue } if let metalBuffer = instance.buffers[netBuffer.id] { buffer.metalBuffer = metalBuffer } } try! Runner.encode(invocation: invocation, commandBuffer: buffer) } buffer.addCompletedHandler() { commandBuffer in self.queue.async { instance.finishNode(node) if instance.isFinished() { self.finishInstance(instance, completion: completion) } } } buffer.commit() instance.closeNode(node) instance.openOutputsOf(node) } } func finishInstance(_ instance: Instance, completion: ((Snapshot) -> Void)) { for n in net.sinkNodes.values { let sinkLayer = n.layer as! SinkLayer if let netBuffer = n.inputBuffer { guard let buffer = instance.buffers[netBuffer.id] else { fatalError("Layer '\(n.layer.name)'s input buffer was not found.") } sinkLayer.consume(valueArrayFromBuffer(buffer, start: n.inputRange.lowerBound)) } } completion(Snapshot(net: self.net, forwardBuffers: instance.buffers)) self.inflightSemaphore.signal() } }
57e32fd6303b728d8391cc90a5fa0c1e
37.877419
193
0.609525
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Geometry/Clip geometry/ClipGeometryViewController.swift
apache-2.0
1
// Copyright 2018 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 ClipGeometryViewController: UIViewController { // MARK: Storyboard views /// The map view managed by the view controller. @IBOutlet var mapView: AGSMapView! { didSet { // Create a map with a topographic basemap. mapView.map = AGSMap(basemapStyle: .arcGISTopographic) // Add the graphics overlays to the map view. mapView.graphicsOverlays.addObjects(from: [coloradoGraphicsOverlay, envelopesGraphicsOverlay, clippedGraphicsOverlay]) // Set the viewpoint to the extent of the Colorado geometry. mapView.setViewpointGeometry(coloradoGraphic.geometry!, padding: 100) } } // MARK: Instance properties /// A Boolean value indicating whether the geometries are clipped. private var geometriesAreClipped = false /// The unclipped graphic of Colorado. private var coloradoGraphic: AGSGraphic { coloradoGraphicsOverlay.graphics.firstObject as! AGSGraphic } /// The overlay for displaying the graphic of Colorado. private let coloradoGraphicsOverlay: AGSGraphicsOverlay = { // An envelope approximating the boundary of Colorado. let coloradoGeometry = AGSEnvelope( xMin: -11362327.128340, yMin: 5012861.290274, xMax: -12138232.018408, yMax: 4441198.773776, spatialReference: .webMercator() ) // A semi-transparent blue color for the fill. let fillColor = UIColor.blue.withAlphaComponent(0.2) // The fill symbol for displaying Colorado. let fillSymbol = AGSSimpleFillSymbol( style: .solid, color: fillColor, outline: AGSSimpleLineSymbol(style: .solid, color: .blue, width: 2) ) // Create a graphic from the geometry and symbol representing Colorado. let coloradoGraphic = AGSGraphic(geometry: coloradoGeometry, symbol: fillSymbol) // Create a graphics overlay. let coloradoGraphicsOverlay = AGSGraphicsOverlay() // Add the Colorado graphic to its overlay. coloradoGraphicsOverlay.graphics.add(coloradoGraphic) return coloradoGraphicsOverlay }() /// The graphics overlay containing clipped graphics. private let clippedGraphicsOverlay = AGSGraphicsOverlay() /// The overlay for displaying the other envelopes. private let envelopesGraphicsOverlay: AGSGraphicsOverlay = { // An envelope outside Colorado. let outsideEnvelope = AGSEnvelope( xMin: -11858344.321294, yMin: 5147942.225174, xMax: -12201990.219681, yMax: 5297071.577304, spatialReference: .webMercator() ) // An envelope intersecting Colorado. let intersectingEnvelope = AGSEnvelope( xMin: -11962086.479298, yMin: 4566553.881363, xMax: -12260345.183558, yMax: 4332053.378376, spatialReference: .webMercator() ) // An envelope inside Colorado. let containedEnvelope = AGSEnvelope( xMin: -11655182.595204, yMin: 4741618.772994, xMax: -11431488.567009, yMax: 4593570.068343, spatialReference: .webMercator() ) // A dotted red outline symbol. let redOutline = AGSSimpleLineSymbol(style: .dot, color: .red, width: 3) // The envelopes in the order we want to display them. let envelopes = [outsideEnvelope, intersectingEnvelope, containedEnvelope] // The graphics for the envelopes with the red outline symbol. let graphics = envelopes.map { AGSGraphic(geometry: $0, symbol: redOutline) } let envelopesOverlay = AGSGraphicsOverlay() // Add the graphics to the overlay. envelopesOverlay.graphics.addObjects(from: graphics) return envelopesOverlay }() // MARK: Actions /// Clip geometries and add resulting graphics. private func clipGeometries() { // Hides the Colorado graphic. coloradoGraphic.isVisible = false let coloradoGeometry = coloradoGraphic.geometry! let coloradoSymbol = coloradoGraphic.symbol! // Clip Colorado's geometry to each envelope. let clippedGraphics: [AGSGraphic] = envelopesGraphicsOverlay.graphics.map { graphic in let envelope = (graphic as! AGSGraphic).geometry as! AGSEnvelope // Use the geometry engine to create a new geometry for the area of // Colorado that overlaps the given envelope. let clippedGeometry = AGSGeometryEngine.clipGeometry(coloradoGeometry, with: envelope) // Create and return the clipped graphic from the clipped geometry // if there is an overlap. return AGSGraphic(geometry: clippedGeometry, symbol: coloradoSymbol) } // Add the clipped graphics. clippedGraphicsOverlay.graphics.addObjects(from: clippedGraphics) } /// Remove all clipped graphics. private func reset() { clippedGraphicsOverlay.graphics.removeAllObjects() coloradoGraphic.isVisible = true } @IBAction func clipGeometry(_ sender: UIBarButtonItem) { geometriesAreClipped ? reset() : clipGeometries() geometriesAreClipped.toggle() // Set button title based on whether the geometries are clipped. sender.title = geometriesAreClipped ? "Reset" : "Clip" } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ClipGeometryViewController"] } }
825dc7619451d1a1d257322c9b1d6f16
38.648485
130
0.650413
false
false
false
false
Keanyuan/SwiftContact
refs/heads/master
SwiftContent/SwiftContent/Classes/Common/ALMacro.swift
mit
1
// // ALMacro.swift // ExpressSystem // // Created by Kean on 2017/5/31. // Copyright © 2017年 Kean. All rights reserved. // import UIKit /// 第一次启动 let YMFirstLaunch = "firstLaunch" let LOGIN_STATUS_KEY = "Login_Status_Key" /// 屏幕的宽 let SCREENW = UIScreen.main.bounds.size.width /// 屏幕的高 let SCREENH = UIScreen.main.bounds.size.height /// iPhone 5 let isIPhone5 = SCREENH == 568 ? true : false /// iPhone 6 let isIPhone6 = SCREENH == 667 ? true : false /// iPhone 6P let isIPhone6P = SCREENH == 736 ? true : false let UIRate = (UIScreen.main.bounds.size.width/375) /// prin输出 /// /// - Parameters: /// - message: 输出内容 /// - logError: 是否错误 default is false /// - file: 输出文件位置 /// - method: 对应方法 /// - line: 所在行 /* #file String 所在的文件名 #line Int 所在的行数 #column Int 所在的列数 #function String 所在的声明的名字 */ func printLog<T>(_ message: T, _ logError: Bool = false, file: String = #file, method: String = #function, line: Int = #line) { if logError { print("\((file as NSString).lastPathComponent)\(method) [Line \(line)]: \(message)") } else { #if DEBUG print("\((file as NSString).lastPathComponent)\(method) [Line \(line)]: \(message)") #endif } } /// 利用泛型获取随机数组中的一个元素 /// /// - Parameter array: 传入的数组 /// - Returns: 返回数组中一个随机元素 func randomElementFromArray<T>(_ array:Array<T>) -> T { let index: Int = Int(arc4random_uniform(UInt32(array.count))) return array[index] }
0f2f8d67f77fb165581c31fdab609b22
20.442857
96
0.61026
false
false
false
false
kNeerajPro/PlayPauseAnimation
refs/heads/master
PlayPauseAnimation/PlayPauseAnimation/VIews/Layers/PauseLayer.swift
mit
1
// // PauseLayer.swift // SignatureAnimation // // Created by Neeraj Kumar on 23/02/15. // Copyright (c) 2015 Neeraj Kumar. All rights reserved. // import UIKit class PauseLayer: CAShapeLayer { override var bounds : CGRect { didSet { path = self.shapeForBounds(bounds, width: bounds.size.width/3.0).CGPath } } func shapeForBounds(rect: CGRect, width:CGFloat) -> UIBezierPath { let shapeWidth = width let point0 = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)) let point1 = CGPointMake(CGRectGetMinX(rect), CGRectGetMaxY(rect)) let point2 = CGPointMake(CGRectGetMinX(rect) + shapeWidth, CGRectGetMaxY(rect)) let point3 = CGPointMake(CGRectGetMinX(rect) + shapeWidth, CGRectGetMinY(rect)) let point4 = CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)) let point5 = CGPointMake(CGRectGetMinX(rect) + shapeWidth + 15.0, CGRectGetMaxY(rect)) let point6 = CGPointMake(CGRectGetMinX(rect) + shapeWidth + 15.0, CGRectGetMinY(rect)) let point7 = CGPointMake(CGRectGetMinX(rect) + shapeWidth + 15.0 + shapeWidth, CGRectGetMinY(rect)) let point8 = CGPointMake(CGRectGetMinX(rect) + shapeWidth + 15.0 + shapeWidth, CGRectGetMaxY(rect)) let customPath = UIBezierPath() customPath.moveToPoint(point0) customPath.addLineToPoint(point1) customPath.addLineToPoint(point2) customPath.addLineToPoint(point3) customPath.addLineToPoint(point4) customPath.moveToPoint(point5) customPath.addLineToPoint(point6) customPath.addLineToPoint(point7) customPath.addLineToPoint(point8) return customPath } override func addAnimation(anim: CAAnimation!, forKey key: String!) { super.addAnimation(anim, forKey: key) if (anim.isKindOfClass(CABasicAnimation.self)) { let basicAnimation = anim as CABasicAnimation if (basicAnimation.keyPath == "bounds.size") { var pathAnimation = basicAnimation.mutableCopy() as CABasicAnimation pathAnimation.keyPath = "path" pathAnimation.fromValue = self.path pathAnimation.toValue = self.shapeForBounds(self.bounds, width: self.bounds.size.width/3.0).CGPath self.removeAnimationForKey("path") self.addAnimation(pathAnimation,forKey: "path") } } } }
b4e20f0f328d0f3605fef622dcd9b4c0
35.869565
114
0.642689
false
false
false
false
blindsey/Swift-BoxOffice
refs/heads/master
BoxOffice/MovieTableViewCell.swift
mit
1
// // BoxOfficeTableViewCell.swift // BoxOffice // // Created by Ben Lindsey on 7/19/14. // Copyright (c) 2014 Ben Lindsey. All rights reserved. // import UIKit class MovieTableViewCell : UITableViewCell { override func layoutSubviews() { super.layoutSubviews() self.imageView.frame.origin = CGPoint(x: 10.0, y: 10.0) self.textLabel.frame.origin = CGPoint(x: 70.0, y: 10.0) self.textLabel.frame.size.width = 250.0 self.detailTextLabel.frame.origin.x = 70.0 self.detailTextLabel.frame.size.width = 250.0 self.detailTextLabel.numberOfLines = 3 self.detailTextLabel.sizeToFit() } }
1de59ed9673fd1155e2217833de4f24d
25.4
63
0.663636
false
false
false
false
Adorkable/Eunomia
refs/heads/master
Source/Core/UtilityExtensions/CoreData/NSManagedObject+Utility.swift
mit
1
// // NSManagedObject+Utility.swift // Eunomia // // Created by Ian Grossberg on 11/26/15. // Copyright © 2015 Adorkable. All rights reserved. // import Foundation import CoreData // MARK: - Creation extension NSManagedObject { public class var entityName : String { // Assumes we've named our CoreData object the same as the Class object let fullClassName: String = NSStringFromClass(object_getClass(self)!) let classNameComponents: [String] = fullClassName.split { $0 == "." }.map { String($0) } return classNameComponents.last! } public class func entityDescription(_ inContext: NSManagedObjectContext) -> NSEntityDescription? { return NSEntityDescription.entity(forEntityName: self.entityName, in: inContext) } public class func insertNewObjectInContext(_ context: NSManagedObjectContext) -> NSManagedObject { return NSEntityDescription.insertNewObject(forEntityName: self.entityName, into: context) } } // MARK: - Sort Descriptors extension NSManagedObject { public class func defaultSortDescriptors() -> [NSSortDescriptor] { return [NSSortDescriptor]() } public class func guaranteeSortDescriptors(_ potentialSortDescriptors : [NSSortDescriptor]?) -> [NSSortDescriptor] { return guarantee(potentialSortDescriptors, fallback: self.defaultSortDescriptors()) } } // MARK: - Fetch Request extension NSManagedObject { public class func defaultFetchRequest(_ sortDescriptors : [NSSortDescriptor]? = nil) -> NSFetchRequest<NSFetchRequestResult> { let result = NSFetchRequest<NSFetchRequestResult>(entityName: self.entityName) result.sortDescriptors = guarantee(sortDescriptors, fallback: self.defaultSortDescriptors()) return result } public class func guaranteeFetchRequest(_ potentialFetchRequest : NSFetchRequest<NSFetchRequestResult>?) -> NSFetchRequest<NSFetchRequestResult> { return guarantee(potentialFetchRequest, fallback: self.defaultFetchRequest()) } } // MARK: - Fetched Results Controller extension NSManagedObject { public class func defaultFetchedResultsController(_ fetchRequest : NSFetchRequest<NSFetchRequestResult>? = nil, predicate : NSPredicate? = nil, sortDescriptors : [NSSortDescriptor]? = nil, inContext context: NSManagedObjectContext) -> NSFetchedResultsController<NSFetchRequestResult> { let useFetchRequest = guarantee(fetchRequest, fallback: self.defaultFetchRequest()) if let predicate = predicate { useFetchRequest.predicate = predicate } if let sortDescriptors = sortDescriptors { useFetchRequest.sortDescriptors = sortDescriptors } return NSFetchedResultsController(fetchRequest: useFetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) } } // MARK: - Save extension NSManagedObject { public func saveOrLogError(_ logContext : String) -> Bool { var result : Bool if let context = self.managedObjectContext { result = context.saveOrLogError(logContext) } else { // TODO: throw result = false } return result } } // MARK: - Delete extension NSManagedObject { public func deleteObject() -> Bool { var result : Bool if let context = self.managedObjectContext { context.delete(self) result = true } else { // TODO: throw result = false } return result } public func deleteAndSaveOrLogError(_ logContext : String) -> Bool { var result : Bool if let context = self.managedObjectContext { // TODO: let user know if delete or save failed result = self.deleteObject() if result == true { result = context.saveOrLogError(logContext) } } else { // TODO: throw result = false } return result } }
90599390c6845e41b2697ad070036337
29.52518
289
0.639642
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/develop
37--Resurgence/VenuesMenuQuadrat/Pods/QuadratTouch/Source/Shared/Endpoints/Events.swift
bsd-2-clause
4
// // Events.swift // Quadrat // // Created by Constantine Fry on 06/11/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public class Events: Endpoint { override var endpoint: String { return "events" } /** https://developer.foursquare.com/docs/events/events */ public func get(eventId: String, completionHandler: ResponseClosure? = nil) -> Task { return self.getWithPath(eventId, parameters: nil, completionHandler: completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/events/categories */ public func categories(completionHandler: ResponseClosure? = nil) -> Task { let path = "categories" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/events/search */ public func search(domain: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "search" var allParameters = [Parameter.domain: domain] allParameters += parameters return self.getWithPath(path, parameters: allParameters, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/events/add */ public func add(parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "add" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } }
8619f784586534411094da8128ed1e15
33.977778
116
0.672173
false
false
false
false
airbnb/lottie-ios
refs/heads/master
Sources/Private/Utility/Extensions/MathKit.swift
apache-2.0
3
// // MathKit.swift // UIToolBox // // Created by Brandon Withrow on 10/10/18. // // From https://github.com/buba447/UIToolBox import CoreGraphics import Foundation extension Int { var cgFloat: CGFloat { CGFloat(self) } } extension Double { var cgFloat: CGFloat { CGFloat(self) } } // MARK: - CGFloat + Interpolatable extension CGFloat { func remap(fromLow: CGFloat, fromHigh: CGFloat, toLow: CGFloat, toHigh: CGFloat) -> CGFloat { guard (fromHigh - fromLow) != 0 else { // Would produce NAN return 0 } return toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) } /// Returns a value that is clamped between the two numbers /// /// 1. The order of arguments does not matter. func clamp(_ a: CGFloat, _ b: CGFloat) -> CGFloat { CGFloat(Double(self).clamp(Double(a), Double(b))) } /// Returns the difference between the receiver and the given number. /// - Parameter absolute: If *true* (Default) the returned value will always be positive. func diff(_ a: CGFloat, absolute: Bool = true) -> CGFloat { absolute ? abs(a - self) : a - self } func toRadians() -> CGFloat { self * .pi / 180 } func toDegrees() -> CGFloat { self * 180 / .pi } } // MARK: - Double extension Double { func remap(fromLow: Double, fromHigh: Double, toLow: Double, toHigh: Double) -> Double { toLow + (self - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) } /// Returns a value that is clamped between the two numbers /// /// 1. The order of arguments does not matter. func clamp(_ a: Double, _ b: Double) -> Double { let minValue = a <= b ? a : b let maxValue = a <= b ? b : a return max(min(self, maxValue), minValue) } } extension CGRect { // MARK: Lifecycle /// Initializes a new CGRect with a center point and size. init(center: CGPoint, size: CGSize) { self.init( x: center.x - (size.width * 0.5), y: center.y - (size.height * 0.5), width: size.width, height: size.height) } // MARK: Internal /// Returns the total area of the rect. var area: CGFloat { width * height } /// The center point of the rect. Settable. var center: CGPoint { get { CGPoint(x: midX, y: midY) } set { origin = CGPoint( x: newValue.x - (size.width * 0.5), y: newValue.y - (size.height * 0.5)) } } /// The top left point of the rect. Settable. var topLeft: CGPoint { get { CGPoint(x: minX, y: minY) } set { origin = CGPoint( x: newValue.x, y: newValue.y) } } /// The bottom left point of the rect. Settable. var bottomLeft: CGPoint { get { CGPoint(x: minX, y: maxY) } set { origin = CGPoint( x: newValue.x, y: newValue.y - size.height) } } /// The top right point of the rect. Settable. var topRight: CGPoint { get { CGPoint(x: maxX, y: minY) } set { origin = CGPoint( x: newValue.x - size.width, y: newValue.y) } } /// The bottom right point of the rect. Settable. var bottomRight: CGPoint { get { CGPoint(x: maxX, y: maxY) } set { origin = CGPoint( x: newValue.x - size.width, y: newValue.y - size.height) } } } extension CGSize { /// Operator convenience to add sizes with + static func +(left: CGSize, right: CGSize) -> CGSize { left.add(right) } /// Operator convenience to subtract sizes with - static func -(left: CGSize, right: CGSize) -> CGSize { left.subtract(right) } /// Operator convenience to multiply sizes with * static func *(left: CGSize, right: CGFloat) -> CGSize { CGSize(width: left.width * right, height: left.height * right) } /// Returns the scale float that will fit the receive inside of the given size. func scaleThatFits(_ size: CGSize) -> CGFloat { CGFloat.minimum(width / size.width, height / size.height) } /// Adds receiver size to give size. func add(_ size: CGSize) -> CGSize { CGSize(width: width + size.width, height: height + size.height) } /// Subtracts given size from receiver size. func subtract(_ size: CGSize) -> CGSize { CGSize(width: width - size.width, height: height - size.height) } /// Multiplies receiver size by the given size. func multiply(_ size: CGSize) -> CGSize { CGSize(width: width * size.width, height: height * size.height) } } // MARK: - CGLine /// A struct that defines a line segment with two CGPoints struct CGLine { // MARK: Lifecycle /// Initializes a line segment with start and end points init(start: CGPoint, end: CGPoint) { self.start = start self.end = end } // MARK: Internal /// The Start of the line segment. var start: CGPoint /// The End of the line segment. var end: CGPoint /// The length of the line segment. var length: CGFloat { end.distanceTo(start) } /// Returns a line segment that is normalized to a length of 1 func normalize() -> CGLine { let len = length guard len > 0 else { return self } let relativeEnd = end - start let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len) let absoluteVector = relativeVector + start return CGLine(start: start, end: absoluteVector) } /// Trims a line segment to the given length func trimmedToLength(_ toLength: CGFloat) -> CGLine { let len = length guard len > 0 else { return self } let relativeEnd = end - start let relativeVector = CGPoint(x: relativeEnd.x / len, y: relativeEnd.y / len) let sizedVector = CGPoint(x: relativeVector.x * toLength, y: relativeVector.y * toLength) let absoluteVector = sizedVector + start return CGLine(start: start, end: absoluteVector) } /// Flips a line vertically and horizontally from the start point. func flipped() -> CGLine { let relativeEnd = end - start let flippedEnd = CGPoint(x: relativeEnd.x * -1, y: relativeEnd.y * -1) return CGLine(start: start, end: flippedEnd + start) } /// Move the line to the new start point. func transpose(_ toPoint: CGPoint) -> CGLine { let diff = toPoint - start let newEnd = end + diff return CGLine(start: toPoint, end: newEnd) } } infix operator +| infix operator +- extension CGPoint { /// Returns the length between the receiver and *CGPoint.zero* var vectorLength: CGFloat { distanceTo(.zero) } var isZero: Bool { x == 0 && y == 0 } /// Operator convenience to divide points with / static func / (lhs: CGPoint, rhs: CGFloat) -> CGPoint { CGPoint(x: lhs.x / CGFloat(rhs), y: lhs.y / CGFloat(rhs)) } /// Operator convenience to multiply points with * static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint { CGPoint(x: lhs.x * CGFloat(rhs), y: lhs.y * CGFloat(rhs)) } /// Operator convenience to add points with + static func +(left: CGPoint, right: CGPoint) -> CGPoint { left.add(right) } /// Operator convenience to subtract points with - static func -(left: CGPoint, right: CGPoint) -> CGPoint { left.subtract(right) } static func +|(left: CGPoint, right: CGFloat) -> CGPoint { CGPoint(x: left.x, y: left.y + right) } static func +-(left: CGPoint, right: CGFloat) -> CGPoint { CGPoint(x: left.x + right, y: left.y) } /// Returns the distance between the receiver and the given point. func distanceTo(_ a: CGPoint) -> CGFloat { let xDist = a.x - x let yDist = a.y - y return CGFloat(sqrt((xDist * xDist) + (yDist * yDist))) } func rounded(decimal: CGFloat) -> CGPoint { CGPoint(x: round(decimal * x) / decimal, y: round(decimal * y) / decimal) } func interpolate( _ to: CGPoint, outTangent: CGPoint, inTangent: CGPoint, amount: CGFloat, maxIterations: Int = 3, samples: Int = 20, accuracy: CGFloat = 1) -> CGPoint { if amount == 0 { return self } if amount == 1 { return to } if colinear(outTangent, inTangent) == true, outTangent.colinear(inTangent, to) == true { return interpolate(to: to, amount: amount) } let step = 1 / CGFloat(samples) var points: [(point: CGPoint, distance: CGFloat)] = [(point: self, distance: 0)] var totalLength: CGFloat = 0 var previousPoint = self var previousAmount = CGFloat(0) var closestPoint = 0 while previousAmount < 1 { previousAmount = previousAmount + step if previousAmount < amount { closestPoint = closestPoint + 1 } let newPoint = pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: previousAmount) let distance = previousPoint.distanceTo(newPoint) totalLength = totalLength + distance points.append((point: newPoint, distance: totalLength)) previousPoint = newPoint } let accurateDistance = amount * totalLength var point = points[closestPoint] var foundPoint = false var pointAmount = CGFloat(closestPoint) * step var nextPointAmount: CGFloat = pointAmount + step var refineIterations = 0 while foundPoint == false { refineIterations = refineIterations + 1 /// First see if the next point is still less than the projected length. let nextPoint = points[closestPoint + 1] if nextPoint.distance < accurateDistance { point = nextPoint closestPoint = closestPoint + 1 pointAmount = CGFloat(closestPoint) * step nextPointAmount = pointAmount + step if closestPoint == points.count { foundPoint = true } continue } if accurateDistance < point.distance { closestPoint = closestPoint - 1 if closestPoint < 0 { foundPoint = true continue } point = points[closestPoint] pointAmount = CGFloat(closestPoint) * step nextPointAmount = pointAmount + step continue } /// Now we are certain the point is the closest point under the distance let pointDiff = nextPoint.distance - point.distance let proposedPointAmount = ((accurateDistance - point.distance) / pointDiff) .remap(fromLow: 0, fromHigh: 1, toLow: pointAmount, toHigh: nextPointAmount) let newPoint = pointOnPath(to, outTangent: outTangent, inTangent: inTangent, amount: proposedPointAmount) let newDistance = point.distance + point.point.distanceTo(newPoint) pointAmount = proposedPointAmount point = (point: newPoint, distance: newDistance) if accurateDistance - newDistance <= accuracy || newDistance - accurateDistance <= accuracy { foundPoint = true } if refineIterations == maxIterations { foundPoint = true } } return point.point } func pointOnPath(_ to: CGPoint, outTangent: CGPoint, inTangent: CGPoint, amount: CGFloat) -> CGPoint { let a = interpolate(to: outTangent, amount: amount) let b = outTangent.interpolate(to: inTangent, amount: amount) let c = inTangent.interpolate(to: to, amount: amount) let d = a.interpolate(to: b, amount: amount) let e = b.interpolate(to: c, amount: amount) let f = d.interpolate(to: e, amount: amount) return f } func colinear(_ a: CGPoint, _ b: CGPoint) -> Bool { let area = x * (a.y - b.y) + a.x * (b.y - y) + b.x * (y - a.y); let accuracy: CGFloat = 0.05 if area < accuracy, area > -accuracy { return true } return false } /// Subtracts the given point from the receiving point. func subtract(_ point: CGPoint) -> CGPoint { CGPoint( x: x - point.x, y: y - point.y) } /// Adds the given point from the receiving point. func add(_ point: CGPoint) -> CGPoint { CGPoint( x: x + point.x, y: y + point.y) } }
3e2d645d6bc8463d3c2361797d7f421c
25.406667
111
0.624169
false
false
false
false
gspd-mobi/rage-ios
refs/heads/master
Sources/Rage/RageResponse.swift
mit
1
import Foundation open class RageResponse { public let request: RageRequest public let data: Data? public let response: URLResponse? public let error: NSError? public let timeMillis: Double public init(request: RageRequest, data: Data?, response: URLResponse?, error: NSError?, timeMillis: Double = 0.0) { self.request = request self.data = data self.response = response self.error = error self.timeMillis = timeMillis } } extension RageResponse { public func statusCode() -> Int? { if let httpResponse = response as? HTTPURLResponse { return httpResponse.statusCode } if let safeError = error { return safeError.code } return nil } public func isSuccess() -> Bool { if let status = statusCode() { return 200 ..< 300 ~= status } return false } }
cd492eb3fb86439afbedcc7387bd7b04
21.772727
60
0.560878
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Generators/Physical Models/Flute/AKFlute.swift
mit
1
// // AKFlute.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// STK Flutee /// /// - Parameters: /// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. /// - amplitude: Amplitude /// public class AKFlute: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKFluteAudioUnit? internal var token: AUParameterObserverToken? private var frequencyParameter: AUParameter? private var amplitudeParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. public var frequency: Double = 110 { willSet { if frequency != newValue { frequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// Amplitude public var amplitude: Double = 0.5 { willSet { if amplitude != newValue { amplitudeParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize the mandolin with defaults override convenience init() { self.init(frequency: 110) } /// Initialize the STK Flute model /// /// - Parameters: /// - frequency: Variable frequency. Values less than the initial frequency will be doubled until it is greater than that. /// - amplitude: Amplitude /// public init( frequency: Double = 440, amplitude: Double = 0.5) { self.frequency = frequency self.amplitude = amplitude var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x666c7574 /*'flut'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKFluteAudioUnit.self, asComponentDescription: description, name: "Local AKFlute", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKFluteAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } frequencyParameter = tree.valueForKey("frequency") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.frequencyParameter!.address { self.frequency = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } } } internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) } /// Trigger the sound with an optional set of parameters /// - frequency: Frequency in Hz /// - amplitude amplitude: Volume /// public func trigger(frequency frequency: Double, amplitude: Double = 1) { self.frequency = frequency self.amplitude = amplitude self.internalAU!.start() self.internalAU!.triggerFrequency(Float(frequency), amplitude: Float(amplitude)) } /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
4c3d96b4b0d3aace24824c94bc335909
30.753425
128
0.624029
false
false
false
false
jmgc/swift
refs/heads/master
test/Parse/switch.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int,Int), y: (Int,Int)) -> Bool { return true } func parseError1(x: Int) { switch func {} // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} expected-error {{expected identifier in function declaration}} expected-error {{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{15-15=do }} } func parseError2(x: Int) { switch x // expected-error {{expected '{' after 'switch' subject expression}} } func parseError3(x: Int) { switch x { case // expected-error {{expected pattern}} expected-error {{expected ':' after 'case'}} } } func parseError4(x: Int) { switch x { case var z where // expected-error {{expected expression for 'where' guard of 'case'}} expected-error {{expected ':' after 'case'}} } } func parseError5(x: Int) { switch x { case let z // expected-error {{expected ':' after 'case'}} expected-warning {{immutable value 'z' was never used}} {{8-13=_}} } } func parseError6(x: Int) { switch x { default // expected-error {{expected ':' after 'default'}} } } var x: Int switch x {} // expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} switch x { case 0: x = 0 // Multiple patterns per case case 1, 2, 3: x = 0 // 'where' guard case _ where x % 2 == 0: x = 1 x = 2 x = 3 case _ where x % 2 == 0, _ where x % 3 == 0: x = 1 case 10, _ where x % 3 == 0: x = 1 case _ where x % 2 == 0, 20: x = 1 case var y where y % 2 == 0: x = y + 1 case _ where 0: // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} x = 0 default: x = 1 } // Multiple cases per case block switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} default: x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: x = 0 case 1: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { case 0: x = 0 default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: ; // expected-error {{';' statements are not allowed}} {{3-5=}} case 1: x = 0 } switch x { x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} default: x = 0 case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case 1: x = 0 } switch x { default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} } switch x { // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} x = 1 // expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} x = 2 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} case 0: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { default: // expected-error{{'default' label in a 'switch' should have at least one executable statement}} {{9-9= break}} default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} case 1: x = 0 } switch x { // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} case 0: x = 0 case 1: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{8-8= break}} } case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} var y = 0 default: // expected-error{{'default' label can only appear inside a 'switch' statement}} var z = 1 fallthrough // expected-error{{'fallthrough' is only allowed inside a switch}} switch x { case 0: fallthrough case 1: fallthrough default: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } // Fallthrough can transfer control anywhere within a case and can appear // multiple times in the same case. switch x { case 0: if true { fallthrough } if false { fallthrough } x += 1 default: x += 1 } // Cases cannot contain 'var' bindings if there are multiple matching patterns // attached to a block. They may however contain other non-binding patterns. var t = (1, 2) switch t { case (var a, 2), (1, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (_, 2), (var a, _): // expected-error {{'a' must be bound in every pattern}} () case (var a, 2), (1, var b): // expected-error {{'a' must be bound in every pattern}} expected-error {{'b' must be bound in every pattern}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, _): () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} () case (var a, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} case (1, var b): // expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} () case (1, let b): // let bindings expected-warning {{immutable value 'b' was never used; consider replacing with '_' or removing it}} () case (_, 2), (let a, _): // expected-error {{'a' must be bound in every pattern}} expected-warning {{case is already handled by previous patterns; consider removing it}} () // OK case (_, 2), (1, _): () case (_, var a), (_, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} // expected-warning@-2 {{case is already handled by previous patterns; consider removing it}} () case (var a, var b), (var b, var a): // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}} expected-warning {{variable 'b' was never used; consider replacing with '_' or removing it}} // expected-warning@-1 {{case is already handled by previous patterns; consider removing it}} // expected-warning@-2 {{case is already handled by previous patterns; consider removing it}} () case (_, 2): // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} case (1, _): () } func patternVarUsedInAnotherPattern(x: Int) { switch x { case let a, // expected-error {{'a' must be bound in every pattern}} a: // expected-error {{cannot find 'a' in scope}} break } } // Fallthroughs can only transfer control into a case label with bindings if the previous case binds a superset of those vars. switch t { case (1, 2): fallthrough // expected-error {{'fallthrough' from a case which doesn't bind variable 'a'}} expected-error {{'fallthrough' from a case which doesn't bind variable 'b'}} case (var a, var b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} t = (b, a) } switch t { // specifically notice on next line that we shouldn't complain that a is unused - just never mutated case (var a, let b): // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} t = (b, b) fallthrough // ok - notice that subset of bound variables falling through is fine case (2, let a): t = (a, a) } func patternVarDiffType(x: Int, y: Double) { switch (x, y) { case (1, let a): // expected-error {{pattern variable bound to type 'Double', fallthrough case bound to type 'Int'}} fallthrough case (let a, _): break } } func patternVarDiffMutability(x: Int, y: Double) { switch x { case let a where a < 5, var a where a > 10: // expected-error {{'var' pattern binding must match previous 'let' pattern binding}}{{27-30=let}} break default: break } switch (x, y) { // Would be nice to have a fixit in the following line if we detect that all bindings in the same pattern have the same problem. case let (a, b) where a < 5, var (a, b) where a > 10: // expected-error 2{{'var' pattern binding must match previous 'let' pattern binding}}{{none}} break case (let a, var b) where a < 5, (let a, let b) where a > 10: // expected-error {{'let' pattern binding must match previous 'var' pattern binding}}{{44-47=var}} break case (let a, let b) where a < 5, (var a, let b) where a > 10, (let a, var b) where a == 8: // expected-error@-1 {{'var' pattern binding must match previous 'let' pattern binding}}{{37-40=let}} // expected-error@-2 {{'var' pattern binding must match previous 'let' pattern binding}}{{73-76=let}} break default: break } } func test_label(x : Int) { Gronk: // expected-error {{switch must be exhaustive}} expected-note{{do you want to add a default clause?}} switch x { case 42: return } } func enumElementSyntaxOnTuple() { switch (1, 1) { case .Bar: // expected-error {{value of tuple type '(Int, Int)' has no member 'Bar'}} break default: break } } // sr-176 enum Whatever { case Thing } func f0(values: [Whatever]) { // expected-note {{'values' declared here}} switch value { // expected-error {{cannot find 'value' in scope; did you mean 'values'?}} case .Thing: // Ok. Don't emit diagnostics about enum case not found in type <<error type>>. break } } // sr-720 enum Whichever { case Thing static let title = "title" static let alias: Whichever = .Thing } func f1(x: String, y: Whichever) { switch x { case Whichever.title: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.buzz: // expected-error {{type 'Whichever' has no member 'buzz'}} break case Whichever.alias: // expected-error {{expression pattern of type 'Whichever' cannot match values of type 'String'}} // expected-note@-1 {{overloads for '~=' exist with these partially matching parameter lists: (Substring, String)}} break default: break } switch y { case Whichever.Thing: // Ok. break case Whichever.alias: // Ok. Don't emit diagnostics for static member of enum. break case Whichever.title: // expected-error {{expression pattern of type 'String' cannot match values of type 'Whichever'}} break } } switch Whatever.Thing { case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} @unknown case _: x = 0 } switch Whatever.Thing { case .Thing: // expected-error{{'case' label in a 'switch' should have at least one executable statement}} {{13-13= break}} @unknown default: x = 0 } switch Whatever.Thing { case .Thing: x = 0 @unknown case _: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{17-17= break}} } switch Whatever.Thing { case .Thing: x = 0 @unknown default: // expected-error {{'default' label in a 'switch' should have at least one executable statement}} {{18-18= break}} } switch Whatever.Thing { @unknown default: x = 0 default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { default: x = 0 @unknown case _: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} expected-error {{'@unknown' can only be applied to the last case in a switch}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { default: x = 0 @unknown default: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} x = 0 case .Thing: x = 0 } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown default where x == 0: // expected-error{{'default' cannot be used with a 'where' guard expression}} x = 0 } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case _: fallthrough // expected-error{{'fallthrough' without a following 'case' or 'default' block}} } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} fallthrough case .Thing: break } switch Whatever.Thing { @unknown default: fallthrough case .Thing: // expected-error{{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch Whatever.Thing { @unknown case _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}} break } switch Whatever.Thing { @unknown case _, _, _: // expected-error {{'@unknown' cannot be applied to multiple patterns}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case let value: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} _ = value } switch (Whatever.Thing, Whatever.Thing) { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '(_, _)'}} @unknown case (_, _): // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case is Whatever: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} // expected-warning@-1 {{'is' test is always true}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case .Thing: // expected-error {{'@unknown' is only supported for catch-all cases ("case _")}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case (_): // okay break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown case _ where x == 0: // expected-error {{'where' cannot be used with '@unknown'}} break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note{{add missing case: '.Thing'}} @unknown default where x == 0: // expected-error {{'default' cannot be used with a 'where' guard expression}} break } switch Whatever.Thing { case .Thing: x = 0 #if true @unknown case _: x = 0 #endif } switch x { case 0: break @garbage case _: // expected-error {{unknown attribute 'garbage'}} break } switch x { case 0: break @garbage @moreGarbage default: // expected-error {{unknown attribute 'garbage'}} expected-error {{unknown attribute 'moreGarbage'}} break } @unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}} switch x { case _: @unknown let _ = 1 // expected-error {{unknown attribute 'unknown'}} } switch Whatever.Thing { case .Thing: break @unknown(garbage) case _: // expected-error {{unexpected '(' in attribute 'unknown'}} break } switch Whatever.Thing { case .Thing: break @unknown // expected-note {{attribute already specified here}} @unknown // expected-error {{duplicate attribute}} case _: break } switch Whatever.Thing { // expected-warning {{switch must be exhaustive}} expected-note {{add missing case: '.Thing'}} @unknown @garbage(foobar) // expected-error {{unknown attribute 'garbage'}} case _: break } switch x { // expected-error {{switch must be exhaustive}} case 1: break @unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch x { // expected-error {{switch must be exhaustive}} @unknown case _: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch x { // expected-error {{switch must be exhaustive}} @unknown default: // expected-note {{remove '@unknown' to handle remaining values}} {{1-10=}} break } switch Whatever.Thing { case .Thing: break @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch Whatever.Thing { case .Thing: break @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch Whatever.Thing { case .Thing: break @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch Whatever.Thing { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch Whatever.Thing { @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } switch x { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown case _: break } switch x { @unknown case _: // expected-error {{'@unknown' can only be applied to the last case in a switch}} break @unknown default: break } switch x { @unknown default: break @unknown default: // expected-error {{additional 'case' blocks cannot appear after the 'default' block of a 'switch'}} break } func testReturnBeforeUnknownDefault() { switch x { // expected-error {{switch must be exhaustive}} case 1: return @unknown default: // expected-note {{remove '@unknown' to handle remaining values}} break } } func testReturnBeforeIncompleteUnknownDefault() { switch x { // expected-error {{switch must be exhaustive}} case 1: return @unknown default // expected-error {{expected ':' after 'default'}} // expected-note@-1 {{remove '@unknown' to handle remaining values}} } } func testReturnBeforeIncompleteUnknownDefault2() { switch x { // expected-error {{switch must be exhaustive}} expected-note {{do you want to add a default clause?}} case 1: return @unknown // expected-error {{unknown attribute 'unknown'}} } // expected-error {{expected declaration}} } func testIncompleteArrayLiteral() { switch x { // expected-error {{switch must be exhaustive}} case 1: _ = [1 // expected-error {{expected ']' in container literal expression}} expected-note {{to match this opening '['}} @unknown default: // expected-note {{remove '@unknown' to handle remaining values}} () } }
77f5134ffc3539e56604807c1575714b
31.306028
326
0.675964
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/OpenPanelAccessoryController.swift
apache-2.0
1
// // OpenPanelAccessoryController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-02-24. // // --------------------------------------------------------------------------- // // © 2018-2022 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. // import Cocoa final class OpenPanelAccessoryController: NSViewController { // MARK: Public Properties weak var openPanel: NSOpenPanel? // keep open panel for hidden file visivility toggle // MARK: Private Properties @IBOutlet private weak var encodingMenu: NSPopUpButton? @objc private dynamic var _selectedEncoding: UInt = 0 // MARK: - // MARK: ViewController Methods override func viewDidLoad() { super.viewDidLoad() // build encoding menu let menu = self.encodingMenu!.menu! let autoDetectItem = NSMenuItem(title: "Automatic".localized, action: nil, keyEquivalent: "") menu.items = [autoDetectItem, .separator()] + EncodingManager.shared.createEncodingMenuItems() } // MARK: Public Methods /// encoding selected by user var selectedEncoding: String.Encoding? { self._selectedEncoding > 0 ? String.Encoding(rawValue: self._selectedEncoding) : nil } // MARK: Action Messages /// toggle visivility of hidden files @IBAction func toggleShowsHiddenFiles(_ sender: NSButton) { guard let openPanel = self.openPanel else { return assertionFailure() } let showsHiddenFiles = (sender.integerValue == 1) openPanel.showsHiddenFiles = showsHiddenFiles openPanel.treatsFilePackagesAsDirectories = showsHiddenFiles openPanel.validateVisibleColumns() } }
20373219f0cc42353df4d45e1db6d29e
27.421687
102
0.633319
false
false
false
false
yaozongchao/ComplicateTableDemo
refs/heads/master
ComplicateUI/KDTools.swift
mit
1
// // KDTools.swift // ComplicateUI // // Created by 姚宗超 on 2017/3/9. // Copyright © 2017年 姚宗超. All rights reserved. // import UIKit class KDTools: NSObject { public static func createAffineTransform(fromRect: CGRect, toRect: CGRect) -> CGAffineTransform { let sx = toRect.size.width/fromRect.size.width let sy = toRect.size.height/fromRect.size.height let scale = CGAffineTransform.init(scaleX: sx, y: sy) let heightDiff = fromRect.size.height - toRect.size.height let widthDiff = fromRect.size.width - toRect.size.width let dx = toRect.origin.x - widthDiff / 2 - fromRect.origin.x let dy = toRect.origin.y - heightDiff / 2 - fromRect.origin.y let trans = CGAffineTransform.init(translationX: dx, y: dy) return scale.concatenating(trans) } } extension CGRect { var centerPt: CGPoint { get { return CGPoint.init(x: self.origin.x + self.width/2.0, y: self.origin.y + self.height/2.0) } } }
5d26a02f7de30d6860aafd8055d601c5
27.540541
102
0.623106
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureCardIssuing/Sources/FeatureCardIssuingData/NetworkClients/LegalClient.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import FeatureCardIssuingDomain import Foundation import NetworkKit public final class LegalClient: LegalClientAPI { // MARK: - Types private enum Path: String { case legal } // MARK: - Properties private let networkAdapter: NetworkAdapterAPI private let requestBuilder: RequestBuilder // MARK: - Setup public init( networkAdapter: NetworkAdapterAPI, requestBuilder: RequestBuilder ) { self.networkAdapter = networkAdapter self.requestBuilder = requestBuilder } // MARK: - API func fetchLegalItems() -> AnyPublisher<[LegalItem], NabuNetworkError> { let request = requestBuilder.get( path: [Path.legal.rawValue], authenticated: true )! return networkAdapter .perform(request: request, responseType: [LegalItem].self) .eraseToAnyPublisher() } func setAccepted(legalItems: [LegalItem]) -> AnyPublisher<[LegalItem], NabuNetworkError> { let request = requestBuilder.put( path: [Path.legal.rawValue], body: try? legalItems.acceptParameters.encode(), authenticated: true )! return networkAdapter .perform(request: request, responseType: [LegalItem].self) .eraseToAnyPublisher() } } struct AcceptLegalParameters: Encodable { let legalPolicies: [Item] struct Item: Encodable { let name: String let acceptedVersion: Int } } extension LegalItem { var acceptParameters: AcceptLegalParameters.Item { AcceptLegalParameters.Item(name: name, acceptedVersion: version) } } extension Array where Element == LegalItem { var acceptParameters: AcceptLegalParameters { AcceptLegalParameters(legalPolicies: map(\.acceptParameters)) } }
69533afd36277679b9f65a0ae46ddba1
23.2625
94
0.657908
false
false
false
false
talentsparkio/GitHubDemo
refs/heads/master
GitHubDemo/GitHubMembersTableViewController.swift
bsd-3-clause
1
// // TableViewController.swift // GitHubDemo // // Created by Nick Chen on 8/6/15. // Copyright © 2015 TalentSpark. All rights reserved. // import UIKit class GitHubMembersTableViewController: UITableViewController { var members: [GitHubOrganization.Member] = [] // Currently this is an unbounded cache - you probably want to use something like a LRU var cachedImages = [String: UIImage]() override func viewDidLoad() { super.viewDidLoad() GitHubOrganization().fetchMembersDetails { (members: [GitHubOrganization.Member]) -> () in self.members = members self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Members" } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return members.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("memberCell", forIndexPath: indexPath) let member = members[indexPath.row] cell.textLabel?.text = member.login loadOrFetchImageFor(member.login, avatarUrl: member.avatarUrl, cell: cell) return cell } func loadOrFetchImageFor(login: String, avatarUrl: String, cell: UITableViewCell) -> Void { if let image = cachedImages[login] { // already in cache cell.imageView?.image = image } else { if let url = NSURL(string: avatarUrl) { // need to fetch dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)) { if let data = NSData(contentsOfURL: url) { if let avatarSquare = UIImage(data:data) { let avatarCircle = UIImage.roundedRectImageFromImage(avatarSquare, imageSize: avatarSquare.size, cornerRadius: avatarSquare.size.width / 2) self.cachedImages.updateValue(avatarCircle, forKey: login) // Because this happens asynchronously in the background, we need to check that by the time we get here // that the cell that requested the image is still the one that is being displayed. // If it is not, we would have cached the image for the future but we will not display it for now. if(cell.textLabel?.text == login) { dispatch_async(dispatch_get_main_queue()) { cell.imageView?.image = avatarCircle } } } } } } } } } // http://stackoverflow.com/questions/7399343/making-a-uiimage-to-a-circle-form extension UIImage { class func roundedRectImageFromImage(image: UIImage, imageSize: CGSize, cornerRadius: CGFloat)->UIImage { UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0) let bounds = CGRect(origin: CGPointZero, size: imageSize) UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip() image.drawInRect(bounds) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return finalImage } }
098000d10414a04209e75e5d1d4208f9
38.113402
167
0.611228
false
false
false
false
jeffreybergier/WaterMe2
refs/heads/master
WaterMe/Frameworks/Datum/Datum/CoreDataModels/CD_Reminder.swift
gpl-3.0
1
// // CD_Reminder.swift // Datum // // Created by Jeffrey Bergier on 2020/05/21. // Copyright © 2020 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // WaterMe is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with WaterMe. If not, see <http://www.gnu.org/licenses/>. // import CoreData @objc(CD_Reminder) internal class CD_Reminder: CD_Base { @NSManaged var interval: Int32 @NSManaged var kindString: String @NSManaged var descriptionString: String? @NSManaged var nextPerformDate: Date? @NSManaged var lastPerformDate: Date? @NSManaged var note: String? @NSManaged var performed: NSSet @NSManaged var vessel: CD_ReminderVessel override func awakeFromInsert() { super.awakeFromInsert() self.kindString = ReminderKind.kCaseWaterValue self.interval = Int32(ReminderConstants.defaultInterval) } internal func updateDates(basedOnAppendedPerformDate newDate: Date) { self.lastPerformDate = newDate let cal = Calendar.current self.nextPerformDate = cal.dateByAddingNumberOfDays(Int(self.interval), to: newDate) } } @objc(CD_ReminderPerform) internal class CD_ReminderPerform: CD_Base { @NSManaged var date: Date @NSManaged var reminder: CD_Reminder override func awakeFromInsert() { super.awakeFromInsert() self.date = Date() } } extension CD_Reminder { static func sortDescriptor(for sortOrder: ReminderSortOrder, ascending: Bool) -> NSSortDescriptor { switch sortOrder { case .interval: return .init(key: #keyPath(CD_Reminder.interval), ascending: ascending) case .kind: return .init(key: #keyPath(CD_Reminder.kindString), ascending: ascending) case .nextPerformDate: return .init(key: #keyPath(CD_Reminder.nextPerformDate), ascending: ascending) case .note: return .init(key: #keyPath(CD_Reminder.note), ascending: ascending) } } }
4b43874601dba819715614b9bb5a2c3e
32.683544
90
0.665163
false
false
false
false
edragoev1/pdfjet
refs/heads/master
Sources/PDFjet/Polynomial.swift
mit
1
/** * Copyright 2009 Kazuhiko Arase URL: http://www.d-project.com/ Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php The word "QR Code" is registered trademark of DENSO WAVE INCORPORATED http://www.denso-wave.com/qrcode/faqpatent-e.html */ import Foundation /** * Polynomial * @author Kazuhiko Arase */ class Polynomial { private var num: [Int] init(_ num: [Int], _ shift: Int) { var offset = 0 while offset < num.count && num[offset] == 0 { offset += 1 } self.num = [Int](repeating: 0, count: num.count - offset + shift) for i in 0..<(num.count - offset) { self.num[i] = num[offset + i] } } func get(_ index: Int) -> Int { return self.num[index] } func getLength() -> Int { return self.num.count } func multiply(_ polynomial: Polynomial) -> Polynomial { var num = [Int](repeating: 0, count: ((getLength() + polynomial.getLength()) - 1)) for i in 0..<getLength() { for j in 0..<polynomial.getLength() { num[i + j] ^= QRMath.singleton.gexp(QRMath.singleton.glog(get(i)) + QRMath.singleton.glog(polynomial.get(j))) } } return Polynomial(num, 0) } func mod(_ polynomial: Polynomial) -> Polynomial { if (getLength() - polynomial.getLength()) < 0 { return self } let ratio = QRMath.singleton.glog(get(0)) - QRMath.singleton.glog(polynomial.get(0)) var num = [Int](repeating: 0, count: getLength()) for i in 0..<getLength() { num[i] = get(i) } for i in 0..<polynomial.getLength() { num[i] ^= QRMath.singleton.gexp( QRMath.singleton.glog(polynomial.get(i)) + ratio) } return Polynomial(num, 0).mod(polynomial) } }
ec7ca1cd8c9417ef53df4b47ae84230d
25.243243
92
0.545314
false
false
false
false
TheTekton/Malibu
refs/heads/master
Sources/Request/Header.swift
mit
1
import Foundation struct Header { static let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" static var acceptLanguage: String { return Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in let quality = 1.0 - (Double(index) * 0.1) return "\(languageCode);q=\(quality)" }.joined(separator: ", ") } static let userAgent: String = { var string = "Malibu" if let info = Bundle.main.infoDictionary { let executable: AnyObject = info[kCFBundleExecutableKey as String] as AnyObject? ?? "Unknown" as AnyObject let bundle: AnyObject = info[kCFBundleIdentifierKey as String] as AnyObject? ?? "Unknown" as AnyObject let version: AnyObject = info[kCFBundleVersionKey as String] as AnyObject? ?? "Unknown" as AnyObject let os: AnyObject = ProcessInfo.processInfo.operatingSystemVersionString as AnyObject? ?? "Unknown" as AnyObject let mutableUserAgent = NSMutableString( string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString if CFStringTransform(mutableUserAgent, nil, transform, false) { string = mutableUserAgent as String } } return string }() static let defaultHeaders: [String: String] = { return [ "Accept-Encoding": acceptEncoding, "User-Agent": userAgent ] }() static func authentication(username: String, password: String) -> String? { let credentials = "\(username):\(password)" guard let credentialsData = credentials.data(using: String.Encoding.utf8) else { return nil } let base64Credentials = credentialsData.base64EncodedString(options: []) return "Basic \(base64Credentials)" } }
48c5ac6ddc7fd5d6f325fcd135f1ed0a
33.730769
118
0.681063
false
false
false
false
hooman/swift
refs/heads/main
test/Concurrency/Runtime/checked_continuation.swift
apache-2.0
2
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import _Concurrency import StdlibUnittest struct TestError: Error {} @main struct Main { static func main() async { var tests = TestSuite("CheckedContinuation") if #available(SwiftStdlib 5.5, *) { tests.test("trap on double resume non-throwing continuation") { expectCrashLater() let task = detach { let _: Int = await withCheckedContinuation { c in c.resume(returning: 17) c.resume(returning: 38) } } await task.get() } tests.test("trap on double resume throwing continuation") { expectCrashLater() let task = detach { do { let _: Int = try await withCheckedThrowingContinuation { c in c.resume(returning: 17) c.resume(throwing: TestError()) } } catch { } } await task.get() } tests.test("test withCheckedThrowingContinuation") { let task2 = detach { do { let x: Int = try await withCheckedThrowingContinuation { c in c.resume(returning: 17) } expectEqual(17, x) } catch { } } let task = detach { do { let x: Int = try await withCheckedThrowingContinuation { c in c.resume(returning: 17) } expectEqual(17, x) } catch { } } await task.get() await task2.get() } } await runAllTestsAsync() } }
04f9788c03cd9f3b3ed581bbb8454e0d
23.666667
94
0.540541
false
true
false
false
zhugejunwei/LeetCode
refs/heads/master
1. Two Sum.swift
mit
1
import Darwin // 996ms - bad solution //func twoSum(nums: [Int], _ target: Int) -> [Int] { // for i in 0..<nums.count { // if target >= 0 && nums[i] <= target { // for j in i+1..<nums.count { // if nums[i] + nums[j] == target { // return [i,j] // } // } // }else if target < 0 && nums[i] >= target { // for j in i+1..<nums.count { // if nums[i] + nums[j] == target { // return [i,j] // } // } // } // } // return [0,1] //} // Nicer solution - 148ms func twoSum(nums: [Int], _ target: Int) -> [Int] { var result = Array(count:2, repeatedValue: -1) var sorted = nums sorted = sorted.sort() var left = 0, right = sorted.count-1 var stop = 0 while left < right && stop == 0 { if sorted[left] + sorted[right] < target { left += 1 }else if sorted[left] + sorted[right] > target { right -= 1 }else { stop = 1 } } for i in 0..<sorted.count { if nums[i] == sorted[left] && result[0] == -1 { result[0] = i }else if nums[i] == sorted[right] { result[1] = i } } return result.sort() } //var a = [2, 7, 11, 15, 1, 3, 4] var b = [2,1,9,4,4,56,90,3], target = 8 twoSum(b, target)
56d2eb29fee0e29cc36e606952affe5a
23.258621
56
0.425729
false
false
false
false
52inc/Pulley
refs/heads/master
Pulley/CustomMaskExample.swift
mit
1
// // CustomMaskExample.swift // Pulley // // Created by Connor Power on 19.08.18. // Copyright © 2018 52inc. All rights reserved. // import UIKit struct CustomMaskExample { // MARK: - Constants private struct Constants { static let cornerRadius: CGFloat = 8.0 static let cutoutDistanceFromEdge: CGFloat = 32.0 static let cutoutRadius: CGFloat = 8.0 } // MARK: - Functions func customMask(for bounds: CGRect) -> UIBezierPath { let maxX = bounds.maxX let maxY = bounds.maxY let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: maxY)) // Left hand edge path.addLine(to: CGPoint(x: 0, y: Constants.cornerRadius)) // Top left rounded corner path.addArc(withCenter: CGPoint(x: Constants.cornerRadius, y: Constants.cornerRadius), radius: Constants.cornerRadius, startAngle: CGFloat.pi, endAngle: 1.5 * CGFloat.pi, clockwise: true) // Top edge left cutout section path.addLine(to: CGPoint(x: Constants.cutoutDistanceFromEdge - Constants.cutoutRadius, y: 0)) path.addArc(withCenter: CGPoint(x: Constants.cutoutDistanceFromEdge, y: 0), radius: Constants.cutoutRadius, startAngle: CGFloat.pi, endAngle: 2.0 * CGFloat.pi, clockwise: false) path.addLine(to: CGPoint(x: Constants.cutoutDistanceFromEdge + Constants.cutoutRadius, y: 0)) // Top edge right cutout section path.addLine(to: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge - Constants.cutoutRadius, y: 0)) path.addArc(withCenter: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge, y: 0), radius: Constants.cutoutRadius, startAngle: CGFloat.pi, endAngle: 2.0 * CGFloat.pi, clockwise: false) path.addLine(to: CGPoint(x: maxX - Constants.cutoutDistanceFromEdge + Constants.cutoutRadius, y: 0)) path.addLine(to: CGPoint(x: maxX - Constants.cornerRadius, y: 0)) // Top right rounded corner path.addArc(withCenter: CGPoint(x: maxX - Constants.cornerRadius, y: Constants.cornerRadius), radius: Constants.cornerRadius, startAngle: 1.5 * CGFloat.pi, endAngle: 2.0 * CGFloat.pi, clockwise: true) // Right hand edge path.addLine(to: CGPoint(x: maxX, y: maxY)) // Bottom edge path.addLine(to: CGPoint(x: 0, y: maxY)) path.close() path.fill() return path } }
d66fa2d8d777336f5c9caaf3d3d4c070
34.038961
108
0.588955
false
false
false
false
chaopengCoder/SwiftWeibo
refs/heads/master
Swift_weibo/Swift_weibo/Classes/View_ViewAndController/Main/WBMainController.swift
mit
1
// // WBMainController.swift // Swift_weibo // // Created by 任超鹏 on 2017/3/17. // Copyright © 2017年 任超鹏. All rights reserved. // import UIKit class WBMainController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() setupChildControllers() setupComposeButton() } /** portrait :竖屏, 字面意思: 肖像 landscape:横屏, 字面意思: 风景画 - 使用代码控制设备的方向, 好处, 可以在需要横屏的时候, 单独处理 - 设置支持的方向后, 当前的控制器及其子控制器都会遵守这个方向设置 - 如果播放视频, 通常是 Model 展现的 */ override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } @objc func composeAction() { print("撰写微博") let vc = UIViewController() vc.view.backgroundColor = UIColor.red let navi = UINavigationController.init(rootViewController: vc) vc.title = "测试屏幕旋转" present(navi, animated: true) { print("转过来了") } } var composeButton: UIButton = UIButton(image: "tabbar_compose_icon_add", backgroundImage: "tabbar_compose_button") } extension WBMainController { func setupComposeButton() { tabBar.addSubview(composeButton) //计算按钮的宽度 let count = CGFloat(childViewControllers.count) // '减 1' 的目的是 补充容错点, 防止用户点到容错点, 发生错误 let width = tabBar.bounds.width / count - 1 //OC 中的 CGRectInset 正数向内缩进, 负数向外扩展 composeButton.frame = tabBar.bounds.insetBy(dx: 2 * width, dy: 0) composeButton.addTarget(self, action: #selector(composeAction), for: .touchUpInside) } //设置所有子控制器 func setupChildControllers() { // let array = [ // ["clsName": "WBHomeController", "title": "首页", "imageName": "home", "visitorInfo": ["imageName": "", "message": "哈哈"] // ], // ["clsName": "WBMessageController", "title": "消息", "imageName": "message_center", "visitorInfo": ["imageName": "", "message": "哈哈"] // ], // ["clsName": "UIViewController"], // ["clsName": "WBDiscoverController", "title": "发现", "imageName": "discover", "visitorInfo": ["imageName": "发现", "message": "哈哈"] // ], // ["clsName": "WBProfileController", "title": "我", "imageName": "profile", "visitorInfo": ["imageName": "发现", "message": "哈哈"] // ] // ] let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let jsonPath = (docDir.first as? NSString)?.appendingPathComponent("main.json") //加载 data var data = NSData(contentsOfFile: jsonPath ?? "") //判断 data 是否有内容, 如果没有, 说明本地沙盒没有数据 if data == nil { //从 Bundle 加载data let path = Bundle.main.path(forResource: "main.json", ofType: nil) data = NSData(contentsOfFile: path ?? "") } //data 一定会有内容, 反序列化 //反序列化转换成数组 guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]] else{ return } //测试数据格式是否正确 - 转换成 plist 数据更加直观 // (array as NSArray).write(toFile: "/Users/r-chaopeng/Desktop/array.plist", atomically: true) //数据 -> json 序列化 // let data = try! JSONSerialization.data(withJSONObject: array, options: .prettyPrinted) // (data as NSData).write(toFile: "/Users/r-chaopeng/Desktop/demo.json", atomically: true) var arrayM = [UIViewController]() for dict in array! { arrayM.append(controller(dict: dict)) } viewControllers = arrayM } /// 使用字典创建一个子控制器 /// /// - Parameter dict: 信息字典[clsName, title, imageName] /// - Returns: 子控制器 private func controller(dict: [String: Any]) -> UIViewController{ //1. 取得字典内容 guard let clsName = dict["clsName"] as? String, let title = dict["title"] as? String, let imageName = dict["imageName"] as? String, let cls = NSClassFromString((Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "") + "." + clsName) as? WBBaseController.Type, let visitorDict = dict["visitorInfo"] as? [String: String] else { return UIViewController() } //2. 创建视图控制器 let vc = cls.init() //设置访客视图字典 vc.visitorInfo = visitorDict //设置标题 vc.title = title //3. 设置值头像 tabbar_home_selected vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName) vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal) //4. 设置 tabbar 的字体大小,颜色 //vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .highlighted) //vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 20)], for: .normal) // 初始化 navigationController的时候会调用 push 方法, 将 rootViewController 压栈 let navi = WBNavigationController(rootViewController: vc) return navi } }
f9a76abbf3a0e7880a5e11c1318ce1d5
31.191617
146
0.563058
false
false
false
false
marselan/patient-records
refs/heads/master
Patient-Records/Patient-Records/DicomInfo.swift
gpl-3.0
1
// // DicomInfo.swift // Patient-Records // // Created by Mariano Arselan on 27/4/17. // Copyright © 2017 Mariano Arselan. All rights reserved. // import Foundation import SwiftyJSON class DicomInfo { var id = 0 var studyId = 0 var sliceCount = 0 func populateFromJson(_ json : JSON) { id = json["data"]["id"].intValue studyId = json["data"]["studyId"].intValue sliceCount = json["data"]["sliceCount"].intValue } }
73e7737b4e9db7e43c58c245905bd50a
18.75
58
0.618143
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCDatabaseTypeInfo.swift
lgpl-2.1
2
// // NCDatabaseTypeInfo.swift // Neocom // // Created by Artem Shimanski on 09.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import Foundation import CoreData import EVEAPI import Futures class NCDatabaseTypeInfoRow: DefaultTreeRow { convenience init?(attribute: NCDBDgmTypeAttribute, value: Double?) { func toString(_ value: Double, _ unit: String?) -> String { var s = NCUnitFormatter.localizedString(from: value, unit: .none, style: .full) if let unit = unit { s += " " + unit } return s } guard let attributeType = attribute.attributeType else {return nil} let value = value ?? attribute.value var title: String? var subtitle: String? var image: UIImage? var object: Any? var route: Route? switch NCDBUnitID(rawValue: Int(attributeType.unit?.unitID ?? 0)) ?? NCDBUnitID.none { case .attributeID: guard let attributeType = NCDBDgmAttributeType.dgmAttributeTypes(managedObjectContext: attribute.managedObjectContext!)[Int(value)] else {break} subtitle = attributeType.displayName ?? attributeType.attributeName case .groupID: guard let group = NCDBInvGroup.invGroups(managedObjectContext: attribute.managedObjectContext!)[Int(value)] else {break} image = attributeType.icon?.image?.image ?? group.icon?.image?.image subtitle = group.groupName object = group.objectID route = Router.Database.Types(group: group) case .typeID: guard let type = NCDBInvType.invTypes(managedObjectContext: attribute.managedObjectContext!)[Int(value)] else {break} image = type.icon?.image?.image ?? attributeType.icon?.image?.image subtitle = type.typeName object = type.objectID route = Router.Database.TypeInfo(type.objectID) case .sizeClass: switch Int(value) { case 0: return nil; case 1: subtitle = NSLocalizedString("Small", comment: "") case 2: subtitle = NSLocalizedString("Medium", comment: "") case 3: subtitle = NSLocalizedString("Large", comment: "") case 4: subtitle = NSLocalizedString("X-Large", comment: "") default: subtitle = "\(Int(value))" } case .bonus: subtitle = "+" + NCUnitFormatter.localizedString(from: Double(value), unit: .none, style: .full) image = attributeType.icon?.image?.image case .boolean: subtitle = Int(value) == 0 ? NSLocalizedString("No", comment: "") : NSLocalizedString("Yes", comment: "") case .inverseAbsolutePercent, .inversedModifierPercent: subtitle = toString((1.0 - value) * 100.0, attributeType.unit?.displayName) case .modifierPercent: subtitle = toString((value - 1.0) * 100.0, attributeType.unit?.displayName) case .absolutePercent: subtitle = toString(value * 100.0, attributeType.unit?.displayName) case .milliseconds: subtitle = toString(value / 1000.0, attributeType.unit?.displayName) default: subtitle = toString(value, attributeType.unit?.displayName) } if title == nil { if let displayName = attributeType.displayName, !displayName.isEmpty { title = displayName } else if let attributeName = attributeType.attributeName, !attributeName.isEmpty { title = attributeName } else { return nil } } if image == nil { image = attributeType.icon?.image?.image } self.init(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: attribute.attributeType?.attributeName, image: image, title: title?.uppercased(), subtitle: subtitle, accessoryType: route != nil ? .disclosureIndicator : .none, route: route, object: object) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.textColor = .caption cell.subtitleLabel?.textColor = .white cell.iconView?.tintColor = .white } } class NCDatabaseTypeSkillRow: DefaultTreeRow { var trainingTime: TimeInterval = 0 var skill: NCTrainingSkill? init(skill: NCDBInvType, level: Int, character: NCCharacter, children: [TreeNode]?) { let title = NSAttributedString(skillName: skill.typeName!, level: level) let image: UIImage? let trainingSkill: NCTrainingSkill? let trainingTime: TimeInterval if let trainedSkill = character.skills[Int(skill.typeID)], let trainedLevel = trainedSkill.level { if trainedLevel >= level { image = #imageLiteral(resourceName: "skillRequirementMe") trainingTime = 0 trainingSkill = nil } else { trainingSkill = NCTrainingSkill(type: skill, skill: trainedSkill, level: level) trainingTime = trainingSkill?.trainingTime(characterAttributes: character.attributes) ?? 0 image = #imageLiteral(resourceName: "skillRequirementNotMe") } } else { trainingSkill = NCTrainingSkill(type: skill, level: level) trainingTime = trainingSkill?.trainingTime(characterAttributes: character.attributes) ?? 0 image = #imageLiteral(resourceName: "skillRequirementNotInjected") } let subtitle = trainingTime > 0 ? NCTimeIntervalFormatter.localizedString(from: trainingTime, precision: .seconds) : nil super.init(prototype: Prototype.NCDefaultTableViewCell.default, image: image, attributedTitle: title, subtitle: subtitle, accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(skill.objectID), object: skill.objectID) self.children = children ?? [] self.skill = trainingSkill self.trainingTime = trainingTime } convenience init(skill: NCDBInvTypeRequiredSkill, character: NCCharacter, children: [TreeNode]? = nil) { self.init(skill: skill.skillType!, level: Int(skill.skillLevel), character: character, children: children) } convenience init(skill: NCDBIndRequiredSkill, character: NCCharacter, children: [TreeNode]? = nil) { self.init(skill: skill.skillType!, level: Int(skill.skillLevel), character: character, children: children) } convenience init(skill: NCDBCertSkill, character: NCCharacter, children: [TreeNode]? = nil) { self.init(skill: skill.type!, level: Int(skill.skillLevel), character: character, children: children) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCDefaultTableViewCell else {return} cell.indentationWidth = 10 let tintColor = trainingTime > 0 ? UIColor.lightText : UIColor.white cell.subtitleLabel?.textColor = tintColor cell.iconView?.tintColor = tintColor if let skill = self.skill/*, trainingTime > 0*/ { let typeID = skill.skill.typeID let level = skill.level let item = NCAccount.current?.activeSkillPlan?.skills?.first(where: { (skill) -> Bool in let skill = skill as! NCSkillPlanSkill return Int(skill.typeID) == typeID && Int(skill.level) >= level }) if item != nil { cell.iconView?.image = #imageLiteral(resourceName: "skillRequirementQueued") } } } } class NCDatabaseTrainingSkillRow: NCDatabaseTypeSkillRow { let character: NCCharacter init(skill: NCDBInvType, level: Int, character: NCCharacter) { self.character = character super.init(skill: skill, level: level, character: character, children: nil) route = nil accessoryType = .none } } class NCDatabaseTypeMarketRow: TreeRow { var volume: UIBezierPath? var median: UIBezierPath? var donchian: UIBezierPath? var donchianVisibleRange: CGRect? var date: ClosedRange<Date>? let history: NCCacheRecord var observer: NCManagedObjectObserver? init(history: NCCacheRecord, typeID: Int) { self.history = history super.init(prototype: Prototype.NCMarketHistoryTableViewCell.default, route: Router.Database.MarketInfo(typeID)) self.observer = NCManagedObjectObserver(managedObject: history) {[weak self] (_, _) in self?.reload() } reload() } func reload() { NCCache.sharedCache?.performBackgroundTask { managedObjectContext in guard let record = (try? managedObjectContext.existingObject(with: self.history.objectID)) as? NCCacheRecord else {return} guard let history: [ESI.Market.History] = record.get() else {return} guard history.count > 0 else {return} guard let date = history.last?.date.addingTimeInterval(-3600 * 24 * 365) else {return} guard let i = history.index(where: { $0.date > date }) else { return } let range = history.suffix(from: i).indices let visibleRange = { () -> ClosedRange<Double> in var h2 = 0 as Double var h = 0 as Double var l2 = 0 as Double var l = 0 as Double let n = Double(range.count) for i in range { let item = history[i] h += Double(item.highest) / n h2 += Double(item.highest * item.highest) / n l += Double(item.lowest) / n l2 += Double(item.lowest * item.lowest) / n } let avgl = l let avgh = h h *= h l *= l let devh = h < h2 ? sqrt(h2 - h) : 0 let devl = l < l2 ? sqrt(l2 - l) : 0 return (avgl - devl * 3)...(avgh + devh * 3) }() let volume = UIBezierPath() volume.move(to: CGPoint(x: 0, y: 0)) let donchian = UIBezierPath() let avg = UIBezierPath() var x: CGFloat = 0 var isFirst = true var v = 0...0 as ClosedRange<Int64> var p = 0...0 as ClosedRange<Double> let d = history[range.first!].date...history[range.last!].date var prevT: TimeInterval? var lowest = Double.greatestFiniteMagnitude as Double var highest = 0 as Double for i in range { let item = history[i] if visibleRange.contains(Double(item.lowest)) { lowest = min(lowest, Double(item.lowest)) } if visibleRange.contains(Double(item.highest)) { highest = max(highest, Double(item.highest)) } let t = item.date.timeIntervalSinceReferenceDate x = CGFloat(item.date.timeIntervalSinceReferenceDate) let lowest = history[max(i - 4, 0)...i].min { $0.lowest < $1.lowest }! let highest = history[max(i - 4, 0)...i].max { $0.highest < $1.highest }! if isFirst { avg.move(to: CGPoint(x: x, y: CGFloat(item.average))) isFirst = false } else { avg.addLine(to: CGPoint(x: x, y: CGFloat(item.average))) } if let prevT = prevT { volume.append(UIBezierPath(rect: CGRect(x: CGFloat(prevT), y: 0, width: CGFloat(t - prevT), height: CGFloat(item.volume)))) donchian.append(UIBezierPath(rect: CGRect(x: CGFloat(prevT), y: CGFloat(lowest.lowest), width: CGFloat(t - prevT), height: abs(CGFloat(highest.highest - lowest.lowest))))) } prevT = t v = min(v.lowerBound, item.volume)...max(v.upperBound, item.volume) p = min(p.lowerBound, Double(lowest.lowest))...max(p.upperBound, Double(highest.highest)) } var donchianVisibleRange = donchian.bounds if lowest < highest { donchianVisibleRange.origin.y = CGFloat(lowest) donchianVisibleRange.size.height = CGFloat(highest - lowest) } DispatchQueue.main.async { self.volume = volume self.median = avg self.donchian = donchian self.donchianVisibleRange = donchianVisibleRange self.date = d self.treeController?.reloadCells(for: [self]) } } } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCMarketHistoryTableViewCell else {return} cell.marketHistoryView.volume = volume cell.marketHistoryView.median = median cell.marketHistoryView.donchian = donchian cell.marketHistoryView.donchianVisibleRange = donchianVisibleRange cell.marketHistoryView.date = date } } class NCDatabaseTypeResistanceRow: TreeRow { var em: Double = 0 var thermal: Double = 0 var kinetic: Double = 0 var explosive: Double = 0 init() { super.init(prototype: Prototype.NCDamageTypeTableViewCell.compact) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCDamageTypeTableViewCell else {return} cell.emLabel.progress = Float(em) cell.emLabel.text = "\(Int(em * 100))%" cell.thermalLabel.progress = Float(thermal) cell.thermalLabel.text = "\(Int(thermal * 100))%" cell.kineticLabel.progress = Float(kinetic) cell.kineticLabel.text = "\(Int(kinetic * 100))%" cell.explosiveLabel.progress = Float(explosive) cell.explosiveLabel.text = "\(Int(explosive * 100))%" } } class NCDatabaseTypeDamageRow: TreeRow { var em: Double = 0 var thermal: Double = 0 var kinetic: Double = 0 var explosive: Double = 0 init() { super.init(prototype: Prototype.NCDamageTypeTableViewCell.compact) } override func configure(cell: UITableViewCell) { let cell = cell as! NCDamageTypeTableViewCell var total = em + thermal + kinetic + explosive if total == 0 { total = 1 } cell.emLabel.progress = Float(em / total) cell.emLabel.text = NCUnitFormatter.localizedString(from: em, unit: .none, style: .short) cell.thermalLabel.progress = Float(thermal / total) cell.thermalLabel.text = NCUnitFormatter.localizedString(from: thermal, unit: .none, style: .short) cell.kineticLabel.progress = Float(kinetic / total) cell.kineticLabel.text = NCUnitFormatter.localizedString(from: kinetic, unit: .none, style: .short) cell.explosiveLabel.progress = Float(explosive / total) cell.explosiveLabel.text = NCUnitFormatter.localizedString(from: explosive, unit: .none, style: .short) } } class NCDatabaseSkillsSection: NCActionTreeSection { let trainingQueue: NCTrainingQueue let character: NCCharacter let trainingTime: TimeInterval init(nodeIdentifier: String?, title: String?, trainingQueue: NCTrainingQueue, character: NCCharacter, children: [TreeNode]? = nil) { self.trainingQueue = trainingQueue self.character = character trainingTime = trainingQueue.trainingTime(characterAttributes: character.attributes) let attributedTitle = NSMutableAttributedString(string: title ?? "") if trainingTime > 0 { attributedTitle.append(NSAttributedString( string: " (\(NCTimeIntervalFormatter.localizedString(from: trainingTime, precision: .seconds)))", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])) } super.init(nodeIdentifier: nodeIdentifier, attributedTitle: attributedTitle, children: children) } override func configure(cell: UITableViewCell) { super.configure(cell: cell) guard let cell = cell as? NCActionHeaderTableViewCell else {return} cell.button?.isHidden = NCAccount.current == nil || trainingTime == 0 } } struct NCDatabaseTypeInfo { static func typeInfo(type: NCDBInvType, attributeValues: [Int: Double]?) -> Future<[TreeNode]> { var marketSection: DefaultTreeSection? if type.marketGroup != nil { let regionID = (UserDefaults.standard.value(forKey: UserDefaults.Key.NCMarketRegion) as? Int) ?? NCDBRegionID.theForge.rawValue let typeID = Int(type.typeID) marketSection = DefaultTreeSection(nodeIdentifier: "Market", title: NSLocalizedString("Market", comment: "").uppercased(), children: []) let dataManager = NCDataManager(account: NCAccount.current) dataManager.marketHistory(typeID: typeID, regionID: regionID).then(on: .main) { result in let row = NCDatabaseTypeMarketRow(history: result.cacheRecord(in: NCCache.sharedCache!.viewContext), typeID: typeID) marketSection?.children.append(row) } dataManager.prices(typeIDs: [typeID]).then(on: .main) { result in guard let price = result[typeID] else {return} let subtitle = NCUnitFormatter.localizedString(from: price, unit: .isk, style: .full) let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, image: #imageLiteral(resourceName: "wallet"), title: NSLocalizedString("PRICE", comment: ""), subtitle: subtitle, accessoryType: .disclosureIndicator, route: Router.Database.MarketInfo(typeID)) marketSection?.children.insert(row, at: 0) } } switch NCDBCategoryID(rawValue: Int(type.group?.category?.categoryID ?? 0)) { case .blueprint?: return blueprintInfo(type: type).then(on: .main) { result -> [TreeNode] in var sections = result if let marketSection = marketSection { sections.insert(marketSection, at: 0) } return result } case .entity?: return npcInfo(type: type) default: if type.wormhole != nil { return whInfo(type: type) } else { return itemInfo(type: type, attributeValues: attributeValues).then(on: .main) { result -> [TreeNode] in var sections = result if let marketSection = marketSection { sections.insert(marketSection, at: 0) } return sections } } } } static func itemInfo(type: NCDBInvType, attributeValues: [Int: Double]?) -> Future<[TreeNode]> { let account = NCAccount.current return NCDatabase.sharedDatabase!.performBackgroundTask { managedObjectContext -> [TreeNode] in let character: NCCharacter = (try? NCCharacter.load(account: NCAccount.current).get()) ?? NCCharacter() var sections = [TreeSection]() guard let type = (try? managedObjectContext.existingObject(with: type.objectID)) as? NCDBInvType else {return sections} if let skillPlan = NCDatabaseTypeInfo.skillPlan(type: type, character: character) { sections.append(skillPlan) } if let mastery = NCDatabaseTypeInfo.masteries(type: type, character: character) { sections.append(mastery) } if type.parentType != nil || (type.variations?.count ?? 0) > 0 { let n = max(type.variations?.count ?? 0, type.parentType?.variations?.count ?? 0) + 1 let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "Variations", title: String(format: NSLocalizedString("%d types", comment: ""), n).uppercased(), accessoryType: .disclosureIndicator, route: Router.Database.Variations(typeObjectID: type.objectID)) let section = DefaultTreeSection(nodeIdentifier: "VariationsSection", title: NSLocalizedString("Variations", comment: "").uppercased(), children: [row]) sections.append(section) } else if (type.requiredForSkill?.count ?? 0) > 0 { let n = type.requiredForSkill!.count let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "RequiredFor", title: String(format: NSLocalizedString("%d types", comment: ""), n).uppercased(), accessoryType: .disclosureIndicator, route: Router.Database.RequiredFor(typeObjectID: type.objectID)) let section = DefaultTreeSection(nodeIdentifier: "RequiredForSection", title: NSLocalizedString("Required for", comment: "").uppercased(), children: [row]) sections.append(section) } let request = NSFetchRequest<NCDBDgmTypeAttribute>(entityName: "DgmTypeAttribute") request.predicate = NSPredicate(format: "type == %@ AND attributeType.published == TRUE", type) request.sortDescriptors = [NSSortDescriptor(key: "attributeType.attributeCategory.categoryID", ascending: true), NSSortDescriptor(key: "attributeType.attributeID", ascending: true)] let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "attributeType.attributeCategory.categoryID", cacheName: nil) guard let _ = try? results.performFetch() else {return sections} guard results.sections != nil else {return sections} for section in results.sections! { guard let attributeCategory = (section.objects?.first as? NCDBDgmTypeAttribute)?.attributeType?.attributeCategory else {continue} if attributeCategory.categoryID == Int32(NCDBAttributeCategoryID.requiredSkills.rawValue) { if let section = requiredSkills(type: type, character: character) { sections.append(section) } } else { let sectionTitle: String if Int(attributeCategory.categoryID) == NCDBAttributeCategoryID.null.rawValue { sectionTitle = NSLocalizedString("Other", comment: "") } else { sectionTitle = attributeCategory.categoryName ?? NSLocalizedString("Other", comment: "") } var rows = [TreeNode]() var resistanceRow: NCDatabaseTypeResistanceRow? func resistance() -> NCDatabaseTypeResistanceRow? { if resistanceRow == nil { resistanceRow = NCDatabaseTypeResistanceRow() } return resistanceRow } var damageRow: NCDatabaseTypeDamageRow? func damage() -> NCDatabaseTypeDamageRow? { if damageRow == nil { damageRow = NCDatabaseTypeDamageRow() } return damageRow } for attribute in (section.objects as? [NCDBDgmTypeAttribute]) ?? [] { let value = attributeValues?[Int(attribute.attributeType!.attributeID)] ?? attribute.value switch NCDBAttributeID(rawValue: Int(attribute.attributeType!.attributeID)) ?? NCDBAttributeID.none { case .emDamageResonance, .armorEmDamageResonance, .shieldEmDamageResonance, .hullEmDamageResonance, .passiveArmorEmDamageResonance, .passiveShieldEmDamageResonance: guard let row = resistance() else {continue} row.em = max(row.em, 1 - value) case .thermalDamageResonance, .armorThermalDamageResonance, .shieldThermalDamageResonance, .hullThermalDamageResonance, .passiveArmorThermalDamageResonance, .passiveShieldThermalDamageResonance: guard let row = resistance() else {continue} row.thermal = max(row.thermal, 1 - value) case .kineticDamageResonance, .armorKineticDamageResonance, .shieldKineticDamageResonance, .hullKineticDamageResonance, .passiveArmorKineticDamageResonance, .passiveShieldKineticDamageResonance: guard let row = resistance() else {continue} row.kinetic = max(row.kinetic, 1 - value) case .explosiveDamageResonance, .armorExplosiveDamageResonance, .shieldExplosiveDamageResonance, .hullExplosiveDamageResonance, .passiveArmorExplosiveDamageResonance, .passiveShieldExplosiveDamageResonance: guard let row = resistance() else {continue} row.explosive = max(row.explosive, 1 - value) case .emDamage: damage()?.em = value case .thermalDamage: damage()?.thermal = value case .kineticDamage: damage()?.kinetic = value case .explosiveDamage: damage()?.explosive = value case .warpSpeedMultiplier: guard let attributeType = attribute.attributeType else {continue} let baseWarpSpeed = attributeValues?[NCDBAttributeID.baseWarpSpeed.rawValue] ?? type.allAttributes[NCDBAttributeID.baseWarpSpeed.rawValue]?.value ?? 1.0 var s = NCUnitFormatter.localizedString(from: Double(value * baseWarpSpeed), unit: .none, style: .full) s += " " + NSLocalizedString("AU/sec", comment: "") rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, image: attributeType.icon?.image?.image, title: NSLocalizedString("Warp Speed", comment: ""), subtitle: s)) default: guard let row = NCDatabaseTypeInfoRow(attribute: attribute, value: value) else {continue} rows.append(row) } } if let resistanceRow = resistanceRow { rows.append(resistanceRow) } if let damageRow = damageRow { rows.append(damageRow) } if rows.count > 0 { sections.append(DefaultTreeSection(nodeIdentifier: String(attributeCategory.categoryID), title: sectionTitle.uppercased(), children: rows)) } } } return sections } } static func blueprintInfo(type: NCDBInvType) -> Future<[TreeNode]> { return NCDatabase.sharedDatabase!.performBackgroundTask { managedObjectContext -> [TreeNode] in let character: NCCharacter = (try? NCCharacter.load(account: NCAccount.current).get()) ?? NCCharacter() var sections = [TreeSection]() guard let type = (try? managedObjectContext.existingObject(with: type.objectID)) as? NCDBInvType else {return sections} guard let blueprintType = type.blueprintType else {return sections} for activity in blueprintType.activities?.sortedArray(using: [NSSortDescriptor(key: "activity.activityID", ascending: true)]) as? [NCDBIndActivity] ?? [] { var rows = [TreeNode]() let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.default, image: #imageLiteral(resourceName: "skillRequirementQueued"), // title: NSLocalizedString("TIME", comment: ""), subtitle: NCTimeIntervalFormatter.localizedString(from: TimeInterval(activity.time), precision: .seconds)) rows.append(row) for product in activity.products?.sortedArray(using: [NSSortDescriptor(key: "productType.typeName", ascending: true)]) as? [NCDBIndProduct] ?? [] { guard let type = product.productType, let subtitle = type.typeName else {continue} let title = NSLocalizedString("PRODUCT", comment: "") let image = type.icon?.image?.image let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, image: image, title: title, subtitle: subtitle, accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(type.objectID)) rows.append(row) } var materials = [TreeNode]() for material in activity.requiredMaterials?.sortedArray(using: [NSSortDescriptor(key: "materialType.typeName", ascending: true)]) as? [NCDBIndRequiredMaterial] ?? [] { guard let type = material.materialType, let title = type.typeName else {continue} let subtitle = NCUnitFormatter.localizedString(from: material.quantity, unit: .none, style: .full) let image = type.icon?.image?.image let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, image: image, title: title, subtitle: subtitle, accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(type.objectID)) materials.append(row) } if materials.count > 0 { rows.append(DefaultTreeSection(nodeIdentifier: "Materials\(activity.activity?.activityID ?? 0)", title: NSLocalizedString("MATERIALS", comment: ""), children: materials)) } if let skills = requiredSkills(activity: activity, character: character) { rows.append(skills) } sections.append(DefaultTreeSection(nodeIdentifier: activity.activity?.activityName, title: activity.activity?.activityName?.uppercased(), children: rows)) } return sections } } static func npcInfo(type: NCDBInvType) -> Future<[TreeNode]> { return NCDatabase.sharedDatabase!.performBackgroundTask { managedObjectContext -> [TreeNode] in var sections = [TreeSection]() guard let type = (try? managedObjectContext.existingObject(with: type.objectID)) as? NCDBInvType else {return sections} let request = NSFetchRequest<NCDBDgmTypeAttribute>(entityName: "DgmTypeAttribute") request.predicate = NSPredicate(format: "type == %@ AND attributeType.published == TRUE", type) request.sortDescriptors = [NSSortDescriptor(key: "attributeType.attributeCategory.categoryID", ascending: true), NSSortDescriptor(key: "attributeType.attributeID", ascending: true)] let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "attributeType.attributeCategory.categoryID", cacheName: nil) guard let _ = try? results.performFetch() else {return sections} guard results.sections != nil else {return sections} let invTypes = NCDBInvType.invTypes(managedObjectContext: managedObjectContext) let attributes = type.allAttributes for section in results.sections! { guard let attributeCategory = (section.objects?.first as? NCDBDgmTypeAttribute)?.attributeType?.attributeCategory else {continue} let sectionTitle: String if Int(attributeCategory.categoryID) == NCDBAttributeCategoryID.null.rawValue { sectionTitle = NSLocalizedString("Other", comment: "") } else { sectionTitle = attributeCategory.categoryName ?? NSLocalizedString("Other", comment: "") } var rows = [TreeNode]() let category = NCDBAttributeCategoryID(rawValue: Int(attributeCategory.categoryID)) switch category { case .turrets?: if let speed = attributes[NCDBAttributeID.speed.rawValue] { let damageMultiplier = attributes[NCDBAttributeID.damageMultiplier.rawValue]?.value ?? 1 let maxRange = attributes[NCDBAttributeID.maxRange.rawValue]?.value ?? 0 let falloff = attributes[NCDBAttributeID.falloff.rawValue]?.value ?? 0 let trackingSpeed = attributes[NCDBAttributeID.trackingSpeed.rawValue]?.value ?? 0 let duration = speed.value / 1000 let em = attributes[NCDBAttributeID.emDamage.rawValue]?.value ?? 0 let explosive = attributes[NCDBAttributeID.explosiveDamage.rawValue]?.value ?? 0 let kinetic = attributes[NCDBAttributeID.kineticDamage.rawValue]?.value ?? 0 let thermal = attributes[NCDBAttributeID.thermalDamage.rawValue]?.value ?? 0 let total = (em + explosive + kinetic + thermal) * damageMultiplier let interval = duration > 0 ? duration : 1 let dps = total / interval let damageRow = NCDatabaseTypeDamageRow() damageRow.em = em * damageMultiplier damageRow.explosive = explosive * damageMultiplier damageRow.kinetic = kinetic * damageMultiplier damageRow.thermal = thermal * damageMultiplier rows.append(damageRow) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "TurretDamage", image: #imageLiteral(resourceName: "turrets"), title: NSLocalizedString("Damage per Second", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: dps, unit: .none, style: .full))) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "TurretRoF", image: #imageLiteral(resourceName: "rateOfFire"), title: NSLocalizedString("Rate of Fire", comment: "").uppercased(), subtitle: NCTimeIntervalFormatter.localizedString(from: TimeInterval(duration), precision: .seconds))) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "TurretOptimal", image: #imageLiteral(resourceName: "targetingRange"), title: NSLocalizedString("Optimal Range", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: maxRange, unit: .meter, style: .full))) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "TurretFalloff", image: #imageLiteral(resourceName: "falloff"), title: NSLocalizedString("Falloff", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: falloff, unit: .meter, style: .full))) } case .missile?: if let attribute = attributes[NCDBAttributeID.entityMissileTypeID.rawValue], let missile = invTypes[Int(attribute.value)] { rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: attribute.attributeType?.attributeName, image: missile.icon?.image?.image, title: NSLocalizedString("Missile", comment: "").uppercased(), subtitle: missile.typeName, accessoryType: .disclosureIndicator, route: Router.Database.TypeInfo(missile.objectID), object: attribute)) let duration = (attributes[NCDBAttributeID.missileLaunchDuration.rawValue]?.value ?? 1000) / 1000 let damageMultiplier = attributes[NCDBAttributeID.missileDamageMultiplier.rawValue]?.value ?? 1 let velocityMultiplier = attributes[NCDBAttributeID.missileEntityVelocityMultiplier.rawValue]?.value ?? 1 let flightTimeMultiplier = attributes[NCDBAttributeID.missileEntityFlightTimeMultiplier.rawValue]?.value ?? 1 let missileAttributes = missile.allAttributes let em = missileAttributes[NCDBAttributeID.emDamage.rawValue]?.value ?? 0 let explosive = missileAttributes[NCDBAttributeID.explosiveDamage.rawValue]?.value ?? 0 let kinetic = missileAttributes[NCDBAttributeID.kineticDamage.rawValue]?.value ?? 0 let thermal = missileAttributes[NCDBAttributeID.thermalDamage.rawValue]?.value ?? 0 let total = (em + explosive + kinetic + thermal) * damageMultiplier let damageRow = NCDatabaseTypeDamageRow() damageRow.em = em * damageMultiplier damageRow.explosive = explosive * damageMultiplier damageRow.kinetic = kinetic * damageMultiplier damageRow.thermal = thermal * damageMultiplier rows.append(damageRow) let velocity = (missileAttributes[NCDBAttributeID.maxVelocity.rawValue]?.value ?? 0) * velocityMultiplier let flightTime = (missileAttributes[NCDBAttributeID.explosionDelay.rawValue]?.value ?? 1) * flightTimeMultiplier / 1000 let agility = missileAttributes[NCDBAttributeID.agility.rawValue]?.value ?? 0 let mass = missile.mass let accelTime = min(flightTime, mass * agility / 1000000.0) let duringAcceleration = velocity / 2 * accelTime let fullSpeed = velocity * (flightTime - accelTime) let optimal = duringAcceleration + fullSpeed; let interval = duration > 0 ? duration : 1 let dps = total / interval rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MissileDamage", image: #imageLiteral(resourceName: "launchers"), title: NSLocalizedString("Damage per Second", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: dps, unit: .none, style: .full))) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MissileRoF", image: #imageLiteral(resourceName: "rateOfFire"), title: NSLocalizedString("Rate of Fire", comment: "").uppercased(), subtitle: NCTimeIntervalFormatter.localizedString(from: TimeInterval(duration), precision: .seconds))) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MissileOptimal", image: #imageLiteral(resourceName: "targetingRange"), title: NSLocalizedString("Optimal Range", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: optimal, unit: .meter, style: .full))) } default: var resistanceRow: NCDatabaseTypeResistanceRow? func resistance() -> NCDatabaseTypeResistanceRow? { if resistanceRow == nil { resistanceRow = NCDatabaseTypeResistanceRow() } return resistanceRow } for attribute in (section.objects as? [NCDBDgmTypeAttribute]) ?? [] { switch NCDBAttributeID(rawValue: Int(attribute.attributeType!.attributeID)) ?? NCDBAttributeID.none { case .emDamageResonance, .armorEmDamageResonance, .shieldEmDamageResonance, .hullEmDamageResonance, .passiveArmorEmDamageResonance, .passiveShieldEmDamageResonance: guard let row = resistance() else {continue} row.em = max(row.em, 1 - attribute.value) case .thermalDamageResonance, .armorThermalDamageResonance, .shieldThermalDamageResonance, .hullThermalDamageResonance, .passiveArmorThermalDamageResonance, .passiveShieldThermalDamageResonance: guard let row = resistance() else {continue} row.thermal = max(row.thermal, 1 - attribute.value) case .kineticDamageResonance, .armorKineticDamageResonance, .shieldKineticDamageResonance, .hullKineticDamageResonance, .passiveArmorKineticDamageResonance, .passiveShieldKineticDamageResonance: guard let row = resistance() else {continue} row.kinetic = max(row.kinetic, 1 - attribute.value) case .explosiveDamageResonance, .armorExplosiveDamageResonance, .shieldExplosiveDamageResonance, .hullExplosiveDamageResonance, .passiveArmorExplosiveDamageResonance, .passiveShieldExplosiveDamageResonance: guard let row = resistance() else {continue} row.explosive = max(row.explosive, 1 - attribute.value) default: guard let row = NCDatabaseTypeInfoRow(attribute: attribute, value: nil) else {continue} rows.append(row) } } if let resistanceRow = resistanceRow { rows.append(resistanceRow) } if category == .shield { if let capacity = attributes[NCDBAttributeID.shieldCapacity.rawValue]?.value, let rechargeRate = attributes[NCDBAttributeID.shieldRechargeRate.rawValue]?.value, rechargeRate > 0 && capacity > 0 { let passive = 10.0 / (rechargeRate / 1000.0) * 0.5 * (1 - 0.5) * capacity rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "ShieldRecharge", image: #imageLiteral(resourceName: "shieldRecharge"), title: NSLocalizedString("Passive Recharge Rate", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: passive, unit: .hpPerSecond, style: .full))) } if let amount = attributes[NCDBAttributeID.entityShieldBoostAmount.rawValue]?.value, let duration = attributes[NCDBAttributeID.entityShieldBoostDuration.rawValue]?.value, duration > 0 && amount > 0 { let chance = (attributes[NCDBAttributeID.entityShieldBoostDelayChance.rawValue] ?? attributes[NCDBAttributeID.entityShieldBoostDelayChanceSmall.rawValue] ?? attributes[NCDBAttributeID.entityShieldBoostDelayChanceMedium.rawValue] ?? attributes[NCDBAttributeID.entityShieldBoostDelayChanceLarge.rawValue])?.value ?? 0 let repair = amount / (duration * (1 + chance) / 1000.0) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "ShieldBooster", image: #imageLiteral(resourceName: "shieldBooster"), title: NSLocalizedString("Repair Rate", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: repair, unit: .hpPerSecond, style: .full))) } } else if category == .armor { if let amount = attributes[NCDBAttributeID.entityArmorRepairAmount.rawValue]?.value, let duration = attributes[NCDBAttributeID.entityArmorRepairDuration.rawValue]?.value, duration > 0 && amount > 0 { let chance = (attributes[NCDBAttributeID.entityArmorRepairDelayChance.rawValue] ?? attributes[NCDBAttributeID.entityArmorRepairDelayChanceSmall.rawValue] ?? attributes[NCDBAttributeID.entityArmorRepairDelayChanceMedium.rawValue] ?? attributes[NCDBAttributeID.entityArmorRepairDelayChanceLarge.rawValue])?.value ?? 0 let repair = amount / (duration * (1 + chance) / 1000.0) rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "ArmorRepair", image: #imageLiteral(resourceName: "armorRepairer"), title: NSLocalizedString("Repair Rate", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: repair, unit: .hpPerSecond, style: .full))) } } } if rows.count > 0 { if category == .entityRewards { sections.insert(DefaultTreeSection(nodeIdentifier: String(attributeCategory.categoryID), title: sectionTitle.uppercased(), children: rows), at: 0) } else { sections.append(DefaultTreeSection(nodeIdentifier: String(attributeCategory.categoryID), title: sectionTitle.uppercased(), children: rows)) } } } return sections } } static func whInfo(type: NCDBInvType) -> Future<[TreeNode]> { return NCDatabase.sharedDatabase!.performBackgroundTask { managedObjectContext -> [TreeNode] in var rows = [TreeNode]() guard let type = (try? managedObjectContext.existingObject(with: type.objectID)) as? NCDBInvType else {return rows} guard let wh = type.wormhole else {return rows} let eveIcons = NCDBEveIcon.eveIcons(managedObjectContext: managedObjectContext) if wh.targetSystemClass >= 0 { rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "LeadsInto", image: #imageLiteral(resourceName: "systems"), title: NSLocalizedString("Leads Into", comment: "").uppercased(), subtitle: wh.targetSystemClassDisplayName)) } if wh.maxStableTime > 0 { rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MaximumStableTime", image: eveIcons["22_32_16"]?.image?.image, title: NSLocalizedString("Maximum Stable Time", comment: "").uppercased(), subtitle: NCTimeIntervalFormatter.localizedString(from: TimeInterval(wh.maxStableTime) * 60, precision: .hours))) } if wh.maxStableMass > 0 { rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MaximumStableMass", image: eveIcons["2_64_10"]?.image?.image, title: NSLocalizedString("Maximum Stable Mass", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: wh.maxStableMass, unit: .kilogram, style: .full))) } if wh.maxJumpMass > 0 { let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MaximumJumpMass", image: eveIcons["36_64_13"]?.image?.image, title: NSLocalizedString("Maximum Jump Mass", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: wh.maxJumpMass, unit: .kilogram, style: .full)) let request = NSFetchRequest<NSDictionary>(entityName: "InvType") request.predicate = NSPredicate(format: "mass <= %f AND group.category.categoryID = 6 AND published = TRUE", wh.maxJumpMass) request.sortDescriptors = [ NSSortDescriptor(key: "group.groupName", ascending: true), NSSortDescriptor(key: "typeName", ascending: true)] let entity = managedObjectContext.persistentStoreCoordinator!.managedObjectModel.entitiesByName[request.entityName!]! let propertiesByName = entity.propertiesByName var properties = [NSPropertyDescription]() properties.append(propertiesByName["typeID"]!) properties.append(propertiesByName["typeName"]!) properties.append(NSExpressionDescription(name: "icon", resultType: .objectIDAttributeType, expression: NSExpression(forKeyPath: "icon"))) properties.append(NSExpressionDescription(name: "groupName", resultType: .stringAttributeType, expression: NSExpression(forKeyPath: "group.groupName"))) request.propertiesToFetch = properties request.resultType = .dictionaryResultType let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: managedObjectContext, sectionNameKeyPath: "groupName", cacheName: nil) try? results.performFetch() if results.fetchedObjects?.isEmpty == false { row.isExpandable = true row.isExpanded = false row.children = [FetchedResultsNode(resultsController: results, sectionNode: NCDefaultFetchedResultsSectionCollapsedNode<NSDictionary>.self, objectNode: NCDatabaseTypeRow<NSDictionary>.self)] } rows.append(row) } if wh.maxRegeneration > 0 { rows.append(NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, nodeIdentifier: "MaximumMassRegeneration", image: eveIcons["23_64_3"]?.image?.image, title: NSLocalizedString("Maximum Mass Regeneration", comment: "").uppercased(), subtitle: NCUnitFormatter.localizedString(from: wh.maxRegeneration, unit: .kilogram, style: .full))) } return rows } } static func subskills(skill: NCDBInvType, character: NCCharacter) -> [NCDatabaseTypeSkillRow] { var rows = [NCDatabaseTypeSkillRow]() for requiredSkill in skill.requiredSkills?.array as? [NCDBInvTypeRequiredSkill] ?? [] { guard let type = requiredSkill.skillType else {continue} let row = NCDatabaseTypeSkillRow(skill: requiredSkill, character: character, children: subskills(skill: type, character: character)) rows.append(row) } return rows } static func requiredSkills(type: NCDBInvType, character: NCCharacter) -> NCDatabaseSkillsSection? { var rows = [TreeNode]() for requiredSkill in type.requiredSkills?.array as? [NCDBInvTypeRequiredSkill] ?? [] { guard let type = requiredSkill.skillType else {continue} let row = NCDatabaseTypeSkillRow(skill: requiredSkill, character: character, children: subskills(skill: type, character: character)) rows.append(row) } guard !rows.isEmpty else {return nil} let trainingQueue = NCTrainingQueue(character: character) trainingQueue.addRequiredSkills(for: type) return NCDatabaseSkillsSection(nodeIdentifier: String(NCDBAttributeCategoryID.requiredSkills.rawValue), title: NSLocalizedString("Required Skills", comment: "").uppercased(), trainingQueue: trainingQueue, character: character, children: rows) } static func requiredSkills(activity: NCDBIndActivity, character: NCCharacter) -> NCDatabaseSkillsSection? { var rows = [TreeNode]() for requiredSkill in activity.requiredSkills?.sortedArray(using: [NSSortDescriptor(key: "skillType.typeName", ascending: true)]) as? [NCDBIndRequiredSkill] ?? [] { guard let type = requiredSkill.skillType else {continue} let row = NCDatabaseTypeSkillRow(skill: requiredSkill, character: character, children: subskills(skill: type, character: character)) rows.append(row) } let trainingQueue = NCTrainingQueue(character: character) trainingQueue.addRequiredSkills(for: activity) return !rows.isEmpty ? NCDatabaseSkillsSection(nodeIdentifier: "RequiredSkills.\(activity.activity?.activityName ?? "")", title: NSLocalizedString("Required Skills", comment: "").uppercased(), trainingQueue: trainingQueue, character: character, children: rows) : nil } static func masteries(type: NCDBInvType, character: NCCharacter) -> TreeSection? { var masteries = [Int: [NCDBCertMastery]]() for certificate in type.certificates?.allObjects as? [NCDBCertCertificate] ?? [] { for mastery in certificate.masteries?.array as? [NCDBCertMastery] ?? [] { let level = Int(mastery.level?.level ?? 0) var array = masteries[level] ?? [] array.append(mastery) masteries[level] = array } } let unclaimedIcon = NCDBEveIcon.eveIcons(managedObjectContext: type.managedObjectContext!)[NCDBEveIcon.File.certificateUnclaimed.rawValue] var rows = [NCDatabaseTypeInfoRow]() for (key, array) in masteries.sorted(by: {return $0.key < $1.key}) { guard let level = array.first?.level else {continue} let trainingQueue = NCTrainingQueue(character: character) for mastery in array { trainingQueue.add(mastery: mastery) } let trainingTime = trainingQueue.trainingTime(characterAttributes: character.attributes) let title = NSLocalizedString("Level", comment: "").uppercased() + " \(String(romanNumber: key + 1))" let subtitle = trainingTime > 0 ? NCTimeIntervalFormatter.localizedString(from: trainingTime, precision: .seconds) : nil let icon = trainingTime > 0 ? unclaimedIcon : level.icon let row = NCDatabaseTypeInfoRow(prototype: Prototype.NCDefaultTableViewCell.attribute, image: icon?.image?.image, title: title, subtitle: subtitle, accessoryType: .disclosureIndicator, route: Router.Database.TypeMastery(typeObjectID: type.objectID, masteryLevelObjectID: level.objectID)) rows.append(row) } if rows.count > 0 { return DefaultTreeSection(nodeIdentifier: "Mastery", title: NSLocalizedString("Mastery", comment: "").uppercased(), children: rows) } else { return nil } } static func skillPlan(type: NCDBInvType, character: NCCharacter) -> TreeSection? { guard NCDBCategoryID(rawValue: Int(type.group?.category?.categoryID ?? 0)) == .skill else {return nil} var rows = [TreeRow]() for i in 1...5 { let row = NCDatabaseTrainingSkillRow(skill: type, level: i, character: character) guard row.trainingTime > 0 else {continue} rows.append(row) } guard !rows.isEmpty else {return nil} return DefaultTreeSection(nodeIdentifier: "SkillPlan", title: NSLocalizedString("Skill Plan", comment: "").uppercased(), children: rows) } }
76e56b3445104c1ce8a577fe7367baf8
45.379216
284
0.680078
false
false
false
false
vinced45/WeatherSampleiOS
refs/heads/master
WeatherKit/Models/Forecast.swift
mit
1
// // Forecast.swift // WeatherSampleiOS // // Created by Vince on 1/18/17. // Copyright © 2017 Vince Davis. All rights reserved. // import Foundation import RealmSwift @objc public class Forecast: Object { public dynamic var id = "" public dynamic var timezone = "" public dynamic var city = "" public dynamic var icon = "" public dynamic var temp = 0.0 public dynamic var windspeed = 0.0 public dynamic var humidity = 0.0 public dynamic var lat = 0.0 public dynamic var lon = 0.0 public dynamic var summary = "" public dynamic var updatedAt = Date() public dynamic var isCurrentLocation: Bool = false override public static func primaryKey() -> String? { return "id" } public func getEmoji() -> String? { switch self.icon { case "clear-day": return "☀️" case "clear-night": return "🌙" case "rain": return "🌧" case "snow": return "🌨" case "wind": return "💨" case "fog": return "🌫" case "cloudy": return "☁️" case "partly-cloudy-day": return "🌤" case "partky-cloudy-night": return "🌥" case "hail": return "❄️" case "thunderstorm": return "⛈" case "tornado": return "🌪" default: return "☀️" } } }
ed6601aa44d361249e915fac15ccf9bc
22.564516
57
0.518138
false
false
false
false
DianQK/rx-sample-code
refs/heads/master
SelectCell/User.swift
mit
1
// // User.swift // SelectCell // // Created by DianQK on 20/10/2016. // Copyright © 2016 T. All rights reserved. // import Contacts import RxSwift import RxCocoa import RxDataSources import RxExtensions struct User { let id: String let name: String let alphabet: String let isSelected: Variable<Bool> } typealias UserSectionModel = SectionModel<String, User> /// 获取用户 func getUsers() -> Observable<[User]> { return Observable.just(CNContactStore(), scheduler: SerialDispatchQueueScheduler(qos: .background)) .flatMap(requestAccess) .map(fetchContacts) .map(convertContactsToUsers) .observeOn(MainScheduler.instance) } /// 请求获取通讯录权限 let requestAccess: (CNContactStore) -> Observable<CNContactStore> = { store in return Observable<CNContactStore> .create { (observer) -> Disposable in if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined { store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) -> Void in if authorized { observer.on(.next(store)) observer.on(.completed) } else if let error = error { observer.on(.error(error)) } }) } else if CNContactStore.authorizationStatus(for: .contacts) == .authorized { observer.on(.next(store)) observer.on(.completed) } return Disposables.create() } } /// 拉取通讯录 let fetchContacts: (CNContactStore) throws -> [CNContact] = { store in let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor] let allContainers = try store.containers(matching: nil) let result = try allContainers.flatMap { (container) -> [CNContact] in let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier) return try store.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch) } return result } /// 将 CNContact 转换成 User let convertContactsToUsers: ([CNContact]) -> [User] = { contacts in contacts .filter { !$0.givenName.isEmpty } .map { contact in let name = contact.familyName.isEmpty ? contact.givenName : (contact.familyName + contact.givenName) return User(id: contact.identifier, name: name, alphabet: name.mandarinLatin.uppercased().first!, isSelected: Variable(false)) } } /// 将 Users 转换成 UserSectionModels let convertUsersToSections: ([User]) -> [UserSectionModel] = { users in users .sorted(by: { (l, r) -> Bool in l.alphabet <= r.alphabet }) .reduce([UserSectionModel](), { (acc, x) in if var last = acc.last, x.alphabet.hasPrefix(last.model) { last.items.append(x) return acc.dropLast() + [last] } else { return acc + [UserSectionModel(model: x.alphabet, items: [x])] } }) } let combineSelectedUsersInfo: ([User]) -> String = { users in combineUsersInfo(users.filter { $0.isSelected.value }) } let combineUsersInfo: ([User]) -> String = { users in users.map { $0.name }.joined(separator: ",") } extension String { var mandarinLatin: String { let mutableString = NSMutableString(string: self) as CFMutableString CFStringTransform(mutableString, nil, kCFStringTransformMandarinLatin, false) return mutableString as String } } extension String { var first: String? { return substring(to: index(after: startIndex)) } }
a6bc771f99fd6b57535069120be8d0aa
32.927928
174
0.637281
false
false
false
false
zane001/ZMTuan
refs/heads/master
ZMTuan/View/Home/DiscountCell.swift
mit
1
// // DiscountCell.swift // ZMTuan // // Created by zm on 4/18/16. // Copyright © 2016 zm. All rights reserved. // 折扣View import UIKit protocol DiscountDelegate { func didSelectUrl(urlStr: String, withType type: NSNumber, withId ID: NSNumber, withTitle title: String) } class DiscountCell: UITableViewCell { var array: NSMutableArray? // var discountArray: NSMutableArray? var delegate: DiscountDelegate? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) array = NSMutableArray() for i in 0 ..< 4 { // 背景 let backView: UIView = UIView(frame: CGRectMake(CGFloat(i)*SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 80)) if i<2 { backView.frame = CGRectMake(CGFloat(i)*SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 80) } else { backView.frame = CGRectMake(CGFloat(i-2)*SCREEN_WIDTH/2, 80, SCREEN_WIDTH/2, 80) } backView.tag = 100 + i backView.layer.borderWidth = 0.25 backView.layer.borderColor = separaterColor.CGColor self.addSubview(backView) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DiscountCell.onTapBackView(_:))) backView.addGestureRecognizer(tap) // 标题 let titleLabel: UILabel = UILabel(frame: CGRectMake(10, 20, SCREEN_WIDTH/2-10-60, 30)) titleLabel.tag = 200 + i titleLabel.font = UIFont.systemFontOfSize(17) backView.addSubview(titleLabel) // 子标题 let subtitleLabel: UILabel = UILabel(frame: CGRectMake(10, 40, SCREEN_WIDTH/2-10-60, 30)) subtitleLabel.tag = 220 + i subtitleLabel.font = UIFont.systemFontOfSize(12) backView.addSubview(subtitleLabel) // 图片 let imageView: UIImageView = UIImageView(frame: CGRectMake(SCREEN_WIDTH/2-10-60, 10, 60, 60)) imageView.tag = 240 + i let image: UIImage = UIImage(named: "bg_customReview_image_default")! imageView.image = image imageView.layer.masksToBounds = true imageView.layer.cornerRadius = 30 backView.addSubview(imageView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setDiscountArray(discountArray: NSMutableArray) { // let array = NSMutableArray() // for i in 0 ..< discountArray.count { // let discount: DiscountModel = discountArray[i] as! DiscountModel // let num: NSNumber = NSNumber(long: 1) // if discount.type.isEqualToValue(num) { // array.addObject(discount) // } // } self.array = discountArray for j in 0 ..< 4 { let titleLabel = self.viewWithTag(200 + j) as! UILabel let subtitleLabel = self.viewWithTag(220 + j) as! UILabel let imageView = self.viewWithTag(240 + j) as! UIImageView let discount: DiscountModel = self.array![j] as! DiscountModel titleLabel.text = discount.maintitle if discount.typeface_color != nil { titleLabel.textColor = self.stringToColor(discount.typeface_color) } subtitleLabel.text = discount.deputytitle if discount.imageurl != nil { let imageUrl = discount.imageurl.stringByReplacingOccurrencesOfString("w.h", withString: "120.0") imageView.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "bg_customReview_image_default")) } } } // 将字符串 #ff1234 转换为颜色 func stringToColor(str: String) -> UIColor { let aStr = str.substringFromIndex(str.startIndex.advancedBy(1)) var range: NSRange = NSMakeRange(0, 2) let rString = (aStr as NSString).substringWithRange(range) range.location = 2 let gString = (aStr as NSString).substringWithRange(range) range.location = 4 let bString = (aStr as NSString).substringWithRange(range) var r: UInt32 = 0x0 var g: UInt32 = 0x0 var b: UInt32 = 0x0 NSScanner.init(string: rString).scanHexInt(&r) NSScanner.init(string: gString).scanHexInt(&g) NSScanner.init(string: bString).scanHexInt(&b) let color = UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1) // print("str: \(str)") // print("red: \(r), green: \(g), blue: \(b)") return color } func onTapBackView(sender: UITapGestureRecognizer) { let index = (sender.view?.tag)! - 100 let discount = self.array![index] as? DiscountModel var str = "" let num = NSNumber(long: 1) if ((discount?.type.isEqualToValue(num)) != nil) { str = (discount?.tplurl)! let range = str.rangeOfString("http") if range != nil { str = str.substringFromIndex(range!.startIndex) } print(str) } self.delegate?.didSelectUrl(str, withType: (discount?.type)!, withId: (discount?.id)!, withTitle: (discount?.maintitle)!) } 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 } }
5156ca02278380b3f7180e6342f24418
36.094937
136
0.579253
false
false
false
false
darrylwest/saguaro-data-model
refs/heads/master
SaguaroDataModel/SAValidationDelegate.swift
mit
1
// // SAValidationDelegate.swift // SaguaroDataModel // // Created by darryl west on 7/23/15. // Copyright © 2015 darryl west. All rights reserved. // import Foundation infix operator =~ public func =~ (value : String, pattern : String) -> SARegexMatchResult { let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange) let options : NSRegularExpression.Options = [] do { let re = try NSRegularExpression(pattern: pattern, options: options) let all = NSRange(location: 0, length: nsstr.length) var matches : Array<String> = [] re.enumerateMatches(in: value, options: [], range: all) { (result, flags, ptr) -> Void in guard let result = result else { return } let string = nsstr.substring(with: result.range) matches.append(string) } return SARegexMatchResult(items: matches) } catch { return SARegexMatchResult(items: []) } } public func =~ (value : String, pattern : String) -> Bool { return (=~)(value, pattern).boolValue } public struct SARegexMatchCaptureGenerator : IteratorProtocol { public var items: ArraySlice<String> public mutating func next() -> String? { if items.isEmpty { return nil } else { let ret = items.remove( at: 0 ) return ret } } } public struct SARegexMatchResult : Sequence { var items: Array<String> public func makeIterator() -> SARegexMatchCaptureGenerator { return SARegexMatchCaptureGenerator(items: items[0..<items.count]) } public var boolValue: Bool { return items.count > 0 } public subscript (i: Int) -> String { return items[i] } } public protocol SAMinMaxRangeType { var min:Int { get } var max:Int { get } func isValid(_ value:Int) -> Bool func isValid(_ value:String) -> Bool } public struct SAMinMaxRange: SAMinMaxRangeType { public let min:Int public let max:Int public func isValid(_ value:Int) -> Bool { return (value >= self.min && value <= self.max) } public func isValid(_ value:String) -> Bool { return isValid( value.characters.count ) } public init(min:Int, max:Int) { self.min = min self.max = max } } // TODO... // because swift 2.0 strings are not compatible with NSRegularExpressions, it might // be a better idea to use straight logic for validation. public struct SARegExPatterns { static public let Email = "[A-Za-z._%+=]+@[A-Za-z0-9]+\\.[A-Za-z]{2,6}" // "\\w+@\\w.\\w" } open class SAValidationDelegate { open let passwordMinMax:SAMinMaxRangeType public init(passwordMinMax:SAMinMaxRangeType? = SAMinMaxRange(min: 4, max: 40)) { self.passwordMinMax = passwordMinMax! } open func isEmail(_ value: String) -> Bool { let matches: SARegexMatchResult = value =~ SARegExPatterns.Email return matches.boolValue } open func isValidUsername(_ username:String) -> Bool { return isEmail(username) } /// password strings are between 4 and 20 characters, so just test length open func isValidPassword(_ password:String) -> Bool { return passwordMinMax.isValid( password ) } }
93a85ab50eeb8c1e063d75803063b3a2
26.479339
125
0.635489
false
false
false
false
dreamsxin/swift
refs/heads/master
test/Interpreter/currying_generics.swift
apache-2.0
3
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test func curry<T, U, V>(_ f: (T, U) -> V) -> (T) -> (U) -> V { return { x in { y in f(x, y) } } } func curry<T1, T2, T3, T4>(_ f: (T1, T2, T3) -> T4) -> (T1) -> (T2) -> (T3) -> T4 { return { x in { y in { z in f(x, y, z) } } } } func concat(_ x: String, _ y: String, _ z: String) -> String { return x + y + z } @inline(never) public func test_concat_closure(_ x: Int) -> String { var x = x let insult = curry(concat)("one ")(" two ") var gs = insult(" three ") if (x > 0) { gs = gs + insult(" four ") gs = gs + insult(" five ") } else { gs = gs + insult(" six ") gs = gs + insult(" seven ") } if (x > 10) { x += 100 } return gs } public protocol P { func val() -> Int32 } struct CP: P { let v: Int32 func val() -> Int32 { return v } init(_ v: Int32) { self.v = v } } func compose(_ x: P, _ y: P, _ z: P) -> Int32 { return x.val() + y.val() + z.val() } @inline(never) public func test_compose_closure(_ x: Int) -> Int32 { var x = x let insult = curry(compose)(CP(1))(CP(2)) var gs = insult(CP(3)) if (x > 0) { gs = gs + insult(CP(4)) gs = gs + insult(CP(5)) } else { gs = gs + insult(CP(6)) gs = gs + insult(CP(7)) } if (x > 10) { x += 100 } return gs } let insult = curry(+)("I'm with stupid ☞ ") print(insult("😡")) // CHECK: I'm with stupid ☞ 😡 let plus1 = curry(+)(1) print(plus1(5)) // CHECK-NEXT: 6 let plus5 = curry(+)(5) print(plus5(5)) // CHECK-NEXT: 10 print(insult("😰")) // CHECK-NEXT: I'm with stupid ☞ 😰 let concat_one_two = curry(concat)("one ")(" two ") print(concat_one_two(" three ")) // CHECK-NEXT: one two three print(test_concat_closure(20)) // CHECK-NEXT: one two three one two four one two five print(test_compose_closure(20)) // CHECK-NEXT: 21 // rdar://problem/18988428 func clamp<T: Comparable>(_ minValue: T, _ maxValue: T) -> (n: T) -> T { return { n in max(minValue, min(n, maxValue)) } } let clampFoo2 = clamp(10.0, 30.0) print(clampFoo2(n: 3.0)) // CHECK-NEXT: 10.0 // rdar://problem/19195470 func pair<T,U> (_ a: T) -> (U) -> (T,U) { return { b in (a,b) } } func pair_<T,U> (_ a: T) -> (b: U) -> (T,U) { return { b in (a,b) } } infix operator <+> { } func <+><T,U,V> (lhs: T?, rhs: (T) -> (U) -> V) -> (U) -> V? { if let x = lhs { return { y in .some(rhs(x)(y)) } } else { return { _ in nil } } } let a : Int? = 23 let b : Int? = 42 print((b <+> pair)(a!)) // CHECK-NEXT: (42, 23) print((b <+> pair_)(a!)) // CHECK-NEXT: (42, 23) // // rdar://problem/20475584 // struct Identity<A> { let value: A } struct Const<A, B> { let value: A } func fmap<A, B>(_ f: (A) -> B) -> (Identity<A>) -> Identity<B> { return { identity in Identity(value: f(identity.value)) } } func fmap<A, B>(_ f: (A) -> B) -> (Const<A, B>) -> Const<A, B> { return { const in const } } // really Const() func _Const<A, B>(_ a: A) -> Const<A, B> { return Const(value: a) } func const<A, B>(_ a: A) -> (B) -> A { return { _ in a } } // really Identity() func _Identity<A>(_ a: A) -> Identity<A> { return Identity(value: a) } func getConst<A, B>(_ c: Const<A, B>) -> A { return c.value } func runIdentity<A>(_ i: Identity<A>) -> A { return i.value } func view<S, A>(_ lens: ((A) -> Const<A, S>) -> (S) -> (((A) -> S) -> (Const<A, S>) -> Const<A, S>) -> Const<A, S>) -> (S) -> A { return { s in getConst(lens(_Const)(s)(fmap)) } } func over<S, A>(_ lens: ((A) -> Identity<A>) -> (S) -> (((A) -> S) -> (Identity<A>) -> Identity<S>) -> Identity<S>) -> ((A) -> A) -> (S) -> S { return { f in { s in runIdentity(lens({ _Identity(f($0)) })(s)(fmap)) } } } func set<S, A>(_ lens: ((A) -> Identity<A>) -> (S) -> (((A) -> S) -> (Identity<A>) -> Identity<S>) -> Identity<S>) -> (A) -> (S) -> S { return { x in { y in over(lens)(const(x))(y) } } } func _1<A, B, C, D>(_ f: (A) -> C) -> (A, B) -> (((A) -> (A, B)) -> (C) -> D) -> D { return { (x, y) in { fmap in fmap({ ($0, y) })(f(x)) } } } func _2<A, B, C, D>(_ f: (B) -> C) -> (A, B) -> (((B) -> (A, B)) -> (C) -> D) -> D { return { (x, y) in { fmap in fmap({ (x, $0) })(f(y)) } } } public func >>> <T, U, V> (f: (T) -> U, g: (U) -> V) -> (T) -> V { return { g(f($0)) } } public func <<< <T, U, V> (f: (U) -> V, g: (T) -> U) -> (T) -> V { return { f(g($0)) } } infix operator >>> { associativity right precedence 170 } infix operator <<< { associativity right precedence 170 } let pt1 = view(_1)((1, 2)) print(pt1) // CHECK-NEXT: 1 let pt2 = over(_1)({ $0 * 4 })((1, 2)) print(pt2) // CHECK-NEXT: (4, 2) let pt3 = set(_1)(3)((1, 2)) print(pt3) // CHECK-NEXT: (3, 2) let pt4 = view(_2)("hello", 5) print(pt4) // CHECK-NEXT: 5
358d26d12f93acd93d50e230fcf00337
21.519048
143
0.499048
false
false
false
false
aestesis/Aether
refs/heads/master
Project/sources/Services/Amazon.swift
apache-2.0
1
// // Amazon.swift // Alib // // Created by renan jegouzo on 08/03/2017. // Copyright © 2017 aestesis. All rights reserved. // import Foundation // doc: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/ItemSearch.html // sign: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html // try sign: http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html public class Amazon { public static var key = "" public static var secret = "" public static var tag = "" static let service="http://webservices.amazon.com/onca/xml?" static let apiSearch="Service=AWSECommerceService&AWSAccessKeyId=$key&AssociateTag=$tag&Operation=ItemSearch&Keywords=$query&SearchIndex=Music&Timestamp=$time" public static func searchArtist(name:String,fn:@escaping ((Any?)->())) { var api = apiSearch api = api.replacingOccurrences(of:"$query",with:rfc3986(name)) api = api.replacingOccurrences(of:"$key",with:key) api = api.replacingOccurrences(of:"$tag",with:tag) api = api.replacingOccurrences(of:"$time",with:rfc3986(ß.dateISO8601)) //Debug.warning("amamzon unsigned request: "+service+api) api = api.split("&").sorted { a,b -> Bool in return a<b }.joined(separator:"&") let st = "GET\nwebservices.amazon.com\n/onca/xml\n"+api let signature = Crypto.hmacSHA256(string:st,key:secret).addingPercentEncoding(withAllowedCharacters:.alphanumerics)! let url = service+api+"&Signature=\(signature)" //Debug.warning("Amazon: request \(url)") Web.getText(url) { r in let btag = "<MoreSearchResultsUrl>" let etag = "</MoreSearchResultsUrl>" if let text = r as? String, let b = text.indexOf(btag), let e = text.indexOf(etag), b<e { let url = text[(b+btag.length)..<e].trim().replacingOccurrences(of:"&amp;",with:"&") //Debug.warning("amazon: \(url)") fn(url) } else if let err = r as? Error { fn(Error(err)) } else { fn(Error("bad amazon response")) } } /* Web.getXML(url, { r in if let xdoc = r as? AEXMLDocument { Debug.warning("Amazon: response: \(xdoc.xml)") fn(xdoc) } else if let err = r as? Alib.Error { Debug.warning("Amazon: error: \(err)") fn(Error(err)) } }) */ } static func rfc3986(_ s:String) -> String { // RFC 3986 let allowed = NSMutableCharacterSet.alphanumeric() allowed.addCharacters(in: "-._~/?") return s.addingPercentEncoding(withAllowedCharacters:allowed as CharacterSet)! } public static func setCredentials(key:String,secret:String,tag:String) { Amazon.key = key Amazon.secret = secret Amazon.tag = tag } }
3ade400a26d348d35889debe23a29e8b
40.901408
163
0.598319
false
false
false
false
poetmountain/MotionMachine
refs/heads/master
Sources/ValueAssistants/UIColorAssistant.swift
mit
1
// // UIColorAssistant.swift // MotionMachine // // Created by Brett Walker on 5/18/16. // Copyright © 2016-2018 Poet & Mountain, LLC. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import UIKit /// UIColorAssistant provides support for the `UIColor` type. public class UIColorAssistant : ValueAssistant { public var additive: Bool = false public var additiveWeighting: Double = 1.0 { didSet { // constrain weighting to range of 0.0 - 1.0 additiveWeighting = max(min(additiveWeighting, 1.0), 0.0) } } public required init() {} // MARK: ValueAssistant methods public func generateProperties(targetObject target: AnyObject, propertyStates: PropertyStates) throws -> [PropertyData] { var properties: [PropertyData] = [] if (propertyStates.end is UIColor) { let new_color = propertyStates.end as! UIColor var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0 var white: CGFloat = 0.0, walpha: CGFloat = 0.0 var add_hue = false var add_sat = false var add_brightness = false var add_alpha = false var add_red = false var add_green = false var add_blue = false var add_white = false var ocolor: UIColor? // first check if target is a UIColor, and if so use that as the ocolor base if (target is UIColor) { ocolor = target as? UIColor } // if there's a start value in the PropertyStates object and it's a UIColor then use that instead if let unwrapped_start = propertyStates.start { if (propertyStates.start is UIColor) { ocolor = unwrapped_start as? UIColor } } var ohue: CGFloat = 0.0, osaturation: CGFloat = 0.0, obrightness: CGFloat = 0.0, oalpha: CGFloat = 0.0 var ored: CGFloat = 0.0, ogreen: CGFloat = 0.0, oblue: CGFloat = 0.0 var owhite: CGFloat = 0.0, owalpha: CGFloat = 0.0 if (ocolor != nil) { ocolor!.getHue(&ohue, saturation: &osaturation, brightness: &obrightness, alpha: &oalpha) ocolor!.getRed(&ored, green: &ogreen, blue: &oblue, alpha: &oalpha) ocolor!.getWhite(&owhite, alpha: &owalpha) } new_color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) new_color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) new_color.getWhite(&white, alpha: &walpha) if (ocolor != nil) { // check each component to avoid building PropertyData objects for color components whose start and end values are the same if (Double(red) !≈ Double(ored)) { add_red = true } if (Double(blue) !≈ Double(oblue)) { add_blue = true } if (Double(green) !≈ Double(ogreen)) { add_green = true } if (!add_red && !add_green && !add_blue) { if (Double(hue) !≈ Double(ohue)) { add_hue = true } if (Double(saturation) !≈ Double(osaturation)) { add_sat = true } if (Double(brightness) !≈ Double(obrightness)) { add_brightness = true } } if (Double(alpha) !≈ Double(oalpha)) { add_alpha = true } // setting white stomps on other color changes so only add white prop if nothing else (other than alpha) is changing if (!add_red && !add_green && !add_blue && !add_hue && !add_sat && !add_brightness) { if (Double(white) !≈ Double(owhite)) { add_white = true } } } if (add_hue) { let p = PropertyData(path: "hue", start: Double(ohue), end: Double(hue)) properties.append(p) } if (add_sat) { let p = PropertyData(path: "saturation", start: Double(osaturation), end: Double(saturation)) properties.append(p) } if (add_brightness) { let p = PropertyData(path: "brightness", start: Double(obrightness), end: Double(brightness)) properties.append(p) } if (add_alpha) { let p = PropertyData(path: "alpha", start: Double(oalpha), end: Double(alpha)) properties.append(p) } if (add_red) { let p = PropertyData(path: "red", start: Double(ored), end: Double(red)) properties.append(p) } if (add_green) { let p = PropertyData(path: "green", start: Double(ogreen), end: Double(green)) properties.append(p) } if (add_blue) { let p = PropertyData(path: "blue", start: Double(oblue), end: Double(blue)) properties.append(p) } if (add_white) { let p = PropertyData(path: "white", start: Double(owhite), end: Double(white)) properties.append(p) } if (target is UIColor) { for index in 0 ..< properties.count { properties[index].target = target } } } if (propertyStates.path != "") { for index in 0 ..< properties.count { if (properties[index].path != "") { properties[index].path = propertyStates.path + "." + properties[index].path } else { properties[index].path = propertyStates.path } } } return properties } public func retrieveCurrentObjectValue(forProperty property: PropertyData) -> Double? { guard let unwrapped_target = property.target else { return nil } var object_value :Double? if let unwrapped_object = property.targetObject { // BEWARE, THIS BE UNSAFE MUCKING ABOUT // this would normally be in a do/catch but unfortunately Swift can't catch exceptions from Obj-C methods typealias GetterFunction = @convention(c) (AnyObject, Selector) -> AnyObject let implementation: IMP = unwrapped_object.method(for: property.getter!) let curried = unsafeBitCast(implementation, to: GetterFunction.self) let obj = curried(unwrapped_object, property.getter!) object_value = retrieveValue(inObject: obj as! NSObject, keyPath: property.path) } else if (unwrapped_target is UIColor) { object_value = retrieveValue(inObject: unwrapped_target as! NSObject, keyPath: property.path) } return object_value } public func retrieveValue(inObject object: Any, keyPath path: String) -> Double? { var retrieved_value: Double? if (object is UIColor) { let color = object as! UIColor var hue: CGFloat = 0, saturation: CGFloat = 0, brightness: CGFloat = 0, alpha: CGFloat = 0 var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, white: CGFloat = 0 color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) color.getWhite(&white, alpha: &alpha) let last_component = lastComponent(forPath: path) if (last_component == "hue") { retrieved_value = Double(hue) } else if (last_component == "saturation") { retrieved_value = Double(saturation) } else if (last_component == "brightness") { retrieved_value = Double(brightness) } else if (last_component == "alpha") { retrieved_value = Double(alpha) } else if (last_component == "red") { retrieved_value = Double(red) } else if (last_component == "green") { retrieved_value = Double(green) } else if (last_component == "blue") { retrieved_value = Double(blue) } else if (last_component == "white") { retrieved_value = Double(blue) } } return retrieved_value } public func updateValue(inObject object: Any, newValues: Dictionary<String, Double>) -> NSObject? { guard newValues.count > 0 else { return nil } var new_parent_value:NSObject? if (object is UIColor) { let color = object as! UIColor var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, white: CGFloat = 0.0 var new_color = color for (prop, newValue) in newValues { var changed = CGFloat(newValue) new_color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) new_color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) new_color.getWhite(&white, alpha: &alpha) let last_component = lastComponent(forPath: prop) if (last_component == "hue") { if (additive) { changed = hue + changed } new_color = UIColor.init(hue: changed, saturation: saturation, brightness: brightness, alpha: alpha) } if (last_component == "saturation") { if (additive) { changed = saturation + changed } new_color = UIColor.init(hue: hue, saturation: changed, brightness: brightness, alpha: alpha) } if (last_component == "brightness") { if (additive) { changed = brightness + changed } new_color = UIColor.init(hue: hue, saturation: saturation, brightness: changed, alpha: alpha) } if (last_component == "alpha") { if (additive) { changed = alpha + changed } new_color = UIColor.init(hue: hue, saturation: saturation, brightness: brightness, alpha: changed) } if (last_component == "red") { if (additive) { changed = red + changed } new_color = UIColor.init(red: changed, green: green, blue: blue, alpha: alpha) } if (last_component == "green") { if (additive) { changed = green + changed } new_color = UIColor.init(red: red, green: changed, blue: blue, alpha: alpha) } if (last_component == "blue") { if (additive) { changed = blue + changed } new_color = UIColor.init(red: red, green: green, blue: changed, alpha: alpha) } if (last_component == "white") { if (additive) { changed = white + changed } new_color = UIColor.init(white: changed, alpha: alpha) } } new_parent_value = new_color } return new_parent_value } public func calculateValue(forProperty property: PropertyData, newValue: Double) -> NSObject? { guard let unwrapped_target = property.target else { return nil } var new_prop: NSObject? = NSNumber.init(value: property.current) if let unwrapped_object = property.targetObject { // we have a normal object whose property is being changed if (unwrapped_target is UIColor) { var new_property_value = property.current if (additive) { new_property_value = newValue } // replace the top-level struct of the property we're trying to alter // e.g.: keyPath is @"frame.origin.x", so we replace "frame" because that's the closest KVC-compliant prop if let base_prop = unwrapped_object.value(forKeyPath: property.parentKeyPath) { let new_color = updateValue(inObject: (base_prop as! NSObject), newValues: [property.path : new_property_value]) as! UIColor new_prop = new_color // BEWARE, THIS BE UNSAFE MUCKING ABOUT // this would normally be in a do/catch but unfortunately Swift can't catch exceptions from Obj-C methods // letting the runtime know about result and argument types typealias SetterFunction = @convention(c) (AnyObject, Selector, UIColor) -> Void let implementation: IMP = unwrapped_object.method(for: property.setter!) let curried = unsafeBitCast(implementation, to: SetterFunction.self) curried(unwrapped_object, property.setter!, new_color) } } return new_prop } // we have no base object, so we must be changing the UIColor directly if (unwrapped_target is UIColor) { var new_property_value = property.current if (additive) { new_property_value = newValue } let new_color = updateValue(inObject: (unwrapped_target as! NSObject), newValues: [property.path : new_property_value]) as! UIColor new_prop = new_color } return new_prop } public func supports(_ object: AnyObject) -> Bool { var is_supported: Bool = false if (object is UIColor) { is_supported = true } return is_supported } public func acceptsKeypath(_ object: AnyObject) -> Bool { return false } }
600ae94bf9daf2c546f539b24d40b160
40.638961
144
0.528289
false
false
false
false
fgengine/quickly
refs/heads/master
Quickly/Extensions/CGRect.swift
mit
1
// // Quickly // public extension CGRect { var topLeftPoint: CGPoint { get { return CGPoint(x: self.minX, y: self.minY) } } var topPoint: CGPoint { get { return CGPoint(x: self.midX, y: self.minY) } } var topRightPoint: CGPoint { get { return CGPoint(x: self.maxX, y: self.minY) } } var centerLeftPoint: CGPoint { get { return CGPoint(x: self.minX, y: self.midY) } } var centerPoint: CGPoint { get { return CGPoint(x: self.midX, y: self.midY) } } var centerRightPoint: CGPoint { get { return CGPoint(x: self.maxX, y: self.midY) } } var bottomLeftPoint: CGPoint { get { return CGPoint(x: self.minX, y: self.maxY) } } var bottomPoint: CGPoint { get { return CGPoint(x: self.midX, y: self.maxY) } } var bottomRightPoint: CGPoint { get { return CGPoint(x: self.maxX, y: self.maxY) } } func lerp(_ to: CGRect, progress: CGFloat) -> CGRect { return CGRect( x: self.origin.x.lerp(to.origin.x, progress: progress), y: self.origin.y.lerp(to.origin.y, progress: progress), width: self.size.width.lerp(to.size.width, progress: progress), height: self.size.height.lerp(to.size.height, progress: progress) ) } func aspectFit(size: CGSize) -> CGRect { let iw = floor(size.width) let ih = floor(size.height) let bw = floor(self.size.width) let bh = floor(self.size.height) let fw = bw / iw let fh = bh / ih let sc = (fw < fh) ? fw : fh let rw = iw * sc let rh = ih * sc let rx = (bw - rw) / 2 let ry = (bh - rh) / 2 return CGRect( x: self.origin.x + rx, y: self.origin.y + ry, width: rw, height: rh ) } func aspectFill(size: CGSize) -> CGRect { let iw = floor(size.width) let ih = floor(size.height) let bw = floor(self.size.width) let bh = floor(self.size.height) let fw = bw / iw let fh = bh / ih let sc = (fw > fh) ? fw : fh let rw = iw * sc let rh = ih * sc let rx = (bw - rw) / 2 let ry = (bh - rh) / 2 return CGRect( x: self.origin.x + rx, y: self.origin.y + ry, width: rw, height: rh ) } }
b493614c899389f9ef3135eb53e9d93e
28.011905
77
0.513746
false
false
false
false
appsandwich/PullToRefreshView
refs/heads/master
PullToRefreshView.swift
mit
1
// // PullToRefreshView.swift // PullToRefreshView // // Created by Vinny Coyne on 21/04/2017. // Copyright © 2017 App Sandwich Limited. All rights reserved. // import UIKit class PullToRefreshView: UIView, UIGestureRecognizerDelegate { private weak var tableView: UITableView? = nil private var performingReset: Bool = false private var insetsLocked: Bool = false internal var touchesActive: Bool = false private var refreshActivityCount: Int = 0 static var ptrViewHeight: CGFloat = 80.0 public var contentView: UIView public var spinnerView: UIActivityIndicatorView internal var refreshDidStartHandler: ((PullToRefreshView) -> Void)? = nil public var refreshDidStartAnimationHandler: ((PullToRefreshView) -> Void)? = nil public var refreshDidStopAnimationHandler: ((PullToRefreshView) -> Void)? = nil override init(frame: CGRect) { self.contentView = UIView(frame: frame) self.spinnerView = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.spinnerView.hidesWhenStopped = false self.contentView.addSubview(self.spinnerView) super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.refreshDidStartHandler = nil self.refreshDidStopAnimationHandler = nil self.refreshDidStartAnimationHandler = nil guard let tv = self.tableView else { return } tv.removeObserver(self, forKeyPath: #keyPath(UITableView.contentOffset)) self.tableView = nil } override func didMoveToSuperview() { super.didMoveToSuperview() self.addSubview(self.contentView) self.tableView = nil guard let tv = self.superview, tv is UITableView else { return } self.tableView = tv as? UITableView self.installObservers() } override func layoutSubviews() { super.layoutSubviews() guard let tv = self.tableView else { return } self.bounds = CGRect(x: 0.0, y: 0.0, width: tv.bounds.width, height: self.bounds.height) self.contentView.frame = CGRect(x: 0.0, y: 0.0, width: tv.bounds.width, height: self.bounds.height) self.spinnerView.center = CGPoint(x: self.contentView.bounds.width / 2.0, y: self.contentView.bounds.height / 2.0) } // MARK: - Private private func handleScrollToOffset(_ offset: CGPoint) { guard offset.y < 0.0 else { return } let absoluteOffset = abs(offset.y) let ratio = absoluteOffset / self.bounds.height self.contentView.alpha = ratio > 1.0 ? 1.0 : ratio self.contentView.layer.transform = CATransform3DMakeScale(ratio, ratio, 1.0) guard self.touchesActive == false, self.insetsLocked == false, absoluteOffset > self.bounds.height else { return } self.spinnerView.startAnimating() self.insetsLocked = self.lockTableViewInsets() if let handler = self.refreshDidStartHandler { handler(self) } if let animationHandler = self.refreshDidStartAnimationHandler { animationHandler(self) } } // MARK: Insets private func lockTableViewInsets() -> Bool { guard let tv = self.tableView else { return false } tv.contentInset.top = self.bounds.height return true } private func resetTableViewInsets() { self.insetsLocked = false guard let tv = self.tableView else { return } let rect = CGRect(x: 0.0, y: tv.bounds.height, width: 1.0, height: 1.0) self.performingReset = true tv.scrollRectToVisible(rect, animated: true) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { guard self.refreshActivityCount == 0 else { return } tv.contentInset.top = 0.0 self.performingReset = false } } // MARK: Balance start/end refresh calls. private func incrementRefreshActivity() -> Int { self.refreshActivityCount += 1 return self.refreshActivityCount } private func decrementRefreshActivity() -> Int { guard self.refreshActivityCount > 0 else { return 0 } self.refreshActivityCount -= 1 return self.refreshActivityCount } private func resetRefreshActivities() { self.refreshActivityCount = 0 } // MARK: KVO private func installObservers() { guard let tv = self.tableView else { return } tv.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: [.new], context: nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard self.performingReset == false, self.tableView != nil else { return } if keyPath == #keyPath(UITableView.contentOffset) { if let dict = change { if let newPoint = dict[NSKeyValueChangeKey.newKey], newPoint is CGPoint { let offset = newPoint as! CGPoint self.handleScrollToOffset(offset) } } } } // MARK: - Pan gesture delegate func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // MARK: - Public public func beginRefreshing() { if 1 == self.incrementRefreshActivity() { self.insetsLocked = self.lockTableViewInsets() self.tableView?.setContentOffset(CGPoint(x: 0.0, y: -PullToRefreshView.ptrViewHeight), animated: true) self.spinnerView.startAnimating() if let animationHandler = self.refreshDidStartAnimationHandler { animationHandler(self) } } } public func endRefreshing(force: Bool = false) { if force { self.refreshActivityCount = 1 } if 0 == self.decrementRefreshActivity() { self.resetTableViewInsets() self.spinnerView.stopAnimating() if let animationHandler = self.refreshDidStopAnimationHandler { animationHandler(self) } } } // MARK: - Class methods class func pullToRefreshView() -> PullToRefreshView { return PullToRefreshView(frame: CGRect(x: 0.0, y: -self.ptrViewHeight, width: UIScreen.main.bounds.width, height: self.ptrViewHeight)) } } // MARK: - UITableView extensions extension UITableView { func installPullToRefreshViewWithHandler(_ handler: ((PullToRefreshView) -> Void)?) { guard self.pullToRefreshView() == nil else { self.pullToRefreshView()?.refreshDidStartHandler = handler return } let pullToRefreshView = PullToRefreshView.pullToRefreshView() pullToRefreshView.refreshDidStartHandler = handler self.addSubview(pullToRefreshView) let panGesture = UIPanGestureRecognizer(target: self, action: #selector(UITableView.handlePTRPanGesture(_:))) panGesture.maximumNumberOfTouches = 1 panGesture.minimumNumberOfTouches = 1 panGesture.delegate = pullToRefreshView self.addGestureRecognizer(panGesture) } func pullToRefreshView() -> PullToRefreshView? { var pullToRefreshView: PullToRefreshView? = nil pullToRefreshView = self.subviews.first(where: { (subview) -> Bool in return subview is PullToRefreshView }) as? PullToRefreshView return pullToRefreshView } func handlePTRPanGesture(_ panGesture: UIPanGestureRecognizer) { switch panGesture.state { case .began: fallthrough case .changed: self.pullToRefreshView()?.touchesActive = true break case .cancelled: fallthrough case .failed: fallthrough case .ended: fallthrough case .possible: self.pullToRefreshView()?.touchesActive = false break } } }
2aa6ad870fac64a1c5dcd54fb3f48950
28.311897
157
0.580518
false
false
false
false
ElijahButers/Swift
refs/heads/master
CoreDataSample2/CoreDataSample2/ViewController.swift
gpl-3.0
26
// // ViewController.swift // CoreDataSample2 // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var results: NSArray? @IBOutlet weak var name: UITextField! @IBOutlet weak var surname: UITextField! @IBOutlet weak var table: UITableView! @IBAction func save(sender: UIButton) { var appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var context: NSManagedObjectContext = appDel.managedObjectContext! var cell = NSEntityDescription.insertNewObjectForEntityForName("Form", inManagedObjectContext: context) as! NSManagedObject cell.setValue(name.text, forKey: "name") cell.setValue(surname.text, forKey: "surname") context.save(nil) if(!context.save(nil)){ println("Error!") } self.loadTable() self.table.reloadData() } override func viewDidLoad() { super.viewDidLoad() self.loadTable() //start load } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell : UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Subtitle, reuseIdentifier: nil) var aux = results![indexPath.row] as! NSManagedObject cell.textLabel!.text = aux.valueForKey("name") as? String cell.detailTextLabel!.text = aux.valueForKey("surname") as? String return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results!.count } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Contacts" } func loadTable(){ var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var context:NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Form") request.returnsObjectsAsFaults = false results = context.executeFetchRequest(request, error: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bd29c029f03921f4929d46d51a7b9cb8
33.130435
132
0.672611
false
false
false
false
yeziahehe/Gank
refs/heads/master
Pods/MonkeyKing/Sources/Extensions.swift
gpl-3.0
1
import Foundation import MobileCoreServices extension Set { subscript(platform: MonkeyKing.SupportedPlatform) -> MonkeyKing.Account? { let accountSet = MonkeyKing.shared.accountSet switch platform { case .weChat: for account in accountSet { if case .weChat = account { return account } } case .qq: for account in accountSet { if case .qq = account { return account } } case .weibo: for account in accountSet { if case .weibo = account { return account } } case .pocket: for account in accountSet { if case .pocket = account { return account } } case .alipay: for account in accountSet { if case .alipay = account { return account } } case .twitter: for account in accountSet { if case .twitter = account { return account } } } return nil } subscript(platform: MonkeyKing.Message) -> MonkeyKing.Account? { let accountSet = MonkeyKing.shared.accountSet switch platform { case .weChat: for account in accountSet { if case .weChat = account { return account } } case .qq: for account in accountSet { if case .qq = account { return account } } case .weibo: for account in accountSet { if case .weibo = account { return account } } case .alipay: for account in accountSet { if case .alipay = account { return account } } case .twitter: for account in accountSet { if case .twitter = account { return account } } } return nil } } extension Bundle { var monkeyking_displayName: String? { let CFBundleDisplayName = (localizedInfoDictionary?["CFBundleDisplayName"] ?? infoDictionary?["CFBundleDisplayName"]) as? String let CFBundleName = (localizedInfoDictionary?["CFBundleName"] ?? infoDictionary?["CFBundleName"]) as? String return CFBundleDisplayName ?? CFBundleName } var monkeyking_bundleID: String? { return object(forInfoDictionaryKey: "CFBundleIdentifier") as? String } } extension String { var monkeyking_base64EncodedString: String? { return data(using: .utf8)?.base64EncodedString() } var monkeyking_urlEncodedString: String? { return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) } var monkeyking_base64AndURLEncodedString: String? { return monkeyking_base64EncodedString?.monkeyking_urlEncodedString } var monkeyking_urlDecodedString: String? { return replacingOccurrences(of: "+", with: " ").removingPercentEncoding } var monkeyking_qqCallbackName: String { let hexString = String(format: "%08llx", (self as NSString).longLongValue) return "QQ" + hexString } } extension Data { var monkeyking_json: [String: Any]? { do { return try JSONSerialization.jsonObject(with: self, options: .allowFragments) as? [String: Any] } catch { return nil } } } extension URL { var monkeyking_queryDictionary: [String: Any] { let components = URLComponents(url: self, resolvingAgainstBaseURL: false) guard let items = components?.queryItems else { return [:] } var infos = [String: Any]() items.forEach { if let value = $0.value { infos[$0.name] = value } } return infos } } extension UIImage { var monkeyking_compressedImageData: Data? { var compressionQuality: CGFloat = 0.7 func compressedDataOfImage(_ image: UIImage) -> Data? { let maxHeight: CGFloat = 240.0 let maxWidth: CGFloat = 240.0 var actualHeight: CGFloat = image.size.height var actualWidth: CGFloat = image.size.width var imgRatio: CGFloat = actualWidth/actualHeight let maxRatio: CGFloat = maxWidth/maxHeight if actualHeight > maxHeight || actualWidth > maxWidth { if imgRatio < maxRatio { // adjust width according to maxHeight imgRatio = maxHeight / actualHeight actualWidth = imgRatio * actualWidth actualHeight = maxHeight } else if imgRatio > maxRatio { // adjust height according to maxWidth imgRatio = maxWidth / actualWidth actualHeight = imgRatio * actualHeight actualWidth = maxWidth } else { actualHeight = maxHeight actualWidth = maxWidth } } let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight) UIGraphicsBeginImageContext(rect.size) defer { UIGraphicsEndImageContext() } image.draw(in: rect) let imageData = UIGraphicsGetImageFromCurrentImageContext().flatMap({ $0.jpegData(compressionQuality: compressionQuality) }) return imageData } let fullImageData = self.jpegData(compressionQuality: compressionQuality) guard var imageData = fullImageData else { return nil } let minCompressionQuality: CGFloat = 0.01 let dataLengthCeiling: Int = 31500 while imageData.count > dataLengthCeiling && compressionQuality > minCompressionQuality { compressionQuality -= 0.1 guard let image = UIImage(data: imageData) else { break } if let compressedImageData = compressedDataOfImage(image) { imageData = compressedImageData } else { break } } return imageData } func monkeyking_resetSizeOfImageData(maxSize: Int) -> Data? { if let imageData = self.jpegData(compressionQuality: 1.0), imageData.count <= maxSize { return imageData } func compressedDataOfImage(_ image: UIImage?) -> Data? { guard let image = image else { return nil } let imageData = image.binaryCompression(to: maxSize) if imageData == nil { let currentMiniIamgeDataSize = self.jpegData(compressionQuality: 0.01)?.count ?? 0 let proportion = CGFloat(currentMiniIamgeDataSize / maxSize) let newWidth = image.size.width * scale / proportion let newHeight = image.size.height * scale / proportion let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContext(newSize) image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return compressedDataOfImage(newImage) } return imageData } return compressedDataOfImage(self) } private func binaryCompression(to maxSize: Int) -> Data? { var compressionQualitys = [CGFloat](repeating: 0, count: 100) var i = compressionQualitys.count + 1 compressionQualitys = compressionQualitys.map { (_) -> CGFloat in let newValue = CGFloat(i) / CGFloat(compressionQualitys.count + 1) i -= 1 return newValue } var imageData: Data? = self.jpegData(compressionQuality: 1) var outPutImageData: Data? = nil var start = 0 var end = compressionQualitys.count - 1 var index = 0 var difference = Int.max while start <= end { index = start + (end - start) / 2 imageData = self.jpegData(compressionQuality: compressionQualitys[index]) let imageDataSize = imageData?.count ?? 0 if imageDataSize > maxSize { start = index + 1 } else if imageDataSize < maxSize { if (maxSize - imageDataSize) < difference { difference = (maxSize - imageDataSize) outPutImageData = imageData } if index <= 0 { break } end = index - 1 } else { break } } return outPutImageData } } extension UIPasteboard { /// Fetch old text on pasteboard var oldText: String? { /// From iOS 8 to iOS 11, UIPasteboardTypeListString contains two elements: public.text, public.utf8-plain-text guard let typeListString = UIPasteboard.typeListString as? [String] else { return nil } guard UIPasteboard.general.contains(pasteboardTypes: typeListString) else { return nil } return UIPasteboard.general.string } } extension Dictionary { var toString: String? { guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: .prettyPrinted), let theJSONText = String(data: jsonData, encoding: .utf8) else { return nil } return theJSONText } }
fb9d5912fba18c63375663f144aaeb9a
30.842949
136
0.549774
false
false
false
false
thion/bialoszewski.app
refs/heads/master
bialoszewski/RecordIconLayer.swift
mit
1
// // RecordIconLayer.swift // bialoszewski // // Created by Kamil Nicieja on 03/08/14. // Copyright (c) 2014 Kamil Nicieja. All rights reserved. // import QuartzCore class RecordIconLayer: CALayer { var startAngle: CGFloat! var endAngle: CGFloat! var fillColor: UIColor! var strokeWidth: CGFloat! var strokeColor: UIColor! override init(layer: AnyObject) { super.init(layer: layer) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawInContext(ctx: CGContextRef) { var center: CGPoint = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) var radius: CGFloat = min(center.x, center.y) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, center.x, center.y) var floated: Float = Float(startAngle) var cosinus: CGFloat = CGFloat(cosf(floated)) var sinus: CGFloat = CGFloat(sinf(floated)) var p1: CGPoint = CGPointMake(center.x + radius * cosinus, center.y + radius * sinus) CGContextAddLineToPoint(ctx, p1.x, p1.y) var clockwise: Int = Int(startAngle > endAngle) CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, Int32(clockwise)) CGContextClosePath(ctx) CGContextSetStrokeColorWithColor(ctx, strokeColor.CGColor) CGContextSetFillColorWithColor(ctx, fillColor.CGColor) CGContextSetLineWidth(ctx, strokeWidth) CGContextSetLineCap(ctx, kCGLineCapButt) CGContextDrawPath(ctx, kCGPathFillStroke) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, center.x, center.y) CGContextAddLineToPoint(ctx, p1.x, p1.y) CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, Int32(clockwise)) CGContextEOClip(ctx) var image: UIImage = UIImage(named: "Empty.png") var mask: CGImageRef = image.CGImage var imageRect: CGRect = CGRectMake(center.x, center.y, image.size.width, image.size.height) CGContextTranslateCTM(ctx, 0, image.size.height) CGContextScaleCTM(ctx, 1.0, -1.0) CGContextTranslateCTM(ctx, imageRect.origin.x, imageRect.origin.y) CGContextRotateCTM(ctx, rad(-90)) CGContextTranslateCTM(ctx, imageRect.size.width * -0.534, imageRect.size.height * -0.474) CGContextDrawImage(ctx, self.bounds, mask) } func rad(degrees: Int) -> CGFloat { return (CGFloat(degrees) / (180.0 / CGFloat(M_PI))) } }
4f9bf1351ba744d35f6469dded237c5c
32.636364
99
0.657529
false
false
false
false
objective-audio/saitama_20150927
refs/heads/master
iOS9AudioUnitOutputSample/iOS9AudioUnitOutputSample/EffectViewController.swift
mit
1
// // EffectViewController.swift // iOS9AudioUnitOutputSample // // Created by 八十嶋祐樹 on 2015/11/29. // Copyright © 2015年 Yuki Yasoshima. All rights reserved. // import UIKit import AVFoundation import Accelerate class EffectViewController: UIViewController { var audioEngine: AVAudioEngine? override func viewDidLoad() { super.viewDidLoad() setupEffectAudioUnit() } func setupEffectAudioUnit() { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) } catch { print(error) return } let engine = AVAudioEngine() self.audioEngine = engine AVAudioUnit.instantiateWithComponentDescription(AudioUnitEffectSample.audioComponentDescription, options: AudioComponentInstantiationOptions(rawValue: 0)) { (audioUnitNode: AVAudioUnit?, err: ErrorType?) in guard let audioUnitNode = audioUnitNode else { print(err) return } guard let inputNode = engine.inputNode else { return } engine.attachNode(audioUnitNode) let sampleRate = AVAudioSession.sharedInstance().sampleRate let format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 2) engine.connect(audioUnitNode, to: engine.mainMixerNode, format: format) engine.connect(inputNode, to: audioUnitNode, format: format) let delayBuffer = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: AVAudioFrameCount(format.sampleRate)) delayBuffer.frameLength = delayBuffer.frameCapacity var delayFrame: AVAudioFrameCount = 0 let effectUnit = audioUnitNode.AUAudioUnit as! AudioUnitEffectSample effectUnit.kernelRenderBlock = { buffer in let format = buffer.format var bufferFrame: AVAudioFrameCount = 0 while bufferFrame < buffer.frameLength { let copyFrame = min(delayBuffer.frameLength - delayFrame, buffer.frameLength - bufferFrame) for ch in 0..<format.channelCount { let bufferData = buffer.floatChannelData[Int(ch)].advancedBy(Int(bufferFrame)) let delayData = delayBuffer.floatChannelData[Int(ch)].advancedBy(Int(delayFrame)) vDSP_vswap(bufferData, 1, delayData, 1, vDSP_Length(copyFrame)) } delayFrame += copyFrame if delayFrame != 0 { delayFrame %= delayBuffer.frameLength } bufferFrame += copyFrame } } do { try AVAudioSession.sharedInstance().setActive(true) try engine.start() } catch { print(error) return } } } }
46684bbdb197b2b157c7a727624fb872
35.448276
214
0.562283
false
false
false
false
iMetalk/TCZKit
refs/heads/master
TCZKitDemo/TCZKit/ViewControllers/TCZKitInputTextViewController.swift
mit
1
// // TCZKitInputTextViewController.swift // Dormouse // // Created by 田向阳 on 2017/8/14. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit import IQKeyboardManagerSwift class TCZKitInputTextViewController: TCZBaseViewController,UITextViewDelegate { //MARK:Property open var placeHolder: String? open var limitCount: Int = 0 open var content: String? open var tipString: String? open var confirmBlock:((_ text: String)->())? //MARK: ControllerLifeCycle override func viewDidLoad() { super.viewDidLoad() initControllerFirstData() createUI() loadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) textView.becomeFirstResponder() } //MARK: LoadData private func loadData() { self.textView.text = self.content self.textView.placeholder = self.placeHolder self.tipLabel.text = self.tipString textDidChanged() } private func initControllerFirstData() { self.title = String(describing: self) view.backgroundColor = UIColor.HexColor(hexValue: 0xf2f2f2) self.setRightButtonItemWithTitle(title: "确定") } //MARK: Action override func didClickNavigationBarRightButton() { if confirmBlock != nil { confirmBlock!(self.textView.text!) } self.navigationController?.popViewController(animated: true) } func textViewDidChange(_ textView: UITextView) { textDidChanged() } func textDidChanged() { if (textView.text?.length)! > limitCount { if textView.markedTextRange != nil { return } textView.text = textView.text?.toNSString.substring(to: limitCount) } updateRightItemEnable() } private func updateRightItemEnable() { self.navigationItem.rightBarButtonItem?.isEnabled = (self.textView.text?.length)! > 0 } //MARK: CreateUI private func createUI() { view.addSubview(textView) textView.snp.makeConstraints { (make) in make.top.equalTo(20) make.left.right.equalToSuperview() make.height.equalTo(100) } view.addSubview(tipLabel) tipLabel.snp.makeConstraints { (make) in make.top.equalTo(textView.snp.bottom) make.left.equalTo(10) make.height.equalTo(40) make.right.equalTo(-kLeftEdge) } } lazy var textView: IQTextView = { let textView = IQTextView() textView.placeholder = "请输入内容" textView.font = UIFont.tcz_systemFontWithSize(size: kTitleFontSize) textView.textColor = .gray textView.delegate = self textView.backgroundColor = .white return textView }() lazy var tipLabel: UILabel = { let label = UILabel.tczLabel(text: nil, font: UIFont.tcz_systemFontWithSize(size: 13), color: UIColor.gray) return label }() //MARK: Helper }
d1d4763809a00c3b4312c7b4548e5333
28.352381
115
0.622972
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/OnThisDayViewControllerHeader.swift
mit
1
import UIKit class OnThisDayViewControllerHeader: UICollectionReusableView { @IBOutlet weak var eventsLabel: UILabel! @IBOutlet weak var onLabel: UILabel! @IBOutlet weak var fromLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() updateFonts() apply(theme: Theme.standard) wmf_configureSubviewsForDynamicType() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { onLabel.font = UIFont.wmf_font(.heavyTitle1, compatibleWithTraitCollection: traitCollection) } func configureFor(eventCount: Int, firstEvent: WMFFeedOnThisDayEvent?, lastEvent: WMFFeedOnThisDayEvent?, midnightUTCDate: Date) { let languageCode = firstEvent?.languageCode let locale = NSLocale.wmf_locale(for: languageCode) semanticContentAttribute = MWKLanguageLinkController.semanticContentAttribute(forContentLanguageCode: firstEvent?.contentLanguageCode) eventsLabel.semanticContentAttribute = semanticContentAttribute onLabel.semanticContentAttribute = semanticContentAttribute fromLabel.semanticContentAttribute = semanticContentAttribute eventsLabel.text = CommonStrings.onThisDayAdditionalEventsMessage(with: languageCode, locale: locale, eventsCount: eventCount).uppercased(with: locale) onLabel.text = DateFormatter.wmf_monthNameDayNumberGMTFormatter(for: languageCode).string(from: midnightUTCDate) if let firstEventEraString = firstEvent?.yearString, let lastEventEraString = lastEvent?.yearString { fromLabel.text = CommonStrings.onThisDayHeaderDateRangeMessage(with: languageCode, locale: locale, lastEvent: lastEventEraString, firstEvent: firstEventEraString) } else { fromLabel.text = nil } } } extension OnThisDayViewControllerHeader: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground eventsLabel.textColor = theme.colors.secondaryText onLabel.textColor = theme.colors.primaryText fromLabel.textColor = theme.colors.secondaryText } }
10e1354d64805c8d2a77f177c0543b40
42.509434
174
0.735039
false
false
false
false
hellogaojun/Swift-coding
refs/heads/master
swift学习教材案例/Swifter.playground/Pages/multi-collection.xcplaygroundpage/Contents.swift
apache-2.0
1
import Foundation let numbers = [1,2,3,4,5] // numbers 的类型是 [Int] let strings = ["hello", "world"] // strings 的类型是 [String] import UIKit let mixed1: [Any] = [1, "two", 3] // 如果不指明类型,由于 UIKit 的存在 // 将被推断为 [NSObject] let objectArray = [1, "two", 3] let any = mixed1[0] // Any 类型 let nsObject = objectArray[0] // NSObject 类型 let mixed2: [CustomStringConvertible] = [1, "two", 3] for obj in mixed2 { print(obj.description) } enum IntOrString { case IntValue(Int) case StringValue(String) } let mixed3 = [IntOrString.IntValue(1), IntOrString.StringValue("two"), IntOrString.IntValue(3)] for value in mixed3 { switch value { case let .IntValue(i): print(i * 2) case let .StringValue(s): print(s.capitalizedString) } } // 输出: // 2 // Two // 6
25d500a5988ebb52b6da8b11bccb6ace
15.708333
53
0.628429
false
false
false
false
remirobert/TextDrawer
refs/heads/master
TextDrawer/TextDrawer/TextDrawer.swift
mit
1
// // DrawView.swift // // // Created by Remi Robert on 11/07/15. // // //Scrux import UIKit import Masonry public class TextDrawer: UIView, TextEditViewDelegate { private var textEditView: TextEditView! private var drawTextView: DrawTextView! private var initialTransformation: CGAffineTransform! private var initialCenterDrawTextView: CGPoint! private var initialRotationTransform: CGAffineTransform! private var initialReferenceRotationTransform: CGAffineTransform! private var activieGestureRecognizer = NSMutableSet() private var activeRotationGesture: UIRotationGestureRecognizer? private var activePinchGesture: UIPinchGestureRecognizer? private lazy var tapRecognizer: UITapGestureRecognizer! = { let tapRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGesture:") tapRecognizer.delegate = self return tapRecognizer }() private lazy var panRecognizer: UIPanGestureRecognizer! = { let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePanGesture:") panRecognizer.delegate = self return panRecognizer }() private lazy var rotateRecognizer: UIRotationGestureRecognizer! = { let rotateRecognizer = UIRotationGestureRecognizer(target: self, action: "handlePinchGesture:") rotateRecognizer.delegate = self return rotateRecognizer }() private lazy var zoomRecognizer: UIPinchGestureRecognizer! = { let zoomRecognizer = UIPinchGestureRecognizer(target: self, action: "handlePinchGesture:") zoomRecognizer.delegate = self return zoomRecognizer }() public func clearText() { text = "" } public func resetTransformation() { drawTextView.transform = initialTransformation drawTextView.mas_updateConstraints({ (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) make.centerX.and().centerY().equalTo()(self) }) drawTextView.center = center //drawTextView.sizeTextLabel() } //MARK: - //MARK: Setup DrawView private func setup() { self.layer.masksToBounds = true drawTextView = DrawTextView() initialTransformation = drawTextView.transform addSubview(drawTextView) drawTextView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) } textEditView = TextEditView() textEditView.delegate = self addSubview(textEditView) textEditView.mas_makeConstraints { (make: MASConstraintMaker!) -> Void in make.edges.equalTo()(self) } addGestureRecognizer(tapRecognizer) addGestureRecognizer(panRecognizer) addGestureRecognizer(rotateRecognizer) addGestureRecognizer(zoomRecognizer) initialReferenceRotationTransform = CGAffineTransformIdentity } //MARK: - //MARK: Initialisation init() { super.init(frame: CGRectZero) setup() drawTextView.textLabel.font = drawTextView.textLabel.font.fontWithSize(44) } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func textEditViewFinishedEditing(text: String) { textEditView.hidden = true drawTextView.text = text } } //MARK: - //MARK: Proprety extension public extension TextDrawer { public var fontSize: CGFloat! { set { drawTextView.textLabel.font = drawTextView.textLabel.font.fontWithSize(newValue) } get { return drawTextView.textLabel.font.pointSize } } public var font: UIFont! { set { drawTextView.textLabel.font = newValue } get { return drawTextView.textLabel.font } } public var textColor: UIColor! { set { drawTextView.textLabel.textColor = newValue } get { return drawTextView.textLabel.textColor } } public var textAlignement: NSTextAlignment! { set { drawTextView.textLabel.textAlignment = newValue } get { return drawTextView.textLabel.textAlignment } } public var textBackgroundColor: UIColor! { set { drawTextView.textLabel.backgroundColor = newValue } get { return drawTextView.textLabel.backgroundColor } } public var text: String! { set { drawTextView.text = newValue } get { return drawTextView.text } } public var textSize: Int! { set { textEditView.textSize = newValue } get { return textEditView.textSize } } } //MARK: - //MARK: Gesture handler extension extension TextDrawer: UIGestureRecognizerDelegate { public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func handleTapGesture(recognizer: UITapGestureRecognizer) { textEditView.textEntry = text textEditView.isEditing = true textEditView.hidden = false } func handlePanGesture(recognizer: UIPanGestureRecognizer) { let translation = recognizer.translationInView(self) switch recognizer.state { case .Began, .Ended, .Failed, .Cancelled: initialCenterDrawTextView = drawTextView.center case .Changed: drawTextView.center = CGPointMake(initialCenterDrawTextView.x + translation.x, initialCenterDrawTextView.y + translation.y) default: return } } func handlePinchGesture(recognizer: UIGestureRecognizer) { var transform = initialRotationTransform switch recognizer.state { case .Began: if activieGestureRecognizer.count == 0 { initialRotationTransform = drawTextView.transform } activieGestureRecognizer.addObject(recognizer) break case .Changed: for currentRecognizer in activieGestureRecognizer { transform = applyRecogniser(currentRecognizer as? UIGestureRecognizer, currentTransform: transform) } drawTextView.transform = transform break case .Ended, .Failed, .Cancelled: initialRotationTransform = applyRecogniser(recognizer, currentTransform: initialRotationTransform) activieGestureRecognizer.removeObject(recognizer) default: return } } private func applyRecogniser(recognizer: UIGestureRecognizer?, currentTransform: CGAffineTransform) -> CGAffineTransform { if let recognizer = recognizer { if recognizer is UIRotationGestureRecognizer { return CGAffineTransformRotate(currentTransform, (recognizer as! UIRotationGestureRecognizer).rotation) } if recognizer is UIPinchGestureRecognizer { let scale = (recognizer as! UIPinchGestureRecognizer).scale return CGAffineTransformScale(currentTransform, scale, scale) } } return currentTransform } } //MARK: - //MARK: Render extension public extension TextDrawer { public func render() -> UIImage? { return renderTextOnView(self) } public func renderTextOnView(view: UIView) -> UIImage? { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0) view.layer.renderInContext(UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return renderTextOnImage(img) } public func renderTextOnImage(image: UIImage) -> UIImage? { let size = image.size let scale = size.width / CGRectGetWidth(self.bounds) let color = layer.backgroundColor UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) image.drawInRect(CGRectMake(CGRectGetWidth(self.bounds) / 2 - (image.size.width / scale) / 2, CGRectGetHeight(self.bounds) / 2 - (image.size.height / scale) / 2, image.size.width / scale, image.size.height / scale)) layer.backgroundColor = UIColor.clearColor().CGColor layer.renderInContext(UIGraphicsGetCurrentContext()!) layer.backgroundColor = color let drawnImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return UIImage(CGImage: drawnImage.CGImage!, scale: 1, orientation: drawnImage.imageOrientation) } }
04c7cb8e82d1feab2b1881f591735527
29.982993
179
0.640026
false
false
false
false
bazelbuild/tulsi
refs/heads/master
src/TulsiGeneratorTests/BuildLabelTests.swift
apache-2.0
2
// Copyright 2016 The Tulsi Authors. 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 XCTest @testable import TulsiGenerator class BuildLabelTests: XCTestCase { let a1 = BuildLabel("//test/place:a") let a2 = BuildLabel("//test/place:a") let b = BuildLabel("//test/place:b") let c = BuildLabel("//test/place:c") let noTargetName = BuildLabel("//test/place") let noLeadingSlash = BuildLabel("no/leading/slash") let emptyLabel = BuildLabel("") let justSlashLabel = BuildLabel("//") let invalidTrailingSlash = BuildLabel("invalid/trailing/slash/") func testEquality() { XCTAssertEqual(a1, a1) XCTAssertEqual(a1, a2) XCTAssertNotEqual(a1, b) } func testHash() { XCTAssertEqual(a1.hashValue, a2.hashValue) } func testComparison() { XCTAssertLessThan(a1, b) XCTAssertGreaterThan(c, b) } func testTargetName() { XCTAssertEqual(a1.targetName, "a") XCTAssertEqual(b.targetName, "b") XCTAssertEqual(c.targetName, "c") XCTAssertEqual(noTargetName.targetName, "place") XCTAssertNil(emptyLabel.targetName) XCTAssertNil(justSlashLabel.targetName) XCTAssertNil(invalidTrailingSlash.targetName) } func testPackageName() { XCTAssertEqual(a1.packageName, "test/place") XCTAssertEqual(a1.packageName, b.packageName) XCTAssertEqual(noLeadingSlash.packageName, "no/leading/slash") XCTAssertEqual(emptyLabel.packageName, "") XCTAssertEqual(justSlashLabel.packageName, "") XCTAssertEqual(invalidTrailingSlash.packageName, "") } func testAsFileName() { XCTAssertEqual(a1.asFileName, "test/place/a") XCTAssertEqual(a1.asFileName, a2.asFileName) XCTAssertEqual(noLeadingSlash.asFileName, "no/leading/slash/slash") XCTAssertNil(emptyLabel.asFileName) XCTAssertNil(justSlashLabel.asFileName) XCTAssertNil(invalidTrailingSlash.asFileName) } }
ec83ef027b7f4b9bf66b5c33589f020c
32.361111
75
0.732723
false
true
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Views/GroupInvitationListView.swift
gpl-3.0
1
// // GroupInvitationListView.swift // Habitica // // Created by Phillip Thelen on 22.06.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import PinLayout import ReactiveSwift class GroupInvitationListView: UIView { private var invitationViews = [GroupInvitationView]() private let socialRepository = SocialRepository() private var disposable = CompositeDisposable() func set(invitations: [GroupInvitationProtocol]?) { if !disposable.isDisposed { disposable.dispose() } disposable = CompositeDisposable() invitationViews.forEach { (view) in view.removeFromSuperview() } invitationViews.removeAll() for invitation in invitations ?? [] { let view = GroupInvitationView() view.set(invitation: invitation) view.responseAction = {[weak self] didAccept in guard let groupID = invitation.id else { return } if didAccept { self?.socialRepository.joinGroup(groupID: groupID).observeCompleted {} } else { self?.socialRepository.rejectGroupInvitation(groupID: groupID).observeCompleted {} } } if let inviterID = invitation.inviterID { DispatchQueue.main.async {[weak self] in self?.disposable.add(self?.socialRepository.getMember(userID: inviterID).skipNil().on(value: { member in view.set(inviter: member) }).start()) } } addSubview(view) invitationViews.append(view) } invitationViews.dropFirst().forEach { (view) in view.showSeparator = true } setNeedsLayout() invalidateIntrinsicContentSize() } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { var topEdge = edge.top for view in invitationViews { view.pin.top(to: topEdge).width(frame.size.width).height(70) topEdge = view.edge.bottom } } override var intrinsicContentSize: CGSize { layout() let height = (invitationViews.last?.frame.origin.y ?? 0) + (invitationViews.last?.frame.size.height ?? 0) return CGSize(width: frame.size.width, height: height) } }
042cf57068546edcf62b9bc3d8be4cf6
31.164557
124
0.578512
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDKTests/Rest/Models/ResultCollectionTests.swift
mit
1
import XCTest import Nimble @testable import FitpaySDK class ResultCollectionTests: XCTestCase { private let mockModels = MockModels() private var restClient: RestClient! private let restRequest = MockRestRequest() override func setUp() { let session = RestSession(restRequest: restRequest) session.accessToken = "authorized" restClient = RestClient(session: session, restRequest: restRequest) } func testResultCollectionParsing() { let resultCollection = mockModels.getResultCollection() expect(resultCollection?.links).toNot(beNil()) expect(resultCollection?.limit).to(equal(1)) expect(resultCollection?.offset).to(equal(1)) expect(resultCollection?.totalResults).to(equal(1)) expect(resultCollection?.results).toNot(beNil()) expect(resultCollection?.client).to(beNil()) let json = resultCollection?.toJSON() expect(json?["_links"]).toNot(beNil()) expect(json?["limit"] as? Int).to(equal(1)) expect(json?["offset"] as? Int).to(equal(1)) expect(json?["totalResults"] as? Int).to(equal(1)) } func testResultCollectionVerificationMethodParsing() { let resultCollection = mockModels.getResultVerificationMethodCollection() expect(resultCollection?.totalResults).to(equal(1)) expect(resultCollection?.results).toNot(beNil()) expect(resultCollection?.results?.count).to(equal(1)) } func testNextAvailable() { let resultCollection = mockModels.getResultCollection() let nextAvailable = resultCollection?.nextAvailable expect(nextAvailable).to(beTrue()) resultCollection?.links = nil let nextNotAvailable = resultCollection?.nextAvailable expect(nextNotAvailable).toNot(beTrue()) } func testLastAvailable() { let resultCollection = mockModels.getResultCollection() let lastAvailable = resultCollection?.lastAvailable expect(lastAvailable).to(beTrue()) resultCollection?.links = nil let lastNotAvailable = resultCollection?.lastAvailable expect(lastNotAvailable).toNot(beTrue()) } func testPreviousAvailable() { let resultCollection = mockModels.getResultCollection() let previousAvailable = resultCollection?.previousAvailable expect(previousAvailable).to(beTrue()) resultCollection?.links = nil let previousNotAvailable = resultCollection?.previousAvailable expect(previousNotAvailable).toNot(beTrue()) } func testClientGetReturnsClientIfClientPresent() { let resultCollection = mockModels.getResultCollection() let client = RestClient(session: RestSession()) resultCollection?.client = client expect(resultCollection?.client).to(equal(client)) } func testClientGetReturnsClientIfResultsHaveClient() { let resultCollection = mockModels.getResultCollection() let client = RestClient(session: RestSession()) expect(resultCollection?.client).to(beNil()) resultCollection?.results?.first?.client = client expect(resultCollection?.client).to(equal(client)) } func testClientSetSetsRestClient() { let resultCollection = mockModels.getResultCollection() let client = RestClient(session: RestSession()) expect(resultCollection?.results?.first?.client).to(beNil()) resultCollection?.client = client expect(resultCollection?.results?.first?.client).to(equal(client)) } func testCollectAllAvailableNoClient() { let resultCollection = mockModels.getResultCollection() waitUntil { done in resultCollection?.collectAllAvailable { (devices, error) in expect(devices).to(beNil()) expect(error).toNot(beNil()) done() } } } func testCollectAllAvailableNoNext() { let resultCollection = mockModels.getResultCollection() resultCollection?.links?["next"] = nil waitUntil { done in resultCollection?.collectAllAvailable { (devices, error) in expect(devices).toNot(beNil()) expect(devices?.count).to(equal(1)) expect(error).to(beNil()) done() } } } func testCollectAllAvailable() { let resultCollection = mockModels.getResultCollection() resultCollection?.client = restClient waitUntil { done in resultCollection?.collectAllAvailable { (devices, error) in expect(devices).toNot(beNil()) expect(devices?.count).to(equal(2)) expect(error).to(beNil()) done() } } } func testNextNoClient() { let resultCollection = mockModels.getResultCollection() waitUntil { done in resultCollection?.next { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).to(beNil()) expect(error).toNot(beNil()) done() } } } func testNext() { let resultCollection = mockModels.getResultCollection() resultCollection?.client = restClient waitUntil { done in resultCollection?.next { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).toNot(beNil()) expect(collection?.results?.count).to(equal(1)) expect(error).to(beNil()) done() } } } func testLastNoClient() { let resultCollection = mockModels.getResultCollection() waitUntil { done in resultCollection?.last { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).to(beNil()) expect(error).toNot(beNil()) done() } } } func testLast() { let resultCollection = mockModels.getResultCollection() resultCollection?.client = restClient waitUntil { done in resultCollection?.last { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).toNot(beNil()) expect(collection?.results?.count).to(equal(1)) expect(error).to(beNil()) done() } } } func testPreviousNoClient() { let resultCollection = mockModels.getResultCollection() waitUntil { done in resultCollection?.previous { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).to(beNil()) expect(error).toNot(beNil()) done() } } } func testPrevious() { let resultCollection = mockModels.getResultCollection() resultCollection?.client = restClient waitUntil { done in resultCollection?.previous { (collection: ResultCollection<Device>?, error: ErrorResponse?) in expect(collection).toNot(beNil()) expect(collection?.results?.count).to(equal(1)) expect(error).to(beNil()) done() } } } }
434192ff4ea1b8245e7dd26275484713
31.834746
106
0.588592
false
true
false
false
trill-lang/LLVMSwift
refs/heads/master
utils/make-pkgconfig.swift
mit
1
#!/usr/bin/env swift import Foundation #if os(Linux) let libCPP = "-L/usr/lib -lc++" #elseif os(macOS) let libCPP = "-lc++" #endif /// Runs the specified program at the provided path. /// - parameter path: The full path of the executable you /// wish to run. /// - parameter args: The arguments you wish to pass to the /// process. /// - returns: The standard output of the process, or nil if it was empty. func run(_ path: String, args: [String] = []) -> String? { print("Running \(path) \(args.joined(separator: " "))...") let pipe = Pipe() let process = Process() process.executableURL = URL(fileURLWithPath: path) process.arguments = args process.standardOutput = pipe try? process.run() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() guard let result = String(data: data, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines), !result.isEmpty else { return nil } return result } /// Finds the location of the provided binary on your system. func which(_ name: String) -> String? { return run("/usr/bin/which", args: [name]) } extension String: Error { /// Replaces all occurrences of characters in the provided set with /// the provided string. func replacing(charactersIn characterSet: CharacterSet, with separator: String) -> String { let components = self.components(separatedBy: characterSet) return components.joined(separator: separator) } } func makeFile() throws { let pkgConfigPath = "/usr/local/lib/pkgconfig" let pkgConfigDir = URL(fileURLWithPath: pkgConfigPath) // Make /usr/local/lib/pkgconfig if it doesn't already exist if !FileManager.default.fileExists(atPath: pkgConfigPath) { try FileManager.default.createDirectory(at: pkgConfigDir, withIntermediateDirectories: true) } let cllvmPath = pkgConfigDir.appendingPathComponent("cllvm.pc") let brewLLVMConfig: () -> String? = { guard let brew = which("brew") else { return nil } guard let brewPrefix = run(brew, args: ["--prefix"]) else { return nil } return which(brewPrefix + "/opt/llvm/bin/llvm-config") } /// Ensure we have llvm-config in the PATH guard let llvmConfig = which("llvm-config-9") ?? which("llvm-config") ?? brewLLVMConfig() else { throw "Failed to find llvm-config. Ensure llvm-config is installed and " + "in your PATH" } /// Extract the info we need from llvm-config print("Found llvm-config at \(llvmConfig)...") let versionStr = run(llvmConfig, args: ["--version"])! .replacing(charactersIn: .newlines, with: "") .replacingOccurrences(of: "svn", with: "") let components = versionStr.components(separatedBy: ".") .compactMap { Int($0) } guard components.count == 3 else { throw "Invalid version number \(versionStr)" } let version = (components[0], components[1], components[2]) guard version >= (9, 0, 0) else { throw "LLVMSwift requires LLVM version >=9.0.0, but you have \(versionStr)" } print("LLVM version is \(versionStr)") let ldFlags = run(llvmConfig, args: ["--ldflags", "--libs", "all", "--system-libs"])! .replacing(charactersIn: .newlines, with: " ") .components(separatedBy: " ") .filter { !$0.hasPrefix("-W") } .joined(separator: " ") // SwiftPM has a whitelisted set of cflags that it understands, and // unfortunately that includes almost everything but the include dir. let cFlags = run(llvmConfig, args: ["--cflags"])! .replacing(charactersIn: .newlines, with: "") .components(separatedBy: " ") .filter { $0.hasPrefix("-I") } .joined(separator: " ") /// Emit the pkg-config file to the path let s = [ "Name: cllvm", "Description: The llvm library", "Version: \(versionStr)", "Libs: \(ldFlags) \(libCPP)", "Requires.private:", "Cflags: \(cFlags)", ].joined(separator: "\n") print("Writing pkg-config file to \(cllvmPath.path)...") try s.write(toFile: cllvmPath.path, atomically: true, encoding: .utf8) print("\nSuccessfully wrote pkg-config file!") print("Make sure to re-run this script when you update LLVM.") } do { try makeFile() } catch { print("error: \(error)") exit(-1) }
cedd5c3376de78250a635e0ee06306fe
33.105263
98
0.62037
false
true
false
false
noremac/UIKitExtensions
refs/heads/master
Extensions/Source/General/Section Data Source/DataSource.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2017 Cameron Pulsford Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation public class DataSource<Element> { public typealias ElementKind = Element public typealias ItemModificationClosure = (_ indexPath: IndexPath, _ item: ElementKind) -> ElementKind public init() { } // The type doesn't really matter. internal var dataSourceHandlerStorage: AnyObject? public var itemModificationClosure: ItemModificationClosure? /// Set the sections array. public var sections: [Section<ElementKind>] = [] /// A convenience method for setting up a data source that only has one section. /// /// - Parameter items: The items to set for section 0. All other sections will be removed. public func set(items: [ElementKind]) { sections = [Section(items: items)] } /// Add a new section at the end of the data source. /// /// - parameter section: The section to add. public func append(section: Section<ElementKind>) { sections.append(section) } /// Insert a new section at the given index. /// /// - parameter section: The section to be inserted. /// - parameter index: The index at which the section should be inserted. public func insert(section: Section<ElementKind>, at index: Int) { sections.insert(section, at: index) } /// Remove a section at the given index. /// /// - parameter index: The index from which to remove a section. /// /// - returns: The section that was removed. public func remove(sectionAt index: Int) -> Section<ElementKind> { return sections.remove(at: index) } /// Remove all existing sections. public func removeAllSections() { sections.removeAll() } /// Return the item at the given index path, or nil. /// /// - parameter indexPath: The index path. /// /// - returns: The item at the given index path, or nil. public func item(for indexPath: IndexPath) -> ElementKind? { guard let section = section(at: indexPath.section), indexPath.row < section.count else { return nil } let item = section[indexPath.row] return itemModificationClosure.map({ $0(indexPath, item) }) ?? item } /// Returns the total number of items, across all sections, in the data source. public var totalNumberOfItems: Int { return sections.map({ $0.count }).reduce(0, +) } /// Returns the section at the given index, or nil. /// /// - parameter index: The index. /// /// - returns: The section at the given index, or nil. public func section(at index: Int) -> Section<ElementKind>? { return index < sections.count ? sections[index] : nil } } extension DataSource: MutableCollection { public typealias Index = Int public var startIndex: Index { return sections.startIndex } public var endIndex: Index { return sections.endIndex } public subscript(position: Index) -> Section<ElementKind> { get { return sections[position] } set { sections[position] = newValue } } public func index(after idx: Int) -> Int { return sections.index(after: idx) } }
a0e455ede91d39a3a6a037d3925a745f
31.291045
107
0.669979
false
false
false
false
DrippApp/Dripp-iOS
refs/heads/master
Dripp/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // Dripp // // Created by Henry Saniuk on 1/29/16. // Copyright © 2016 Henry Saniuk. All rights reserved. // import UIKit enum SettingsTableSection: Int { case AccountSettings case Other case ContactUs } class SettingsViewController: UITableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { _ = tableView.indexPathForSelectedRow?.row if let section = SettingsTableSection(rawValue: indexPath.section) { switch section { case .AccountSettings: AuthenticationManager.sharedManager.logout() let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewControllerWithIdentifier("loginViewController") self.presentViewController(vc, animated: true, completion: nil) print("log out") case .ContactUs: let email = "[email protected]" let url = NSURL(string: "mailto:\(email)") UIApplication.sharedApplication().openURL(url!) default: break } } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
1b4316ebbbbe8d534030fcf0e78564d0
31.45
101
0.630971
false
false
false
false
Acidburn0zzz/firefox-ios
refs/heads/main
Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift
mpl-2.0
1
/* 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 import Shared import SwiftKeychainWrapper import LocalAuthentication private let logger = Logger.browserLogger private func presentNavAsFormSheet(_ presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) { presented.modalPresentationStyle = .formSheet presenter?.present(presented, animated: true) { if let selectedRow = settings?.tableView.indexPathForSelectedRow { settings?.tableView.deselectRow(at: selectedRow, animated: false) } } } class TurnPasscodeOnSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOnPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(.AuthenticationTurnOnPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()), presenter: navigationController, settings: settings) } } class TurnPasscodeOffSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "TurnOffPasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) { self.settings = settings as? AuthenticationSettingsViewController super.init(title: NSAttributedString.tableRowTitle(.AuthenticationTurnOffPasscode, enabled: true), delegate: delegate) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()), presenter: navigationController, settings: settings) } } class ChangePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? override var accessibilityIdentifier: String? { return "ChangePasscode" } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) { self.settings = settings as? AuthenticationSettingsViewController let attributedTitle = NSAttributedString.tableRowTitle(.AuthenticationChangePasscode, enabled: enabled) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } override func onClick(_ navigationController: UINavigationController?) { presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()), presenter: navigationController, settings: settings) } } class RequirePasscodeSetting: Setting { weak var settings: AuthenticationSettingsViewController? fileprivate weak var navigationController: UINavigationController? override var accessibilityIdentifier: String? { return "PasscodeInterval" } override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator } override var style: UITableViewCell.CellStyle { return .value1 } override var status: NSAttributedString { // Only show the interval if we are enabled and have an interval set. let authenticationInterval = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() if let interval = authenticationInterval?.requiredPasscodeInterval, enabled { return NSAttributedString.tableRowTitle(interval.settingTitle, enabled: false) } return NSAttributedString(string: "") } init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) { self.navigationController = settings.navigationController self.settings = settings as? AuthenticationSettingsViewController let title: String = .AuthenticationRequirePasscode let attributedTitle = NSAttributedString.tableRowTitle(title, enabled: enabled ?? true) super.init(title: attributedTitle, delegate: delegate, enabled: enabled) } func deselectRow () { if let selectedRow = self.settings?.tableView.indexPathForSelectedRow { self.settings?.tableView.deselectRow(at: selectedRow, animated: true) } } override func onClick(_: UINavigationController?) { deselectRow() guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else { navigateToRequireInterval() return } if authInfo.requiresValidation() { AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: .AuthenticationRequirePasscodeTouchReason, success: { self.navigateToRequireInterval() }, cancel: nil, fallback: { AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isOk in guard isOk else { return } self.navigationController?.dismiss(animated: true) { self.navigateToRequireInterval() } } }) } else { self.navigateToRequireInterval() } } fileprivate func navigateToRequireInterval() { navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true) } } class TouchIDSetting: Setting { fileprivate let authInfo: AuthenticationKeychainInfo? fileprivate weak var navigationController: UINavigationController? fileprivate weak var switchControl: UISwitch? fileprivate var touchIDSuccess: (() -> Void)? fileprivate var touchIDFallback: (() -> Void)? init( title: NSAttributedString?, navigationController: UINavigationController? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil, touchIDSuccess: (() -> Void)? = nil, touchIDFallback: (() -> Void)? = nil) { self.touchIDSuccess = touchIDSuccess self.touchIDFallback = touchIDFallback self.navigationController = navigationController self.authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() super.init(title: title, delegate: delegate, enabled: enabled) } override func onConfigureCell(_ cell: UITableViewCell) { super.onConfigureCell(cell) cell.selectionStyle = .none // In order for us to recognize a tap gesture without toggling the switch, // the switch is wrapped in a UIView which has a tap gesture recognizer. This way // we can disable interaction of the switch and still handle tap events. let control = UISwitchThemed() control.onTintColor = UIColor.theme.tableView.controlTint control.isOn = authInfo?.useTouchID ?? false control.isUserInteractionEnabled = false switchControl = control let accessoryContainer = UIView(frame: control.frame) accessoryContainer.addSubview(control) let gesture = UITapGestureRecognizer(target: self, action: #selector(switchTapped)) accessoryContainer.addGestureRecognizer(gesture) cell.accessoryView = accessoryContainer } @objc fileprivate func switchTapped() { guard let authInfo = authInfo else { logger.error("Authentication info should always be present when modifying Touch ID preference.") return } if authInfo.useTouchID { AppAuthenticator.presentAuthenticationUsingInfo( authInfo, touchIDReason: .AuthenticationDisableTouchReason, success: self.touchIDSuccess, cancel: nil, fallback: self.touchIDFallback ) } else { toggleTouchID(true) } } func toggleTouchID(_ enabled: Bool) { authInfo?.useTouchID = enabled KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) switchControl?.setOn(enabled, animated: true) } } class AuthenticationSettingsViewController: SettingsTableViewController { override func viewDidLoad() { super.viewDidLoad() updateTitleForTouchIDState() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidRemove, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidCreate, object: nil) notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: UIApplication.didBecomeActiveNotification, object: nil) tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView" } override func generateSettings() -> [SettingSection] { if let _ = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { return passcodeEnabledSettings() } else { return passcodeDisabledSettings() } } fileprivate func updateTitleForTouchIDState() { let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if localAuthContext.biometryType == .faceID { title = .AuthenticationFaceIDPasscodeSetting } else { title = .AuthenticationTouchIDPasscodeSetting } navigationItem.title = title } else { navigationItem.title = .AuthenticationPasscode } } fileprivate func passcodeEnabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: .AuthenticationPasscode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOffSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: true) ]) var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)] let localAuthContext = LAContext() if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { let title: String if localAuthContext.biometryType == .faceID { title = Strings.UseFaceID } else { title = Strings.UseTouchID } requirePasscodeSectionChildren.append( TouchIDSetting( title: NSAttributedString.tableRowTitle(title, enabled: true), navigationController: self.navigationController, delegate: nil, enabled: true, touchIDSuccess: { [unowned self] in self.touchIDAuthenticationSucceeded() }, touchIDFallback: { [unowned self] in self.fallbackOnTouchIDFailure() } ) ) } let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren) settings += [ passcodeSection, requirePasscodeSection, ] return settings } fileprivate func passcodeDisabledSettings() -> [SettingSection] { var settings = [SettingSection]() let passcodeSectionTitle = NSAttributedString(string: .AuthenticationPasscode) let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [ TurnPasscodeOnSetting(settings: self), ChangePasscodeSetting(settings: self, delegate: nil, enabled: false) ]) let requirePasscodeSection = SettingSection(title: nil, children: [ RequirePasscodeSetting(settings: self, delegate: nil, enabled: false), ]) settings += [ passcodeSection, requirePasscodeSection, ] return settings } } extension AuthenticationSettingsViewController { @objc func refreshSettings(_ notification: Notification) { updateTitleForTouchIDState() settings = generateSettings() tableView.reloadData() } } extension AuthenticationSettingsViewController { fileprivate func getTouchIDSetting() -> TouchIDSetting? { guard settings.count >= 2 && settings[1].count >= 2 else { return nil } return settings[1][1] as? TouchIDSetting } fileprivate func touchIDAuthenticationSucceeded() { getTouchIDSetting()?.toggleTouchID(false) } func fallbackOnTouchIDFailure() { AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isPasscodeOk in guard isPasscodeOk else { return } self.getTouchIDSetting()?.toggleTouchID(false) self.navigationController?.dismiss(animated: true, completion: nil) } } }
9afd4a99b40492988fb3536eccaa42a0
38.105413
158
0.670042
false
false
false
false
CSSE497/pathfinder-ios
refs/heads/master
examples/ClusterObserver/ClusterObserver/ViewController.swift
mit
1
// // ViewController.swift // ClusterObserver // // Created by Adam Michael on 10/25/15. // Copyright © 2015 Pathfinder. All rights reserved. // import UIKit import thepathfinder class ViewController: UIViewController { let pathfinderAppId = "9869bd06-12ec-451f-8207-2c5f217eb4d0" let userCredentials = "abc" let baseDirectionsUrl = "https://maps.googleapis.com/maps/api/directions/json?" let apiKey = "AIzaSyCxkw1-mYOy6nsSTdyQ6CIjOjIRP33iIxY" var cluster: Cluster! var drawnPaths = [GMSPolyline]() var existingMarkers = [Double]() @IBOutlet weak var mapView: GMSMapView! override func viewDidLoad() { super.viewDidLoad() // Set up Pathfinder cluster = Pathfinder(applicationIdentifier: pathfinderAppId, userCredentials: userCredentials).cluster() cluster.delegate = self cluster.connect() let target = CLLocationCoordinate2DMake(40.65325, -87.5373) mapView.camera = GMSCameraPosition.cameraWithTarget(target, zoom: 7.5) } func draw(coordinate: CLLocationCoordinate2D, icon: UIImage, opacity: Float) { if !existingMarkers.contains(coordinate.latitude*coordinate.longitude) { print("Drawing marker at \(coordinate)") let marker = GMSMarker(position: coordinate) marker.map = mapView marker.appearAnimation = kGMSMarkerAnimationPop marker.icon = icon marker.opacity = opacity existingMarkers.append(coordinate.longitude*coordinate.latitude) } } func getDirections(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D, waypoints: [CLLocationCoordinate2D], color: UIColor) { var directionsUrl = "\(baseDirectionsUrl)origin=\(start.latitude),\(start.longitude)&destination=\(end.latitude),\(end.longitude)" if !waypoints.isEmpty { directionsUrl += "&waypoints=" + waypoints.map { (c: CLLocationCoordinate2D) -> String in "\(c.latitude),\(c.longitude)" }.joinWithSeparator("|") } let directionsNSUrl = NSURL(string: directionsUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!) print("Requesting directions from \(directionsNSUrl)") dispatch_async(dispatch_get_main_queue()) { let directionsData = NSData(contentsOfURL: directionsNSUrl!) do { let response = try NSJSONSerialization.JSONObjectWithData(directionsData!, options: NSJSONReadingOptions.MutableContainers) as! [NSObject:AnyObject] if let routes = response["routes"] as? [[NSObject:AnyObject]] { if let overviewPolyline = routes.first?["overview_polyline"] as? [NSObject:AnyObject] { self.draw(GMSPath(fromEncodedPath: overviewPolyline["points"] as! String), color: color) } else { print("Google Maps response missing overview polyline: \(routes)") } } else { print("Google Maps response missing routes field") } } catch { print("Unable to parse directions response from Google Maps: \(error)") } } } func draw(path: GMSPath, color: UIColor) { let drawnPath = GMSPolyline(path: path) drawnPath?.map = mapView drawnPath?.strokeWidth = 4 drawnPath?.strokeColor = color drawnPaths.append(drawnPath) } func draw(route: Route, color: UIColor) { for action in route.actions { if action.commodity != nil { let color = randomColor() draw(action.commodity!.start!, icon: GMSMarker.markerImageWithColor(color), opacity: 1.0) draw(action.commodity!.destination!, icon: GMSMarker.markerImageWithColor(color), opacity: 0.5) } } var locations = route.coordinates() if locations.count > 1 { let startLocation = locations.removeFirst() let endLocation = locations.removeLast() getDirections(startLocation, end: endLocation, waypoints: locations, color: color) } } func randomColor() -> UIColor { return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1.0) } } // MARK: - ClusterDelegate extension ViewController: ClusterDelegate { func connected(cluster: Cluster) { print("Cluster connected: \(cluster)") for c in cluster.commodities { let color = randomColor() draw(c.start!, icon: GMSMarker.markerImageWithColor(color), opacity: 1.0) draw(c.destination!, icon: GMSMarker.markerImageWithColor(color), opacity: 0.5) } for t in cluster.transports { draw(t.location!, icon: UIImage(named: "car.png")!, opacity: 1.0) } cluster.subscribe() } func transportDidComeOnline(transport: Transport) { print("Transport did come online: \(transport)") } func transportDidGoOffline(transport: Transport) { print("Transport did go offline: \(transport)") } func commodityWasRequested(commodity: Commodity) { print("Commodity was requested: \(commodity)") } func commodityWasPickuped(commodity: Commodity) { print("Commodity was picked up: \(commodity)") } func commodityWasDroppedOff(commodity: Commodity) { print("Commodity was dropped off: \(commodity)") } func commodityWasCancelled(c: Commodity) { print("Commodity was cancelled: \(c)") } func clusterWasRouted(routes: [Route]) { print("Commodity was routed: \(routes)") for drawnPath in drawnPaths { drawnPath.map = nil } drawnPaths.removeAll() for route in routes { draw(route, color: randomColor()) } } }
6e5d32c18dbb873ab1c04634ca022eec
34.045161
156
0.695084
false
false
false
false
damonslu/EvoShare
refs/heads/master
EvoShareSwift/OfferController.swift
unlicense
2
// // OfferController.swift // EvoShareSwift // // Created by Ilya Vlasov on 1/16/15. // Copyright (c) 2015 mtu. All rights reserved. // import Foundation import UIKit class OfferController : UIViewController, ConnectionManagerDelegate { @IBOutlet weak var tottalPriceLabel: UILabel! @IBOutlet weak var currencyLabel: UILabel! var checkID: Int? var summ: String? var curr: String? @IBAction func refusePayment(sender: UIButton) { responseWithBool(false) tottalPriceLabel.text = "0.00" } @IBAction func confirmPayment(sender: UIButton) { responseWithBool(true) } func popOut() { // let vc : MainController = self.storyboard?.instantiateViewControllerWithIdentifier("maincontroller") as MainController // self.navigationController?.popViewControllerAnimated(true) self.performSegueWithIdentifier("backInBlack", sender: self) } func responseWithBool(confirm:Bool) { let locale = NSLocale.currentLocale() let countryCode = locale.objectForKey(NSLocaleCountryCode) as! String var successResponse = ["UID":EVOUidSingleton.sharedInstance.userID(), "LOC":countryCode, "CID":self.checkID!, "ICM":confirm, "DBG":true] as Dictionary<String,AnyObject> var params = ["RQS":successResponse, "M": 219] as Dictionary<String,AnyObject> println("Foundation dictionary for JSON: \(params)") var err: NSError? let finalJSONData = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err) var stringJSON : String = NSString(data: finalJSONData!, encoding: NSUTF8StringEncoding)! ConnectionManager.sharedInstance.socket.writeString(stringJSON) } override func viewDidLoad() { super.viewDidLoad() self.tottalPriceLabel.text = self.summ self.currencyLabel.text = curr } override func didReceiveMemoryWarning() { // } } extension OfferController : ConnectionManagerDelegate { func connectionManagerDidRecieveObject(responseObject: AnyObject) { let jsonContent = responseObject as! [String:AnyObject] let responseDict = jsonContent["C"] as [String:AnyObject] let method : Int = jsonContent["M"] as Int switch method { case 222: let price : Double = responseDict["SUM"] as Double var priceString : String = String(format: "%.2f", price) self.tottalPriceLabel.text = priceString case 219: let isFinished = responseDict["IAP"] as Bool if isFinished { let failAlert = UIAlertController(title: "Offer status", message: "Offer success", preferredStyle: UIAlertControllerStyle.Alert) failAlert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in self.popOut() })) self.presentViewController(failAlert, animated: true, completion: { }) } else { } default: println("asd") } } }
47b051c5405277dfb96f05c2bfabcaa5
33.84375
144
0.619916
false
false
false
false
natecook1000/swift
refs/heads/master
test/SILGen/tsan_instrumentation.swift
apache-2.0
1
// RUN: %target-swift-emit-silgen -sanitize=thread %s | %FileCheck %s // REQUIRES: tsan_runtime func takesInout(_ p: inout Int) { } func takesInout(_ p: inout MyStruct) { } struct MyStruct { var storedProperty: Int = 77 } class MyClass { var storedProperty: Int = 22 } var gStruct = MyStruct() var gClass = MyClass() // CHECK-LABEL: sil hidden @$S20tsan_instrumentation17inoutGlobalStructyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[WRITE]]) : $@convention(thin) (@inout MyStruct) -> () func inoutGlobalStruct() { takesInout(&gStruct) } // CHECK-LABEL: sil hidden @$S20tsan_instrumentation31inoutGlobalStructStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[ELEMENT_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MyStruct, #MyStruct.storedProperty // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[ELEMENT_ADDR]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[ELEMENT_ADDR]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalStructStoredProperty() { // This should generate two TSan inout instrumentations; one for the address // of the global and one for the address of the struct stored property. takesInout(&gStruct.storedProperty) } // CHECK-LABEL: sil hidden @$S20tsan_instrumentation30inoutGlobalClassStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation6gClassAA02MyC0Cvp : $*MyClass // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*MyClass // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[READ]] : $*MyClass // CHECK: end_access [[READ]] // CHECK: [[MODIFY:%.*]] = class_method [[LOADED_CLASS]] : $MyClass, #MyClass.storedProperty!modify.1 : // CHECK: ([[BUFFER_ADDRESS:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[LOADED_CLASS]]) : $@yield_once @convention(method) (@guaranteed MyClass) -> @yields @inout Int // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[BUFFER_ADDRESS]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} apply [[TAKES_INOUT_FUNC]]([[BUFFER_ADDRESS]]) : $@convention(thin) (@inout Int) -> () // CHECK: end_apply [[TOKEN]] // CHECK: destroy_value [[LOADED_CLASS]] func inoutGlobalClassStoredProperty() { // This generates two TSan inout instrumentations. One for the value // buffer that is passed inout to materializeForSet and one for the // temporary buffer passed to takesInout(). takesInout(&gClass.storedProperty) }
32ba2fa9e896a55003e048b702d5e1f2
54.721311
172
0.661371
false
false
false
false
Fluci/CPU-Spy
refs/heads/master
CPU Spy/lib/Sampling/PSSampler/FSPSCommandSplitter.swift
mit
1
// // FSPSCommandSplitter.swift // CPU Spy // // Created by Felice Serena on 18.01.16. // Copyright © 2016 Serena. All rights reserved. // import Foundation /** Analyses a command (like in command line within a console/terminal) and splits it to path, executable name and arguments array. */ public class FSPSCommandSplitter: CommandSplitter { private let commandArgsUpperBounds: [FSString] = [" --", " /", " ./"] private func argSureUpperBound(command: FSString ) -> Int { var argsStart = command.length for u in commandArgsUpperBounds { argsStart = min(argsStart, command.findNext(u)) } return argsStart } public func split(command: FSString) -> (path: FSString?, exec: FSString, args: [FSString]) { var argStart = argSureUpperBound(command) let execStart = command.substring(0, aLength: argStart).findPrev(ASCII.Slash.rawValue)+1 var space = command.findNext(ASCII.Space.rawValue, start: execStart) let argStartTmp = argStart-1 while space < argStartTmp { assert(command[space] == ASCII.Space.rawValue) let nextLetter = command[space+1] if !(ASCII.UpperA.rawValue <= nextLetter && nextLetter <= ASCII.UpperZ.rawValue) { argStart = min(argStart, space+1) break } space = command.findNext(ASCII.Space.rawValue, start: space + 1) } let path: FSString? let exec: FSString if execStart > 0 { path = command.substring(0, aLength: execStart-1).trim(ASCII.Space.rawValue) } else { path = nil } exec = command .substring(execStart, aLength: argStart - execStart) .trim(ASCII.Space.rawValue) let argsStr: FSString if argStart < command.length { argsStr = command.substring(argStart).trim(ASCII.Space.rawValue) } else { argsStr = FSString() } let args: [FSString] = argsStr.componentsSeparatedByString(" ") return (path: path, exec: exec, args: args) } }
9bb52242952bec08dc693654f49d7c88
30.470588
97
0.608411
false
false
false
false
lilongcnc/Swift-weibo2015
refs/heads/master
ILWEIBO04/ILWEIBO04Tests/OAuthViewControllerTests.swift
mit
1
// // OAuthViewControllerTests.swift // 02-TDD // // Created by apple on 15/2/28. // Copyright (c) 2015年 heima. All rights reserved. // import UIKit import XCTest /** 所有要测试的函数都是以 test 开头的 setUp() test1() test2() test3() tearDown() 在跑测试的时候,可以一次跑所有,也可以一次只跑一个 在实际开发中 先写测试-运行是红色的-红灯 再写代码-运行是绿色的-绿灯 重构-红灯,绿灯 单元测试有被叫做红灯绿灯开发! 断言: XCTAssert 提前预判符合某一种条件! - 在单元测试中,如果不符合断言条件,就会报错! - 在正规的代码中,同样可以使用断言 - 在测试的时候,如果不符合条件,运行时会直接崩溃! - 在发布的时候,如果不符合条件,但是代码本身能够执行,会继续执行,断言不会对程序的运行造成任何的影响! - 发布模式,assert 会被忽略 - assert 几乎是所有 C/C++ 程序员的最爱! - 会不会用断言,直接体现开发的经验! - OC 中为什么断言用的那么少呢?因为 oc 是消息机制,可以给 nil 发送消息,不会报错! - 提示:今后开发中,可以大胆的使用断言! - 相当于代码的保护锁!只是在调试模式下有效 */ class OAuthViewControllerTests: XCTestCase { // 在运行测试之前,运行一次,可以做全局的初始化 override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } // 在运行结束之前,运行一次,可以做销毁动作 override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } /// 测试随机的 code func testRandomCode() { for i in 0...20 { let democode = "7b54cde6155f23bc189fad24c150c6a7\(i)" let url = NSURL(string: "http://www.itheima.com/?code=\(democode)")! let result = oauthVC!.continueWithCode(url) XCTAssertFalse(result.load, "不应该加载") XCTAssert(result.code == democode, "code 不正确") } } // MARK: - 测试处理 URL // 测试函数名 test+函数名 // 测试用例:就是测试使用的例子 func testContiuneWithCode() { /** 1. 如果地址的主机是 api.weibo.com,需要加载,否则不加载 2. code 的条件,返回的地址是预先设定的 回调地址 http://www.itheima.com 同样不需要加载 同时 query 是以 code= 开头 需要返回 code 其他的 quert 不需要加载,没有code */ // 登录界面的 URL // 应该加载,没有 code var url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2720451414&redirect_uri=http://www.itheima.com")! var result = oauthVC!.continueWithCode(url) XCTAssertTrue(result.load, "应该加载") XCTAssertNil(result.code, "不应该有code") // 点击注册按钮 // 不加载,没有code url = NSURL(string: "http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=4o1TqS&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D2720451414%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itheima.com%26from%3D%26with_cookie%3D")! result = oauthVC!.continueWithCode(url) XCTAssertFalse(result.load, "不应该加载") XCTAssertNil(result.code, "不应该有code") // 登录成功 url = NSURL(string: "https://api.weibo.com/oauth2/authorize")! result = oauthVC!.continueWithCode(url) XCTAssertTrue(result.load, "应该加载") XCTAssertNil(result.code, "不应该有code") // 授权回调 - 测试用例 let democode = "7b54cde6155f23bc189fad24c150c6a7" url = NSURL(string: "http://www.itheima.com/?code=\(democode)")! result = oauthVC!.continueWithCode(url) XCTAssertFalse(result.load, "不应该加载") XCTAssert(result.code == democode, "code 不正确") // 取消授权 url = NSURL(string: "http://www.itheima.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")! result = oauthVC!.continueWithCode(url) XCTAssertFalse(result.load, "不应该加载") XCTAssertNil(result.code, "不应该有code") // 切换账号 url = NSURL(string: "http://login.sina.com.cn/sso/logout.php?entry=openapi&r=https%3A%2F%2Fapi.weibo.com%2Foauth2%2Fauthorize%3Fclient_id%3D2720451414%26redirect_uri%3Dhttp%3A%2F%2Fwww.itheima.com")! result = oauthVC!.continueWithCode(url) XCTAssertFalse(result.load, "不应该加载") XCTAssertNil(result.code, "不应该有code") } // MARK: - 测试界面 /** 1. 从 storyboard加载viewControlller 2. 根视图是 UIWebView 3. webView的代理是视图控制器 */ // 根视图是 UIWebView func testRootView() { let view = oauthVC!.view // 断言:视图是一个 UIWebView,如果不是 UIWebView 就会报错! XCTAssert(view.isKindOfClass(UIWebView.self), "根视图类型不是 webView") } /// 测试根视图控制器的代理 func testRootViewDelegate() { let webView = oauthVC!.view as! UIWebView // === 是 swift 中判断两个对象是否恒等的方法,对象类型相同,指针地址一致 XCTAssert(webView.delegate === oauthVC!, "没有设置代理") } /// 测试使用的视图控制器 lazy var oauthVC: OAuthViewController? = { let bundle = NSBundle(forClass: OAuthViewControllerTests.self) println(bundle) let sb = UIStoryboard(name: "Main", bundle: bundle) // 拿到视图控制器 return sb.instantiateInitialViewController() as? OAuthViewController }() }
af6636ee2ec8141111c3ff230fa8ab17
30.675159
297
0.618942
false
true
false
false
renyufei8023/WeiBo
refs/heads/master
Pod/Classes/Controller/PreviewViewController.swift
mit
2
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 final class PreviewViewController : UIViewController { var imageView: UIImageView? private var fullscreen = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) view.backgroundColor = UIColor.whiteColor() imageView = UIImageView(frame: view.bounds) imageView?.contentMode = .ScaleAspectFit imageView?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] view.addSubview(imageView!) let tapRecognizer = UITapGestureRecognizer() tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.addTarget(self, action: "toggleFullscreen") view.addGestureRecognizer(tapRecognizer) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func loadView() { super.loadView() } func toggleFullscreen() { fullscreen = !fullscreen UIView.animateWithDuration(0.3, animations: { () -> Void in self.toggleNavigationBar() self.toggleStatusBar() self.toggleBackgroundColor() }) } func toggleNavigationBar() { navigationController?.setNavigationBarHidden(fullscreen, animated: true) } func toggleStatusBar() { self.setNeedsStatusBarAppearanceUpdate() } func toggleBackgroundColor() { let aColor: UIColor if self.fullscreen { aColor = UIColor.blackColor() } else { aColor = UIColor.whiteColor() } self.view.backgroundColor = aColor } override func prefersStatusBarHidden() -> Bool { return fullscreen } }
e73234a367de786ef94809240b78fa17
33.741176
84
0.676261
false
false
false
false
claudetech/swift-box
refs/heads/master
box/Box.swift
mit
1
// // Box.swift // box // // Created by Daniel Perez on 2015/05/03. // Copyright (c) 2015 ClaudeTech. All rights reserved. // import Foundation public enum Box<T> { case Full(ValueWrapper<T>) case Failure(NSError) case Empty public init(_ value: T) { self = .Full(ValueWrapper(value)) } public init(_ failure: NSError) { self = .Failure(failure) } public var value: T? { switch self { case .Full(let v): return v.value default: return nil } } public var failure: NSError? { switch self { case .Failure(let e): return e default: return nil } } public func isFull() -> Bool { return value != nil } public func isFailure() -> Bool { return failure != nil } public func isEmpty() -> Bool { return !isFailure() && !isFull() } } public func == <T: Equatable>(left: Box<T>, right: Box<T>) -> Bool { switch (left, right) { case (.Full(let v1), .Full(let v2)): return v1 == v2 case (.Failure(let e1), .Failure(let e2)): return e1 == e2 case (.Empty, .Empty): return true default: return false } } postfix operator >! {} public postfix func >!<T>(box: Box<T>) -> T { return box.value! }
ecd0ef836d99f13aeffd791e208b9f32
18.458333
68
0.511777
false
false
false
false
luinily/hOme
refs/heads/master
hOme/UI/NewDeviceNameCell.swift
mit
1
// // NewDeviceNameCell.swift // hOme // // Created by Coldefy Yoann on 2016/04/29. // Copyright © 2016年 YoannColdefy. All rights reserved. // import Foundation import UIKit class NewDeviceNameCell: UITableViewCell { @IBOutlet weak var textEdit: UITextField! private var _name: String = "New Device" private var _onNameChanged: ((_ newName: String) -> Void)? var name: String { get {return _name} set { _name = newValue textEdit.text = newValue } } var onNameChanged: ((_ newName: String) -> Void)? { get {return _onNameChanged} set { _onNameChanged = newValue } } @IBAction func onValueChanged(_ sender: AnyObject) { if let newName = textEdit.text { _name = newName _onNameChanged?(newName) } } }
9ca925cd87c6f2352efb2ce4df48c226
17.047619
59
0.663588
false
false
false
false
younata/RSSClient
refs/heads/master
TethysKit/Realm/RealmObjects.swift
mit
1
import RealmSwift import Foundation #if os(iOS) import UIKit #else import Cocoa #endif final class RealmString: Object { @objc dynamic var string: String = "" convenience init(string: String) { self.init(value: ["string": string]) } override static func primaryKey() -> String? { return "string" } } enum FeedSource: String { case local case inoreader } final class RealmFeed: Object { @objc dynamic var title = "" @objc dynamic var url = "" @objc dynamic var summary = "" let tags = List<RealmString>() var articles = LinkingObjects(fromType: RealmArticle.self, property: "feed") @objc dynamic var imageData: Data? @objc dynamic var settings: RealmSettings? @objc private dynamic var _source = "local" var source: FeedSource { get { return FeedSource(rawValue: self._source)! } set { self._source = newValue.rawValue } } @objc dynamic var id: String = UUID().uuidString override static func primaryKey() -> String? { return "id" } override static func indexedProperties() -> [String] { return ["url", "title"] } } final class RealmAuthor: Object { @objc dynamic var name = "" @objc dynamic var email: String? convenience init(name: String, email: URL?) { self.init(value: ["name": name, "email": email?.absoluteString]) } @objc dynamic var id: String = UUID().uuidString override static func primaryKey() -> String? { return "id" } override static func indexedProperties() -> [String] { return ["name", "email"] } } final class RealmArticle: Object { @objc dynamic var title: String? @objc dynamic var link = "" @objc dynamic var summary: String? @objc dynamic var published = Date(timeIntervalSinceNow: 0) @objc dynamic var updatedAt: Date? @objc dynamic var date: Date { return updatedAt ?? published } @objc dynamic var identifier: String? @objc dynamic var content: String? @objc dynamic var read = false @objc dynamic var estimatedReadingTime: Double = 0 @objc dynamic var feed: RealmFeed? let authors = List<RealmAuthor>() @objc dynamic var id: String = UUID().uuidString override static func primaryKey() -> String? { return "id" } override static func indexedProperties() -> [String] { return ["link", "published", "updatedAt", "title", "read"] } } final class RealmSettings: Object { @objc dynamic var maxNumberOfArticles = 0 }
d9955c37015865ebe9f6c92559651f60
24.623762
80
0.630989
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/Array/18_4Sum.swift
mit
1
// // 18_4Sum.swift // LeetcodeSwift // // Created by yansong li on 2016-11-02. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:18 4 Sum URL: https://leetcode.com/problems/4sum/ Space: O(N^2) Time: O(N^4) */ class FourSum_Solution { func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { guard nums.count > 3 else { return [] } let nums = nums.sorted() var ret: [[Int]] = [] for i in 0..<nums.count - 3 { if i - 1 >= 0 && nums[i] == nums[i - 1] { continue } var left = i + 1 while left < nums.count - 2 { var leftMiddle: Int = left + 1 var right = nums.count - 1 while leftMiddle < right { if nums[i] + nums[left] + nums[leftMiddle] + nums[right] == target { ret.append([nums[i], nums[left], nums[leftMiddle], nums[right]]) leftMiddle += 1 while leftMiddle < right && nums[leftMiddle] == nums[leftMiddle - 1] { leftMiddle += 1 } right -= 1 while leftMiddle < right && nums[right] == nums[right + 1] { right -= 1 } } else if nums[i] + nums[left] + nums[leftMiddle] + nums[right] < target { leftMiddle += 1 while leftMiddle < right && nums[leftMiddle] == nums[leftMiddle - 1] { leftMiddle += 1 } } else { right -= 1 while leftMiddle < right && nums[right] == nums[right + 1] { right -= 1 } } } left += 1 while left < nums.count - 1 && nums[left] == nums[left - 1] { left += 1 } } } return ret } func test() { let result = fourSum([-1, -5, -5, -3, 2, 5, 0, 4], -7) print(result) } }
35ea8a88bdaaa6914ec5fd7e84d7476a
25.637681
84
0.477149
false
false
false
false
grigaci/RateMyTalkAtMobOS
refs/heads/master
RateMyTalkAtMobOS/Classes/Helpers/Extensions/NSError+App.swift
bsd-3-clause
1
// // NSError+App.swift // RateMyTalkAtMobOS // // Created by Bogdan Iusco on 10/18/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import Foundation extension NSError { class var titleKey: String { get { return "windowTitle" } } class var descriptionKey: String { get { return "windowDescription" } } class var appDomain: String { get { return "RMTRateMyTalk" } } var titleText: String? { get { if let dictionary = self.userInfo { if let title = dictionary[NSError.titleKey] as? NSString { return title } } return nil } } var descriptionText: String? { get { if let dictionary = self.userInfo { if let description = dictionary[NSError.descriptionKey] as? NSString { return description } } return nil } } class func internetConnectionError() -> NSError { let title = NSLocalizedString("No connection", comment: "No internet error title") let description = NSLocalizedString("Please check your internet connection.", comment: "No internet error description") var userInfo = [NSError.titleKey : title, NSError.descriptionKey : description] let error = NSError(domain: NSError.appDomain, code: 0, userInfo: userInfo) return error } class func cloudKitConnectionError() -> NSError { let title = NSLocalizedString("CloudKit error", comment: "Cloudkit error title") let description = NSLocalizedString("Cannot sync your ratings. Please make sure that you are logged into your iCloud account and iCloud Drive is enabled.", comment: "Cloudkit error description") var userInfo = [NSError.titleKey : title, NSError.descriptionKey : description] let error = NSError(domain: NSError.appDomain, code: 0, userInfo: userInfo) return error } }
f8a02d1d44bb56b951288ba2fdcc01b3
30.119403
202
0.596643
false
false
false
false
andrea-prearo/SwiftExamples
refs/heads/master
SQLiteConnectionPool/SQLiteConnectionPool/SQLiteConnectionPoolConcurrentAsync.swift
mit
1
// // SQLiteConnectionPoolConcurrentAsync.swift // SQLiteConnectionPool // // Created by Andrea Prearo on 1/20/19. // Copyright © 2019 Andrea Prearo. All rights reserved. // import Foundation public class SQLiteConnectionPoolConcurrentAsync { public static let shared = SQLiteConnectionPoolConcurrentAsync() private var connectedDatabases = Set<SQLiteConnection>() private var queue = DispatchQueue(label: "com.aprearo.connectionPool.concurrentQueueAsync", qos: .background, attributes: .concurrent) public func connectToDatabase(filename: String, completion: @escaping (SQLiteConnection?) -> Void, failure: @escaping (Error) -> Void) { queue.async(flags: .barrier) { if let database = self.connectedDatabase(filename: filename) { return completion(database) } do { let newDatabase = try SQLiteConnection(filename: filename) self.connectedDatabases.insert(newDatabase) return completion(newDatabase) } catch let error { return failure(error) } } } public func disconnectFromDatabase(filename: String, completion: @escaping (Bool) -> Void, failure: @escaping (Error) -> Void) { queue.async(flags: .barrier) { for database in self.connectedDatabases { if database.filename == filename { guard let connection = self.connectedDatabases.remove(database) else { return } do { try connection.close() return completion(true) } catch let error { return failure(error) } } } return completion(false) } } public func connectedDatabase(filename: String, completion: @escaping (SQLiteConnection?) -> Void) { queue.sync { return completion(connectedDatabase(filename: filename)) } } public func disconnectFromAllDatabases(completion: @escaping () -> Void, failure: @escaping (Error) -> Void) { queue.async(flags: .barrier) { self.connectedDatabases.forEach { connection in do { try connection.close() } catch let error { failure(error) } } self.connectedDatabases.removeAll() return completion() } } public var connectedDatabasesCount: Int { return queue.sync { connectedDatabases.count } } private func connectedDatabase(filename: String) -> SQLiteConnection? { let connectedDatabases = self.connectedDatabases for database in connectedDatabases { if database.filename == filename { return database } } return nil } }
eb917108b66201bdfc1f9c37fc3cecad
35.08046
138
0.546352
false
false
false
false
brenogazzola/CabCentral
refs/heads/master
CabCentral/MapController.swift
mit
1
// // ViewController.swift // CabCentral // // Created by Breno Gazzola on 8/27/15. // Copyright (c) 2015 Breno Gazzola. All rights reserved. // // This class contains the minimum functionality for the map // It will display the user location, handle location and // region changes and ensure location authorization // Anything aside from that should be done on other files // as extensions to this class // import UIKit import MapKit class MapController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { // MARK: - Constants and Properties // MARK: Location /// Default region size to show when request to center on use let regionRadius : CLLocationDistance = 500 /// Indicates if the mapView can center itself on the user var shouldCenterOnUserLocation = true // TODO: Find a way to get authorization using the mapView's location manager /// Used to get the initial authorization to get the user's location var locationManager: CLLocationManager? /// Used to decode the user's current location into something readable let geocoder = CLGeocoder() // MARK: Update /// Update timer var timer = NSTimer() /// Indicates theres a user search in progress so you don't start a new one var searchNearUserInProgress = false /// Indicates theres a region search in progress so you don't start a new one var searchInRegionInProgress = false // MARK: Annotations /// Stores known drivers to we can update then later var knownDrivers = [Int:Driver]() /// How many drivers we can track at once var knownDriversPoolSize = 200 // MARK: Outlets @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var addressLabel: UILabel! // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() ensureLocationAuthorized() } // MARK: - MapView Delegate /** Center the map on the user location the first time mapView */ func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){ // Only let the map center on the user if it's being shown for the first time. // We don't want to reset the view back to the user while he is busy panning around the map if shouldCenterOnUserLocation { shouldCenterOnUserLocation = false timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "searchDrivers", userInfo: nil, repeats: true) centerOnUser() } } func mapView(mapView: MKMapView!, regionDidChangeAnimated animated: Bool) { displayDrivers() } // MARK: - Compass Button @IBAction func locationButtonClicked(sender: UIBarButtonItem) { centerOnUser() } /** Centers the map on the user's current location */ func centerOnUser() { let userLocation = mapView.userLocation.location let coordinateRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, regionRadius, regionRadius) mapView.setRegion(coordinateRegion, animated: true) decodeUserLocation() } // MARK: - Authorization /** Ensures that the app has permission to use the user's location. If authorized, it tells the map to center on the user. If not, it makes the request */ func ensureLocationAuthorized() { let authorizationStatus = CLLocationManager.authorizationStatus() switch authorizationStatus { case .NotDetermined, .Restricted, .Denied: locationManager = CLLocationManager() locationManager!.delegate = self locationManager!.requestWhenInUseAuthorization() default: self.mapView.showsUserLocation = true } } /** Watches for changes in authorization so the app can start updating the user's location */ func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .AuthorizedWhenInUse, .AuthorizedAlways: self.mapView.showsUserLocation = true // Kill the manager, MapView already has it's own locationManager = nil default: // TODO: Figure out what I should do if the user doesn't give me authorization break } } }
77d8eb10e0ae4822bf478293f4c15e0c
32.19403
132
0.67034
false
false
false
false
edstewbob/cs193p-winter-2015
refs/heads/master
GraphingCalculator/GraphingCalculator/GraphView.swift
mit
2
// // GraphView.swift // GraphingCalculator // // Created by jrm on 4/5/15. // Copyright (c) 2015 Riesam LLC. All rights reserved. // import UIKit protocol GraphViewDataSource: class { func pointsForGraphView(sender: GraphView) -> [CGPoint] } @IBDesignable class GraphView: UIView { var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } } var color: UIColor = UIColor.blackColor() { didSet { setNeedsDisplay() } } @IBInspectable var scale: CGFloat = 50.0{ didSet { updateRange() setNeedsDisplay() } } var viewCenter: CGPoint { return convertPoint(center, fromView: superview) } var axesOrigin: CGPoint = CGPoint(x: 0, y: 0) { didSet { updateRange() setNeedsDisplay() } } //range on x axis for which to request data points var range_min_x: CGFloat = -100.0 var range_max_x: CGFloat = 100.0 //increment value for x points on axis var increment: CGFloat = 1.0 func updateRange(){ range_min_x = -axesOrigin.x / scale //println("In updateRange, axesOrigin.x: \(axesOrigin.x) bounds.size.width: \(bounds.size.width) range_min_x: \(range_min_x)" ) range_max_x = range_min_x + (bounds.size.width / scale) //println("In updateRange, axesOrigin.x: \(axesOrigin.x) bounds.size.width: \(bounds.size.width) range_max_x: \(range_max_x)" ) increment = (1.0/scale) //println("In updateRange, scale: \(scale) increment value: \(increment) " ) } // viewBounds passed to AxesDrawer private var viewBounds: CGRect { return CGRect( origin: CGPoint(x: 0, y: 0), size: bounds.size ) } weak var dataSource: GraphViewDataSource? override func drawRect(rect: CGRect) { //println("In drawRect, scale = \(scale)") let axesDrawer = AxesDrawer( color: color, contentScaleFactor: contentScaleFactor ) axesDrawer.drawAxesInRect( viewBounds, origin: axesOrigin, pointsPerUnit: scale ) let path = UIBezierPath() path.lineWidth = lineWidth color.set() if var points = dataSource?.pointsForGraphView(self) { if(points.count > 1){ let firstPoint = points.removeAtIndex(0); path.moveToPoint(firstPoint) for point in points { path.addLineToPoint(point) } } } path.stroke() } // MARK: - gestures func processPinch(gesture: UIPinchGestureRecognizer) { //println("entered GraphView.processPinch() ") if gesture.state == .Changed { //println("gesture.scale \(gesture.scale)") scale *= gesture.scale gesture.scale = 1.0 } } func processPan(gesture: UIPanGestureRecognizer) { //println("entered GraphViewController.processPan() ") switch gesture.state { case .Ended: fallthrough case .Changed: let translation = gesture.translationInView(self) let movementY = translation.y let movementX = translation.x if movementX != 0 || movementY != 0{ axesOrigin.x += movementX axesOrigin.y += movementY gesture.setTranslation(CGPointZero, inView: self) //println("movementX \(movementX), movementY \(movementY)") } default: break } } func processTap(gesture: UITapGestureRecognizer){ //println("entered GraphViewController.processTap() ") if gesture.state == .Ended { axesOrigin = gesture.locationInView(self) } } }
804f8dda18ee1516d7c084dc39b7151d
26.944056
135
0.549049
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Banking
refs/heads/master
HatchReadyApp/apps/Hatch/iphone/native/HatchReadyAppHatchIphoneTests/LoginTest.swift
epl-1.0
2
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit import XCTest import Hatch class LoginTest: XCTestCase { var loginManager: LoginDataManager! var dashboardDataManager: DashboardDataManager! override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. loginManager = LoginDataManager.sharedInstance dashboardDataManager = DashboardDataManager.sharedInstance } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testValidLogin() { let username = "u1" let password = "p1" // Ensure user data is empty. // Fire authentication. //loginManager.submitAuthentication(username, password: password) // Check that login succeeds by seeing that user data has loaded. } func testInvalidLogin() { let username = "fakeuser" let password = "fakepassword" // Ensure user data is empty. // Fire authentication. //loginManager.submitAuthentication(username, password: password) // Check that login fails by seeing that user data is still empty. } func testChallengeAuth() { // Ensure user is not authenticated and login is nil. //XCTAssertNil(loginManager.challengeHandler.loginViewController, "loginViewController is not nil and has already be instantiated.") // Attempt to access protected data. //dashboardDataManager.getDashboardDataTest() // Check that challenge handler fires. //sleep(1) //XCTAssertNotNil(loginManager.challengeHandler.loginViewController, "loginVC is still nil and has not been successfully instantiated.") } }
af2d261a7c247c0867f14883ed638451
30.484375
144
0.652605
false
true
false
false
Adorkable/Eunomia
refs/heads/master
Source/Core/UtilityExtensions/CLLocation+Utility.swift
mit
1
// // CLLocation+Utility.swift // Eunomia // // Created by Ian Grossberg on 8/24/18. // Copyright © 2018 Adorkable. All rights reserved. // import Foundation import CoreLocation extension CLLocation { public convenience init(latitude: Measurement<UnitAngle>, longitude: Measurement<UnitAngle>) { self.init(latitude: CLLocationDegrees(from: latitude), longitude: CLLocationDegrees(from: longitude)) } public convenience init(coordinate: CLLocationCoordinate2D) { self.init(latitude: coordinate.latitude, longitude: coordinate.longitude) } } extension CLLocation { public func closest(from: [CLLocation]) -> CLLocation? { var result: CLLocation? = nil var closestDistance: CLLocationDistance = CLLocationDistance.infinity for testLocation in from { let testDistance = self.distance(from: testLocation) if result == nil || testDistance < closestDistance { result = testLocation closestDistance = testDistance } } return result } } extension CLLocation { public func heading(to: CLLocation) -> Measurement<UnitAngle> { return self.coordinate.heading(to: to.coordinate) } public func heading(to: CLLocation) -> CLLocationDirection { return self.coordinate.heading(to: to.coordinate) } } extension CLLocation: Encodable { public enum CodingKeys: String, CodingKey { case latitude case longitude case altitude case horizontalAccuracy case verticalAccuracy case speed case course case timestamp } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(coordinate.latitude, forKey: .latitude) try container.encode(coordinate.longitude, forKey: .longitude) try container.encode(altitude, forKey: .altitude) try container.encode(horizontalAccuracy, forKey: .horizontalAccuracy) try container.encode(verticalAccuracy, forKey: .verticalAccuracy) try container.encode(speed, forKey: .speed) try container.encode(course, forKey: .course) try container.encode(timestamp, forKey: .timestamp) } } // Based on https://medium.com/@kf99916/codable-nsmanagedobject-and-cllocation-in-swift-4-b32f042cb7d3 public struct CodableLocation: Codable { let latitude: CLLocationDegrees let longitude: CLLocationDegrees let altitude: CLLocationDistance let horizontalAccuracy: CLLocationAccuracy let verticalAccuracy: CLLocationAccuracy let speed: CLLocationSpeed let course: CLLocationDirection let timestamp: Date var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake(self.latitude, self.longitude) } init(latitude: CLLocationDegrees, longitude: CLLocationDegrees, altitude: CLLocationDistance, horizontalAccuracy: CLLocationAccuracy, verticalAccuracy: CLLocationAccuracy, speed: CLLocationSpeed, course: CLLocationDirection, timestamp: Date) { self.latitude = latitude self.longitude = longitude self.altitude = altitude self.horizontalAccuracy = horizontalAccuracy self.verticalAccuracy = verticalAccuracy self.speed = speed self.course = course self.timestamp = timestamp } public init(from: CLLocation) { self.init(latitude: from.coordinate.latitude, longitude: from.coordinate.longitude, altitude: from.altitude, horizontalAccuracy: from.horizontalAccuracy, verticalAccuracy: from.verticalAccuracy, speed: from.speed, course: from.course, timestamp: from.timestamp) } } extension CLLocation { public convenience init(model: CodableLocation) { self.init(coordinate: model.coordinate, altitude: model.altitude, horizontalAccuracy: model.horizontalAccuracy, verticalAccuracy: model.verticalAccuracy, course: model.course, speed: model.speed, timestamp: model.timestamp) } } // //extension CLLocation: Decodable { // enum CodingKeys: String, CodingKey { // case latitude = "latitude" // case longitude = "longitude" // } // public convenience init(from decoder: Decoder) throws { // let container = try decoder.container(keyedBy: CLLocation.CodingKeys.self) // let latitude = try container.decode(CLLocationDegrees.self, forKey: .latitude) // let longitude = try container.decode(CLLocationDegrees.self, forKey: .longitude) // // self.init(latitude: latitude, longitude: longitude) // } //}
e7c1b7bdbdd99e8f34378630eacd427c
34.636364
269
0.693452
false
false
false
false
JadenGeller/Gluey
refs/heads/master
Sources/Gluey/DriedGlue.swift
mit
1
// // DriedGlue.swift // Gluey // // Created by Jaden Geller on 1/18/16. // Copyright © 2016 Jaden Geller. All rights reserved. // /// A snapshot of a previous `Glue` value that can be restored at a later date. internal struct DriedGlue<Element: Equatable> { internal var value: Element? internal var bindings: Set<Binding<Element>> = [] /// Construct a `Glue` with no bindings that's bound to `value`. internal init(glue: Glue<Element>) { self.value = glue.value self.bindings = glue.bindings } } extension Glue { /// Restore by creating a new `Glue` value from the saved stated, and updating /// all saved bindings to utilize this `Glue`. static func restore(_ dried: DriedGlue<Element>) { let restored = Glue(value: dried.value) for binding in dried.bindings { binding.glue = restored } } }
6543fe0709d89b011f42fbb55bb145e2
28.096774
82
0.636364
false
false
false
false
HackerEdu/dreaminglwjfrog
refs/heads/master
xogame/xogame/ViewController.swift
mit
1
// // ViewController.swift // xogame // // Created by Weimu on 15-4-18. // Copyright (c) 2015年 Weimu. All rights reserved. // import UIKit class ViewController: UIViewController { private var osturn:Int!//1表示o,2表示x private var chessboard = [[Int]](count:3,repeatedValue: [Int](count:3,repeatedValue:0)) private var isgameover:Bool = false // @IBOutlet weak var btnselx: UIButton! // @IBOutlet weak var btnselo: UIButton! @IBOutlet weak var labelplayer: UILabel! @IBOutlet weak var gz00: UIButton! @IBOutlet weak var gz01: UIButton! @IBOutlet weak var gz02: UIButton! @IBOutlet weak var gz10: UIButton! @IBOutlet weak var gz11: UIButton! @IBOutlet weak var gz12: UIButton! @IBOutlet weak var gz20: UIButton! @IBOutlet weak var gz21: UIButton! @IBOutlet weak var gz22: UIButton! @IBOutlet weak var msglabel: UILabel! private func printArr() { for var i = 0; i < 3; i++ { for var j = 0; j < 3; j++ { print( "\(chessboard[ i ][ j ]) " ) } print( "\n" ) } } private func showChessBoard() { gz00.setTitle(CalCellValue( chessboard[0][0] ), forState:UIControlState.Normal) gz01.setTitle(CalCellValue( chessboard[0][1] ), forState:UIControlState.Normal) gz02.setTitle(CalCellValue( chessboard[0][2] ), forState:UIControlState.Normal) gz10.setTitle(CalCellValue( chessboard[1][0] ), forState:UIControlState.Normal) gz11.setTitle(CalCellValue( chessboard[1][1] ), forState:UIControlState.Normal) gz12.setTitle(CalCellValue( chessboard[1][2] ), forState:UIControlState.Normal) gz20.setTitle(CalCellValue( chessboard[2][0] ), forState:UIControlState.Normal) gz21.setTitle(CalCellValue( chessboard[2][1] ), forState:UIControlState.Normal) gz22.setTitle(CalCellValue( chessboard[2][2] ), forState:UIControlState.Normal) } private func CalCellValue( V:Int )->NSString { switch V { case 0: return "_" case 1: return "o" case 2: return "x" default:return "_" } } private func checkCB( ix:Int, iy:Int, ValueNum:Int )->Bool { println( "ix:\(ix) iy:\(iy) ValueNum:\(ValueNum)" ) var bwin:Bool = true //判断第一条路径--横向 for var i = 0; i < 3; i++ { if chessboard[ix][i] != ValueNum { bwin = false break } } if bwin { return true; } //判断第二条路径--纵向 bwin = true; for var i = 0; i < 3; i++ { if chessboard[i][iy] != ValueNum { bwin = false break } } if bwin { return true; } // //如果是处在没有斜角的位置,返回false // if ix == 1 || iy == 1 // { // if ix ==0 || iy == 0 // { // return false // } // } //判断第三条路径--左上到右下 bwin = true; for var i = 0; i < 3; i++ { if chessboard[ i ][ i ] != ValueNum { bwin = false } } if bwin { return true } //判断第四条路径--左下到右上 bwin = true for var i = 0; i < 3; i++ { if chessboard[ i ][ 2 - i ] != ValueNum { bwin = false } } if bwin { return true } return false } private func isTie()->Bool { for var i = 0; i < 3; i++ { for var j = 0; j < 3; j++ { if chessboard[ i ][ j ] == 0 { return false } } } return true } private func showWinner() { if osturn == 1 { msglabel.text = "o win" } else { msglabel.text = "x win" } } private func dealWithBtnClick( ix:Int, iy:Int ) { println( "ix:\( ix ) iy:\( iy )" ) if chessboard[ ix ][ iy ] != 0 || isgameover { return } self.chessboard[ ix ][ iy ] = self.osturn showChessBoard() self.printArr() //判断是否胜利 if checkCB( ix, iy:iy, ValueNum:self.osturn ) { showWinner() isgameover = true } else if isTie()//判断是否平局 { msglabel.text = " tie " } if osturn == 1 { osturn = 2 } else { osturn = 1 } labelplayer.text = CalCellValue( osturn ) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. osturn = 1 labelplayer.text = CalCellValue( osturn ) //self.btnselo.backgroundColor = UIColor.redColor() self.printArr() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // @IBAction func btnclickedx(sender: AnyObject) { // self.btnselx.backgroundColor = UIColor.redColor() // self.btnselo.backgroundColor = UIColor.clearColor() // osturn = 2 // } // // // @IBAction func btnclickedo(sender: AnyObject) { // self.btnselx.backgroundColor = UIColor.clearColor() // self.btnselo.backgroundColor = UIColor.redColor() // osturn = 1 // } @IBAction func ongz00(sender: AnyObject) { dealWithBtnClick( 0, iy:0 ) } @IBAction func ongz01(sender: AnyObject) { dealWithBtnClick( 0, iy:1 ) } @IBAction func ongz02(sender: AnyObject) { dealWithBtnClick( 0, iy:2 ) } @IBAction func ongz10(sender: AnyObject) { dealWithBtnClick( 1, iy:0 ) } @IBAction func ongz11(sender: AnyObject) { dealWithBtnClick( 1, iy:1 ) } @IBAction func ongz12(sender: AnyObject) { dealWithBtnClick( 1, iy:2 ) } @IBAction func ongz20(sender: AnyObject) { dealWithBtnClick( 2, iy:0 ) } @IBAction func ongz21(sender: AnyObject) { dealWithBtnClick( 2, iy:1 ) } @IBAction func ongz22(sender: AnyObject) { dealWithBtnClick( 2, iy:2 ) } @IBAction func btnReGame(sender: AnyObject) { osturn = 1 labelplayer.text = CalCellValue( osturn ) isgameover = false for var i = 0; i < 3; i++ { for var j = 0; j < 3; j++ { chessboard[ i ][ j ] = 0 } } msglabel.text = "" showChessBoard() } }
9edf6cf29b5e2aa5aaf0a061ec1b07a1
23.261017
91
0.481067
false
false
false
false
mperovic/my41
refs/heads/master
my41/Classes/CalculatorWindow.swift
bsd-3-clause
1
// // CalculatorWindow.swift // my41 // // Created by Miroslav Perovic on 8/28/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation import Cocoa typealias DisplayFont = [DisplaySegmentMap] typealias DisplaySegmentPaths = [NSBezierPath] class CalculatorWindowController: NSWindowController { } class CalculatorWindow : NSWindow { //This point is used in dragging to mark the initial click location var initialLocation: NSPoint? override init( contentRect: NSRect, styleMask style: NSWindow.StyleMask, backing backingStoreType: NSWindow.BackingStoreType, defer flag: Bool) { super.init(contentRect: contentRect, styleMask: style, backing: backingStoreType, defer: flag) } override var acceptsFirstResponder: Bool { return true } override func awakeFromNib() { let appDelegate = CalculatorApplication.shared.delegate as! AppDelegate appDelegate.window = self self.isExcludedFromWindowsMenu = false self.backgroundColor = NSColor.clear self.isOpaque = false self.hasShadow = true } override var canBecomeMain: Bool { get { return true } } override var canBecomeKey: Bool { get { return true } } override func mouseDown(with theEvent: NSEvent) { initialLocation = theEvent.locationInWindow } override func mouseDragged(with theEvent: NSEvent) { let appDelegate = NSApplication.shared.delegate as! AppDelegate if appDelegate.buttonPressed { return } if let iLocation = initialLocation { let screenVisibleFrame = NSScreen.main()?.visibleFrame let windowFrame = self.frame var newOrigin = windowFrame.origin // Get the mouse location in window coordinates. let currentLocation = theEvent.locationInWindow // Update the origin with the difference between the new mouse location and the old mouse location. newOrigin.x += (currentLocation.x - iLocation.x) newOrigin.y += (currentLocation.y - iLocation.y) // Don't let window get dragged up under the menu bar if ((newOrigin.y + windowFrame.size.height) > (screenVisibleFrame!.origin.y + screenVisibleFrame!.size.height)) { newOrigin.y = screenVisibleFrame!.origin.y + (screenVisibleFrame!.size.height - windowFrame.size.height) } // Move the window to the new location self.setFrameOrigin(newOrigin) } } override func mouseUp(with theEvent: NSEvent) { initialLocation = nil } } class Display : NSView, Peripheral { let numDisplayCells = 12 let numAnnunciators = 12 let numDisplaySegments = 17 let numFontChars = 128 var on: Bool = true var updateCountdown: Int = 0 var registers = DisplayRegisters() var displayFont = DisplayFont() var segmentPaths = DisplaySegmentPaths() var annunciatorFont: NSFont? var annunciatorFontScale: CGFloat = 1.2 var annunciatorFontSize: CGFloat = 9.0 var annunciatorBottomMargin: CGFloat = 4.0 var annunciatorPositions: [NSPoint] = [NSPoint](repeating: NSMakePoint(0.0, 0.0), count: 12) var foregroundColor: NSColor? var contrast: Digit { set { self.contrast = newValue & 0xf scheduleUpdate() } get { return self.contrast } } // override init() { // // super.init() // } override init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { super.init(coder: coder) } override func awakeFromNib() { calculatorController.display = self self.foregroundColor = NSColorList(name: "HP41").color(withKey: "displayForegroundColor") self.displayFont = self.loadFont("hpfont") // self.segmentPaths = self.loadSegmentPaths("hpchar") self.segmentPaths = bezierPaths() self.annunciatorFont = NSFont(name: "Menlo", size:self.annunciatorFontScale * self.annunciatorFontSize) self.annunciatorPositions = self.calculateAnnunciatorPositions(font: self.annunciatorFont!, inRect: self.bounds) self.on = true self.updateCountdown = 2 bus.installPeripheral(self, inSlot: 0xFD) bus.display = self for idx in 0..<self.numDisplayCells { self.registers.A[idx] = 0xA self.registers.B[idx] = 0x3 self.registers.C[idx] = 0x2 self.registers.E = 0xfff } //-- initialize the display character to unicode lookup table: // The table simply contains one unicode character for each X-41 hardware character // index (0x00..0x7f). The file can be tweaked for whatever translation is desired. // Character groups (approximated): // 0x00..0x1f: A-Z uppercase characters // 0x20..0x3f: ASCII-like symbols and numbers // 0x40..0x4f: a-e + "hangman" // 0x50..0x5f: some greek characters + "hangman" // 0x60..0x7f: a-z lowercase characters let filename: String = Bundle.main.path(forResource: CTULookupRsrcName, ofType: CTULookupRsrcType)! let mString: NSMutableString = try! NSMutableString(contentsOfFile: filename, encoding: String.Encoding.unicode.rawValue) CTULookup = String(mString) CTULookupLength = (CTULookup!).characters.count } override var isFlipped:Bool{ return true } override func draw(_ dirtyRect: NSRect) { if on { let cellTranslation = NSAffineTransform() cellTranslation.translateX(by: cellWidth(), yBy: 0.0) foregroundColor?.set() if true { NSGraphicsContext.saveGraphicsState() for idx in 0..<numDisplayCells { let segmentsOn = segmentsForCell(idx) for seg in 0..<numDisplaySegments { if (segmentsOn & (1 << UInt32(seg))) != 0 { segmentPaths[seg].fill() } } cellTranslation.concat() } NSGraphicsContext.restoreGraphicsState() } self.lockFocus() let attrs = [ NSAttributedString.Key.font: annunciatorFont! ] calculatorController.prgmMode = false calculatorController.alphaMode = false for idx in 0..<numAnnunciators { if annunciatorOn(idx) { if idx == 10 { calculatorController.prgmMode = true } if idx == 11 { calculatorController.alphaMode = true } let transformation = NSAffineTransform() let point = annunciatorPositions[idx] transformation.translateX(by: point.x, yBy: point.y) transformation.scale(by: 1.0 / annunciatorFontScale) NSGraphicsContext.saveGraphicsState() transformation.concat() let nsString = annunciatorStrings[idx] as NSString nsString.draw( at: NSMakePoint(0.0, 0.0), withAttributes: attrs ) NSGraphicsContext.restoreGraphicsState() } } self.unlockFocus() } } func bezierPaths() -> DisplaySegmentPaths { var paths: DisplaySegmentPaths = DisplaySegmentPaths() //1 /* Key: 0 Bounds: {{2.3755772113800049, 0}, {12.6975257396698, 2}} Control point bounds: {{2.3755772113800049, 0}, {12.6975257396698, 2}} 4.617837 2.000000 moveto 2.375577 0.000000 lineto 15.073103 0.000000 lineto 12.304828 2.000000 lineto 4.617837 2.000000 lineto closepath 4.617837 2.000000 moveto */ let bezierPath0 = NSBezierPath() bezierPath0.move(to: NSMakePoint(4.617837, 2.000000)) bezierPath0.line(to: NSMakePoint(2.375577, 0.000000)) bezierPath0.line(to: NSMakePoint(15.073103, 0.000000)) bezierPath0.line(to: NSMakePoint(12.304828, 2.000000)) bezierPath0.line(to: NSMakePoint(4.617837, 2.000000)) bezierPath0.close() bezierPath0.move(to: NSMakePoint(4.617837, 2.000000)) paths.append(bezierPath0) // 2 /* Bounds: {{1.0269801616668701, 0.71005439758300781}, {2.4166390895843506, 9.9931669235229492}} Control point bounds: {{1.0269801616668701, 0.71005439758300781}, {2.4166390895843506, 9.9931669235229492}} 1.026980 10.703221 moveto 1.935450 0.710054 lineto 3.443619 6.210914 lineto 3.136238 9.592111 lineto 1.026980 10.703221 lineto closepath 1.026980 10.703221 moveto */ let bezierPath1 = NSBezierPath() bezierPath1.move(to: NSMakePoint(1.026980, 10.703221)) bezierPath1.line(to: NSMakePoint(1.935450, 0.710054)) bezierPath1.line(to: NSMakePoint(3.443619, 6.210914)) bezierPath1.line(to: NSMakePoint(3.136238, 9.592111)) bezierPath1.line(to: NSMakePoint(1.026980, 10.703221)) bezierPath1.close() bezierPath1.move(to: NSMakePoint(1.026980, 10.703221)) paths.append(bezierPath1) // 3 /* Bounds: {{2.4647183418273926, 0.74950754642486572}, {4.684511661529541, 9.7398122549057007}} Control point bounds: {{2.4647183418273926, 0.74950754642486572}, {4.684511661529541, 9.7398122549057007}} 3.931293 6.098653 moveto 2.464718 0.749508 lineto 4.320368 2.404667 lineto 6.413752 6.591435 lineto 7.149230 10.489320 lineto 5.669303 9.574674 lineto 3.931293 6.098653 lineto closepath 3.931293 6.098653 moveto */ let bezierPath2 = NSBezierPath() bezierPath2.move(to: NSMakePoint(3.931293, 6.098653)) bezierPath2.line(to: NSMakePoint(2.464718, 0.749508)) bezierPath2.line(to: NSMakePoint(4.320368, 2.404667)) bezierPath2.line(to: NSMakePoint(6.413752, 6.591435)) bezierPath2.line(to: NSMakePoint(7.149230, 10.489320)) bezierPath2.line(to: NSMakePoint(5.669303, 9.574674)) bezierPath2.line(to: NSMakePoint(3.931293, 6.098653)) bezierPath2.close() bezierPath2.move(to: NSMakePoint(3.931293, 6.098653)) paths.append(bezierPath2) // 4 /* Bounds: {{6.9050822257995605, 2.25}, {2.3944964408874512, 7.8533802032470703}} Control point bounds: {{6.9050822257995605, 2.25}, {2.3944964408874512, 7.8533802032470703}} 6.905082 6.498730 moveto 7.291330 2.250000 lineto 9.299579 2.250000 lineto 8.884876 6.811726 lineto 7.585231 10.103380 lineto 6.905082 6.498730 lineto closepath 6.905082 6.498730 moveto */ let bezierPath3 = NSBezierPath() bezierPath3.move(to: NSMakePoint(6.905082, 6.498730)) bezierPath3.line(to: NSMakePoint(7.291330, 2.250000)) bezierPath3.line(to: NSMakePoint(9.299579, 2.250000)) bezierPath3.line(to: NSMakePoint(8.884876, 6.811726)) bezierPath3.line(to: NSMakePoint(7.585231, 10.103380)) bezierPath3.line(to: NSMakePoint(6.905082, 6.498730)) bezierPath3.close() bezierPath3.move(to: NSMakePoint(6.905082, 6.498730)) paths.append(bezierPath3) // 5 /* Bounds: {{7.9639315605163574, 0.75679004192352295}, {6.9154620170593262, 9.7489453554153442}} Control point bounds: {{7.9639315605163574, 0.75679004192352295}, {6.9154620170593262, 9.7489453554153442}} 9.352165 6.989707 moveto 12.565980 2.428165 lineto 14.879394 0.756790 lineto 12.461739 6.048622 lineto 9.993521 9.551898 lineto 7.963932 10.505735 lineto 9.352165 6.989707 lineto closepath 9.352165 6.989707 moveto */ let bezierPath4 = NSBezierPath() bezierPath4.move(to: NSMakePoint(9.352165, 6.989707)) bezierPath4.line(to: NSMakePoint(12.565980, 2.428165)) bezierPath4.line(to: NSMakePoint(14.879394, 0.756790)) bezierPath4.line(to: NSMakePoint(12.461739, 6.048622)) bezierPath4.line(to: NSMakePoint(9.993521, 9.551898)) bezierPath4.line(to: NSMakePoint(7.963932, 10.505735)) bezierPath4.line(to: NSMakePoint(9.352165, 6.989707)) bezierPath4.close() bezierPath4.move(to: NSMakePoint(9.352165, 6.989707)) paths.append(bezierPath4) // 6 /* Bounds: {{12.617741584777832, 0.75105857849121094}, {2.8139810562133789, 9.9741630554199219}} Control point bounds: {{12.617741584777832, 0.75105857849121094}, {2.8139810562133789, 9.9741630554199219}} 14.524980 10.725222 moveto 12.617742 9.614111 lineto 12.924595 6.238729 lineto 15.431723 0.751059 lineto 14.524980 10.725222 lineto closepath 14.524980 10.725222 moveto */ let bezierPath5 = NSBezierPath() bezierPath5.move(to: NSMakePoint(14.524980, 10.725222)) bezierPath5.line(to: NSMakePoint(12.617742, 9.614111)) bezierPath5.line(to: NSMakePoint(12.924595, 6.238729)) bezierPath5.line(to: NSMakePoint(15.431723, 0.751059)) bezierPath5.line(to: NSMakePoint(14.524980, 10.725222)) bezierPath5.close() bezierPath5.move(to: NSMakePoint(14.524980, 10.725222)) paths.append(bezierPath5) // 7 /* Bounds: {{1.5155218839645386, 10}, {5.4815198183059692, 2}} Control point bounds: {{1.5155218839645386, 10}, {5.4815198183059692, 2}} 3.213154 12.000000 moveto 1.515522 11.011001 lineto 3.434736 10.000000 lineto 5.406438 10.000000 lineto 6.997042 10.983047 lineto 5.072827 12.000000 lineto 3.213154 12.000000 lineto closepath 3.213154 12.000000 moveto */ let bezierPath6 = NSBezierPath() bezierPath6.move(to: NSMakePoint(3.213154, 12.000000)) bezierPath6.line(to: NSMakePoint(1.515522, 11.011001)) bezierPath6.line(to: NSMakePoint(3.434736, 10.000000)) bezierPath6.line(to: NSMakePoint(5.406438, 10.000000)) bezierPath6.line(to: NSMakePoint(6.997042, 10.983047)) bezierPath6.line(to: NSMakePoint(5.072827, 12.000000)) bezierPath6.line(to: NSMakePoint(3.213154, 12.000000)) bezierPath6.close() bezierPath6.move(to: NSMakePoint(3.213154, 12.000000)) paths.append(bezierPath6) // 8 /* Bounds: {{8.0330619812011719, 10}, {5.951416015625, 2}} Control point bounds: {{8.0330619812011719, 10}, {5.951416015625, 2}} 9.674292 12.000000 moveto 8.033062 11.025712 lineto 10.215584 10.000000 lineto 12.286846 10.000000 lineto 13.984478 10.988999 lineto 12.065263 12.000000 lineto 9.674292 12.000000 lineto closepath 9.674292 12.000000 moveto */ let bezierPath7 = NSBezierPath() bezierPath7.move(to: NSMakePoint(9.674292, 12.000000)) bezierPath7.line(to: NSMakePoint(8.033062, 11.025712)) bezierPath7.line(to: NSMakePoint(10.215584, 10.000000)) bezierPath7.line(to: NSMakePoint(12.286846, 10.000000)) bezierPath7.line(to: NSMakePoint(13.984478, 10.988999)) bezierPath7.line(to: NSMakePoint(12.065263, 12.000000)) bezierPath7.line(to: NSMakePoint(9.674292, 12.000000)) bezierPath7.close() bezierPath7.move(to: NSMakePoint(9.674292, 12.000000)) paths.append(bezierPath7) // 9 /* Bounds: {{0.070283412933349609, 11.274778366088867}, {2.8119742870330811, 9.9521026611328125}} Control point bounds: {{0.070283412933349609, 11.274778366088867}, {2.8119742870330811, 9.9521026611328125}} 0.070283 21.226881 moveto 0.975020 11.274778 lineto 2.882258 12.385889 lineto 2.594385 15.552494 lineto 0.070283 21.226881 lineto closepath 0.070283 21.226881 moveto */ let bezierPath8 = NSBezierPath() bezierPath8.move(to: NSMakePoint(0.070283, 21.226881)) bezierPath8.line(to: NSMakePoint(0.975020, 11.274778)) bezierPath8.line(to: NSMakePoint(2.882258, 12.385889)) bezierPath8.line(to: NSMakePoint(2.594385, 15.552494)) bezierPath8.line(to: NSMakePoint(0.070283, 21.226881)) bezierPath8.close() bezierPath8.move(to: NSMakePoint(0.070283, 21.226881)) paths.append(bezierPath8) // 10 /* Bounds: {{0.61331439018249512, 11.522175788879395}, {6.4336917400360107, 9.7141599655151367}} Control point bounds: {{0.61331439018249512, 11.522175788879395}, {6.4336917400360107, 9.7141599655151367}} 3.058874 15.738516 moveto 5.306457 12.442060 lineto 7.047006 11.522176 lineto 5.594459 15.569930 lineto 2.864343 19.574100 lineto 0.613314 21.236336 lineto 3.058874 15.738516 lineto closepath 3.058874 15.738516 moveto */ let bezierPath9 = NSBezierPath() bezierPath9.move(to: NSMakePoint(3.058874, 15.738516)) bezierPath9.line(to: NSMakePoint(5.306457, 12.442060)) bezierPath9.line(to: NSMakePoint(7.047006, 11.522176)) bezierPath9.line(to: NSMakePoint(5.594459, 15.569930)) bezierPath9.line(to: NSMakePoint(2.864343, 19.574100)) bezierPath9.line(to: NSMakePoint(0.613314, 21.236336)) bezierPath9.line(to: NSMakePoint(3.058874, 15.738516)) bezierPath9.close() bezierPath9.move(to: NSMakePoint(3.058874, 15.738516)) paths.append(bezierPath9) // 11 /* Bounds: {{5.7004213333129883, 11.920211791992188}, {2.4196805953979492, 7.8297882080078125}} Control point bounds: {{5.7004213333129883, 11.920211791992188}, {2.4196805953979492, 7.8297882080078125}} 6.065075 15.738811 moveto 7.435389 11.920212 lineto 8.120102 15.224238 lineto 7.708670 19.750000 lineto 5.700421 19.750000 lineto 6.065075 15.738811 lineto closepath 6.065075 15.738811 moveto */ let bezierPath10 = NSBezierPath() bezierPath10.move(to: NSMakePoint(6.065075, 15.738811)) bezierPath10.line(to: NSMakePoint(7.435389, 11.920212)) bezierPath10.line(to: NSMakePoint(8.120102, 15.224238)) bezierPath10.line(to: NSMakePoint(7.708670, 19.750000)) bezierPath10.line(to: NSMakePoint(5.700421, 19.750000)) bezierPath10.line(to: NSMakePoint(6.065075, 15.738811)) bezierPath10.close() bezierPath10.move(to: NSMakePoint(6.065075, 15.738811)) paths.append(bezierPath10) // 12 /* Bounds: {{7.8598289489746094, 11.504337310791016}, {5.1586418151855469, 9.75909423828125}} Control point bounds: {{7.8598289489746094, 11.504337310791016}, {5.1586418151855469, 9.75909423828125}} 8.609699 15.122776 moveto 7.859829 11.504337 lineto 9.419060 12.429949 lineto 11.534890 16.308971 lineto 13.018471 21.263432 lineto 11.046081 19.589474 lineto 8.609699 15.122776 lineto closepath 8.609699 15.122776 moveto */ let bezierPath11 = NSBezierPath() bezierPath11.move(to: NSMakePoint(8.609699, 15.122776)) bezierPath11.line(to: NSMakePoint(7.859829, 11.504337)) bezierPath11.line(to: NSMakePoint(9.419060, 12.429949)) bezierPath11.line(to: NSMakePoint(11.534890, 16.308971)) bezierPath11.line(to: NSMakePoint(13.018471, 21.263432)) bezierPath11.line(to: NSMakePoint(11.046081, 19.589474)) bezierPath11.line(to: NSMakePoint(8.609699, 15.122776)) bezierPath11.close() bezierPath11.move(to: NSMakePoint(8.609699, 15.122776)) paths.append(bezierPath11) // 13 /* Bounds: {{12.020228385925293, 11.296778678894043}, {2.4527921676635742, 10.034676551818848}} Control point bounds: {{12.020228385925293, 11.296778678894043}, {2.4527921676635742, 10.034676551818848}} 12.020228 16.186754 moveto 12.363762 12.407889 lineto 14.473021 11.296779 lineto 13.560777 21.331455 lineto 12.020228 16.186754 lineto closepath 12.020228 16.186754 moveto */ let bezierPath12 = NSBezierPath() bezierPath12.move(to: NSMakePoint(12.020228, 16.186754)) bezierPath12.line(to: NSMakePoint(12.363762, 12.407889)) bezierPath12.line(to: NSMakePoint(14.473021, 11.296779)) bezierPath12.line(to: NSMakePoint(13.560777, 21.331455)) bezierPath12.line(to: NSMakePoint(12.020228, 16.186754)) bezierPath12.close() bezierPath12.move(to: NSMakePoint(12.020228, 16.186754)) paths.append(bezierPath12) // 14 /* Bounds: {{0.42085522413253784, 20}, {12.692788422107697, 2}} Control point bounds: {{0.42085522413253784, 20}, {12.692788422107697, 2}} 0.420855 22.000000 moveto 3.129292 20.000000 lineto 10.757083 20.000000 lineto 13.113644 22.000000 lineto 0.420855 22.000000 lineto closepath 0.420855 22.000000 moveto */ let bezierPath13 = NSBezierPath() bezierPath13.move(to: NSMakePoint(0.420855, 22.000000)) bezierPath13.line(to: NSMakePoint(3.129292, 20.000000)) bezierPath13.line(to: NSMakePoint(10.757083, 20.000000)) bezierPath13.line(to: NSMakePoint(13.113644, 22.000000)) bezierPath13.line(to: NSMakePoint(0.420855, 22.000000)) bezierPath13.close() bezierPath13.move(to: NSMakePoint(0.420855, 22.000000)) paths.append(bezierPath13) // 15 /* Bounds: {{16.493814468383789, 9.4938144683837891}, {3.0123710632324219, 3.0123710632324219}} Control point bounds: {{16.493814468383789, 9.4938144683837891}, {3.0123710632324219, 3.0123710632324219}} 19.506186 11.000000 moveto 19.506186 11.000000 lineto 19.506186 11.831843 18.831842 12.506186 18.000000 12.506186 curveto 17.168158 12.506186 16.493814 11.831843 16.493814 11.000000 curveto 16.493814 11.000000 lineto 16.493814 11.000000 lineto 16.493814 10.168157 17.168158 9.493814 18.000000 9.493814 curveto 18.831842 9.493814 19.506186 10.168157 19.506186 11.000000 curveto 19.506186 11.000000 lineto closepath 19.506186 11.000000 moveto */ let bezierPath14 = NSBezierPath() bezierPath14.move(to: NSMakePoint(19.506186, 11.000000)) bezierPath14.line(to: NSMakePoint(19.506186, 11.000000)) bezierPath14.curve(to: NSMakePoint(19.506186, 11.831843), controlPoint1: NSMakePoint(18.831842, 12.506186), controlPoint2: NSMakePoint(18.000000, 12.506186)) bezierPath14.curve(to: NSMakePoint(17.168158, 12.506186), controlPoint1: NSMakePoint(16.493814, 11.831843), controlPoint2: NSMakePoint(16.493814, 11.000000)) bezierPath14.line(to: NSMakePoint(16.493814, 11.000000)) bezierPath14.line(to: NSMakePoint(16.493814, 11.000000)) bezierPath14.curve(to: NSMakePoint(16.493814, 10.168157), controlPoint1: NSMakePoint(17.168158, 9.493814), controlPoint2: NSMakePoint(18.000000, 9.493814)) bezierPath14.curve(to: NSMakePoint(18.831842, 9.493814), controlPoint1: NSMakePoint(19.506186, 10.1681573), controlPoint2: NSMakePoint(19.506186, 11.000000)) bezierPath14.line(to: NSMakePoint(19.506186, 11.000000)) bezierPath14.close() bezierPath14.move(to: NSMakePoint(19.506186, 11.000000)) paths.append(bezierPath14) // 16 /* Bounds: {{15.590910911560059, 19.5}, {2.9999990463256836, 3}} Control point bounds: {{15.590910911560059, 19.5}, {2.9999990463256836, 3}} 18.590910 21.000000 moveto 18.590910 21.000000 lineto 18.590910 21.828426 17.919336 22.500000 17.090910 22.500000 curveto 16.262484 22.500000 15.590911 21.828426 15.590911 21.000000 curveto 15.590911 21.000000 lineto 15.590911 21.000000 lineto 15.590911 20.171574 16.262484 19.500000 17.090910 19.500000 curveto 17.919336 19.500000 18.590910 20.171574 18.590910 21.000000 curveto 18.590910 21.000000 lineto closepath 18.590910 21.000000 moveto */ let bezierPath15 = NSBezierPath() bezierPath15.move(to: NSMakePoint(18.590910, 21.000000)) bezierPath15.line(to: NSMakePoint(18.590910, 21.000000)) bezierPath15.curve(to: NSMakePoint(18.590910, 21.828426), controlPoint1: NSMakePoint(17.919336, 22.500000), controlPoint2: NSMakePoint(17.090910, 22.500000)) bezierPath15.curve(to: NSMakePoint(16.262484, 22.500000), controlPoint1: NSMakePoint(15.590911, 21.828426), controlPoint2: NSMakePoint(15.590911, 21.000000)) bezierPath15.line(to: NSMakePoint(15.590911, 21.000000)) bezierPath15.line(to: NSMakePoint(15.590911, 21.000000)) bezierPath15.curve(to: NSMakePoint(15.590911, 20.1715747), controlPoint1: NSMakePoint(16.262484, 19.500000), controlPoint2: NSMakePoint(17.090910, 19.500000)) bezierPath15.curve(to: NSMakePoint(17.919336, 19.500000), controlPoint1: NSMakePoint(18.590910, 20.171574), controlPoint2: NSMakePoint(18.590910, 21.000000)) bezierPath15.line(to: NSMakePoint(18.590910, 21.000000)) bezierPath15.close() bezierPath15.move(to: NSMakePoint(18.590910, 21.000000)) paths.append(bezierPath15) // 17 /* Bounds: {{12.478299140930176, 21.263595581054688}, {5.9959535598754883, 4.8282829296589576}} Control point bounds: {{12.478299140930176, 21.263595581054688}, {5.9959535598754883, 5.2830562591552734}} 18.474253 22.083590 moveto 18.474253 22.083590 lineto 17.881054 24.806688 15.208557 26.546652 12.478299 25.987333 curveto 12.478300 25.987331 lineto 12.478301 25.987333 lineto 14.211855 25.127237 15.191052 23.245596 14.900759 21.332298 curveto 15.353578 21.263596 lineto 15.353578 21.263596 lineto 15.499158 22.223097 16.395004 22.882912 17.354506 22.737331 curveto 17.797445 22.670126 18.197989 22.436277 18.474253 22.083590 curveto 18.474253 22.083590 lineto closepath 18.474253 22.083590 moveto */ let bezierPath16 = NSBezierPath() bezierPath16.move(to: NSMakePoint(18.474253, 22.083590)) bezierPath16.line(to: NSMakePoint(18.474253, 22.083590)) bezierPath16.curve(to: NSMakePoint(17.881054, 24.806688), controlPoint1: NSMakePoint(15.208557, 26.546652), controlPoint2: NSMakePoint(12.478299, 25.987333)) bezierPath16.line(to: NSMakePoint(12.478300, 25.987331)) bezierPath16.line(to: NSMakePoint(12.478301, 25.987333)) bezierPath16.curve(to: NSMakePoint(14.211855, 25.12723), controlPoint1: NSMakePoint(15.191052, 23.245596), controlPoint2: NSMakePoint(17.354506, 22.737331)) bezierPath16.line(to: NSMakePoint(15.353578, 21.263596)) bezierPath16.line(to: NSMakePoint(15.353578, 21.263596)) bezierPath16.curve(to: NSMakePoint(15.499158, 22.223097), controlPoint1: NSMakePoint(16.395004, 22.882912), controlPoint2: NSMakePoint(17.354506, 22.737331)) bezierPath16.curve(to: NSMakePoint(17.797445, 22.670126), controlPoint1: NSMakePoint(18.197989, 22.436277), controlPoint2: NSMakePoint(18.474253, 22.083590)) bezierPath16.line(to: NSMakePoint(18.474253, 22.083590)) bezierPath16.close() bezierPath16.move(to: NSMakePoint(18.474253, 22.083590)) paths.append(bezierPath16) return paths } override func acceptsFirstMouse(for theEvent: NSEvent?) -> Bool { return true } //MARK: - Font support func loadSegmentPaths(file: String) -> DisplaySegmentPaths { var paths: DisplaySegmentPaths = DisplaySegmentPaths() let path = Bundle.main.path(forResource: file, ofType: "geom") var data: NSData? do { data = try NSData(contentsOfFile: path!, options: .mappedIfSafe) } catch _ { data = nil } let unarchiver = NSKeyedUnarchiver(forReadingWith: data! as Data) let dict = unarchiver.decodeObject(forKey: "bezierPaths") as! NSDictionary unarchiver.finishDecoding() for idx in 0..<numDisplaySegments { let key = String(idx) let path = dict[key]! as! NSBezierPath paths.append(path) } return paths } func calculateAnnunciatorPositions(font: NSFont, inRect bounds: NSRect) -> [NSPoint] { // Distribute the annunciators evenly across the width of the display based on the sizes of their strings. var positions: [NSPoint] = [NSPoint](repeating: NSMakePoint(0.0, 0.0), count: numAnnunciators) var annunciatorWidths: [CGFloat] = [CGFloat](repeating: 0.0, count: numAnnunciators) var spaceWidth: CGFloat = 0.0 var x: CGFloat = 0.0 var y: CGFloat = 0.0 var d: CGFloat = 0.0 var h: CGFloat = 0.0 var totalWidth: CGFloat = 0.0 let attrs = [ NSAttributedString.Key.font: annunciatorFont! ] for idx in 0..<numAnnunciators { let nsString: NSString = annunciatorStrings[idx] as NSString let width = nsString.size(withAttributes: attrs).width annunciatorWidths[idx] = width totalWidth += width } spaceWidth = (bounds.size.width - totalWidth) / CGFloat(numAnnunciators - 1) d -= font.descender h = NSLayoutManager().defaultLineHeight(for: font) y = bounds.size.height - annunciatorBottomMargin - (h - d) / annunciatorFontScale for idx in 0..<numAnnunciators { positions[idx] = NSMakePoint(x, y) x += annunciatorWidths[idx] + spaceWidth } return positions } }
27264c242cfb5988fcacba0a0933d5b8
35.550345
160
0.736858
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
refs/heads/master
weibo/weibo/Classes/Home/View/QRCode/CreateQRCodeViewController.swift
mit
1
// // CreateQRCodeViewController.swift // weibo // // Created by mada on 15/9/30. // Copyright © 2015年 MD. All rights reserved. // import UIKit class CreateQRCodeViewController: UIViewController { @IBOutlet weak var customImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() /* 生成二维码 */ // 1.创建滤镜 let filter = CIFilter(name: "CIQRCodeGenerator")! // 2.还原滤镜默认设置 filter.setDefaults() // 3.设置数据 filter.setValue("加斯加的猿".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage") // 4.从滤镜中取出二维码 let ciImage = filter.outputImage! let QRImage = createNonInterpolatedUIImageFormCIImage(ciImage, size: 500) let iconImage = UIImage(named: "nange.jpg")! // 5.合成二维码图片 let newImage = createImage(QRImage, iconImage: iconImage) // 6.设置图片到界面上 customImageView.image = newImage } private func createImage(backgroundImage: UIImage, iconImage: UIImage) -> UIImage { // 开启图形上下文 UIGraphicsBeginImageContext(backgroundImage.size) // 绘制图片 backgroundImage.drawInRect(CGRect(origin: CGPointZero, size: backgroundImage.size)) // 绘制图标 let width: CGFloat = 100.0 let height: CGFloat = 100.0 let x = (backgroundImage.size.width - width) * 0.5 let y = (backgroundImage.size.height - height) * 0.5 iconImage.drawInRect(CGRect(x: x, y: y, width: width, height: height)) // 取出图片 let image = UIGraphicsGetImageFromCurrentImageContext() return image } /** 根据CIImage生成指定大小的高清UIImage :param: image 指定CIImage :param: size 指定大小 :returns: 生成好的图片 */ private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = CGRectIntegral(image.extent) let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)) // 1.创建bitmap; let width = CGRectGetWidth(extent) * scale let height = CGRectGetHeight(extent) * scale let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()! let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)! let context = CIContext(options: nil) let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent) CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None) CGContextScaleCTM(bitmapRef, scale, scale); CGContextDrawImage(bitmapRef, extent, bitmapImage); // 2.保存bitmap到图片 let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)! return UIImage(CGImage: scaledImage) } }
02906e825c50efd99e4ecd286ae3ed50
34.382716
100
0.644103
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
IntegrationTests/Tests/IntegrationTests/StringChecker.swift
apache-2.0
2
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 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 Swift project authors */ import Foundation import TSCTestSupport import XCTest class StringChecker { private let string: String private let lines: [Substring] private var currentLineIndex: Int private var currentLine: Substring { lines[currentLineIndex] } init(string: String) { self.string = string self.lines = string.split(separator: "\n") self.currentLineIndex = 0 } func check(_ pattern: StringPattern, file: StaticString = #file, line: UInt = #line) { while let line = nextLine() { if pattern ~= line { return } } XCTFail(string, file: file, line: line) } func checkNext(_ pattern: StringPattern, file: StaticString = #file, line: UInt = #line) { if let line = nextLine(), pattern ~= line { return } XCTFail(string, file: file, line: line) } private func nextLine() -> String? { guard currentLineIndex < lines.count else { return nil } let currentLine = lines[currentLineIndex] currentLineIndex += 1 return String(currentLine) } } func XCTAssertContents( _ string: String, _ check: (StringChecker) -> Void ) { let checker = StringChecker(string: string) check(checker) }
945b641ff1bd29595176495006c8d1ba
25.225806
94
0.635301
false
false
false
false
Legoless/Saystack
refs/heads/master
Code/Extensions/UIKit/UIDevice+Utilities.swift
mit
1
// // UIDevice+Utilities.swift // Saystack // // Created by Dal Rupnik on 09/08/16. // Copyright © 2016 Unified Sense. All rights reserved. // import ObjectiveC import UIKit extension UIDevice { public var isSimulator : Bool { return TARGET_OS_SIMULATOR != 0 } public var modelIdentifier : String { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier } public var readableModel : String { let identifier = modelIdentifier switch identifier { case "iPod5,1": return "iPod Touch 5" case "iPod7,1": return "iPod Touch 6" case "iPod9,1": return "iPod Touch 7" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPhone12,1": return "iPhone 11" case "iPhone12,3": return "iPhone 11 Pro" case "iPhone12,5": return "iPhone 11 Pro Max" case "iPhone12,8": return "iPhone SE 2nd Gen" case "iPhone13,1": return "iPhone 12 Mini" case "iPhone13,2": return "iPhone 12" case "iPhone13,3": return "iPhone 12 Pro" case "iPhone13,4": return "iPhone 12 Pro Max" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad11,3", "iPad11,4": return "iPad Air 3" case "iPad13,1", "iPad13,2": return "iPad Air 4" case "iPad6,11", "iPad6,12": return "iPad 5" case "iPad7,5", "iPad7,6": return "iPad 6. Generation" case "iPad7,11", "iPad7,12": return "iPad 7. Generation 10.2-inch" case "iPad11,6", "iPad11,7": return "iPad 8. Generation" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3" case "iPad5,1", "iPad5,2": return "iPad Mini 4" case "iPad11,1", "iPad11,2": return "iPad Mini 5" case "iPad6,3", "iPad6,4": return "iPad Pro 9.7 Inch" case "iPad6,7", "iPad6,8": return "iPad Pro 12.9 Inch" case "iPad7,1", "iPad7,2": return "iPad Pro 12.9 Inch 2. Generation" case "iPad7,3", "iPad7,4": return "iPad Pro 10.5 Inch" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro 11 Inch 3. Generation" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro 12.9 Inch 3. Generation" case "Watch1,1", "Watch1,2": return "Apple Watch" case "Watch2,6", "Watch2,7": return "Apple Watch Series 1" case "Watch2,3", "Watch2,4": return "Apple Watch Series 2" case "Watch3,1", "Watch3,2", "Watch3,3", "Watch3,4": return "Apple Watch Series 3" case "Watch4,1", "Watch4,2", "Watch4,3", "Watch4,4": return "Apple Watch Series 4" case "Watch5,1", "Watch5,2", "Watch5,3", "Watch5,4": return "Apple Watch Series 5" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator" default: return identifier } } }
32f36f770f24014b201e4fd86def975f
56.641509
101
0.436498
false
false
false
false
pennlabs/penn-mobile-ios
refs/heads/main
PennMobile/General/SecureStore.swift
mit
1
// Copyright (c) 2018 Razeware LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, // distribute, sublicense, create a derivative work, and/or sell copies of the // Software in any work that is designed, intended, or marketed for pedagogical or // instructional purposes related to programming, coding, application development, // or information technology. Permission for such use, copying, modification, // merger, publication, distribution, sublicensing, creation of derivative works, // or sale is expressly withheld. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import Security public struct SecureStore { let secureStoreQueryable: SecureStoreQueryable public init(secureStoreQueryable: SecureStoreQueryable) { self.secureStoreQueryable = secureStoreQueryable } public func setValue(_ value: String, for userAccount: String) throws { guard let encodedPassword = value.data(using: .utf8) else { throw NetworkingError.other } var query = secureStoreQueryable.query query[String(kSecAttrAccount)] = userAccount var status = SecItemCopyMatching(query as CFDictionary, nil) switch status { case errSecSuccess: var attributesToUpdate: [String: Any] = [:] attributesToUpdate[String(kSecValueData)] = encodedPassword status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) if status != errSecSuccess { throw NetworkingError.other } case errSecItemNotFound: query[String(kSecValueData)] = encodedPassword status = SecItemAdd(query as CFDictionary, nil) if status != errSecSuccess { throw NetworkingError.other } default: throw NetworkingError.other } } public func getValue(for userAccount: String) throws -> String? { var query = secureStoreQueryable.query query[String(kSecMatchLimit)] = kSecMatchLimitOne query[String(kSecReturnAttributes)] = kCFBooleanTrue query[String(kSecReturnData)] = kCFBooleanTrue query[String(kSecAttrAccount)] = userAccount var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, $0) } switch status { case errSecSuccess: guard let queriedItem = queryResult as? [String: Any], let passwordData = queriedItem[String(kSecValueData)] as? Data, let password = String(data: passwordData, encoding: .utf8) else { throw NetworkingError.other } return password case errSecItemNotFound: return nil default: throw NetworkingError.other } } public func removeValue(for userAccount: String) throws { var query = secureStoreQueryable.query query[String(kSecAttrAccount)] = userAccount let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw NetworkingError.other } } public func removeAllValues() throws { let query = secureStoreQueryable.query let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw NetworkingError.other } } } public protocol SecureStoreQueryable { var query: [String: Any] { get } } public struct GenericPasswordQueryable { let service: String let accessGroup: String? init(service: String, accessGroup: String? = nil) { self.service = service self.accessGroup = accessGroup } } extension GenericPasswordQueryable: SecureStoreQueryable { public var query: [String: Any] { var query: [String: Any] = [:] query[String(kSecClass)] = kSecClassGenericPassword query[String(kSecAttrService)] = service // Access group if target environment is not simulator #if !targetEnvironment(simulator) if let accessGroup = accessGroup { query[String(kSecAttrAccessGroup)] = accessGroup } #endif return query } }
a16b2b777e877911bbc0b4de7db95f2e
36.554795
82
0.670254
false
false
false
false
material-motion/material-motion-swift
refs/heads/develop
Pods/MaterialMotion/src/reactivetypes/Reactive+UIButton.swift
apache-2.0
2
/* Copyright 2017-present The Material Motion Authors. 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 import UIKit /** A reactive button target exposes streams for certain button events. */ public final class ReactiveButtonTarget: NSObject { public init(_ button: UIButton) { super.init() button.addTarget(self, action: #selector(didEnterEvent), for: [.touchDown, .touchDragInside]) button.addTarget(self, action: #selector(didExitEvent), for: [.touchUpInside, .touchUpOutside, .touchDragOutside]) } // MARK: Streams /** Emits true when the button should be highlighted and false when it should not. */ public var didHighlight: MotionObservable<Bool> { return MotionObservable { observer in self.didHighlightObservers.append(observer) return { if let index = self.didHighlightObservers.index(where: { $0 === observer }) { self.didHighlightObservers.remove(at: index) } } } } func didEnterEvent(_ button: UIButton) { didHighlightObservers.forEach { $0.next(true) } } func didExitEvent(_ button: UIButton) { didHighlightObservers.forEach { $0.next(false) } } private var didHighlightObservers: [MotionObserver<Bool>] = [] }
3d5affcea1819609922eb966197300fe
31.125
85
0.707059
false
false
false
false
roytang121/Akaibu-NSUserDefaults
refs/heads/master
Akaibu/Sample/ViewController.swift
mit
1
// // ViewController.swift // Akaibu // // Created by Roy Tang on 4/10/2015. // Copyright © 2015 lerryrowy. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // let model = Child() // model.code = "aCode" // model.parentName = "aParent" let loaded = Akaibu.loadWithKey("model-1") as? Child print(loaded?.dictionaryWithValuesForKeys(["code", "parentName", "name"])) let ud = NSUserDefaults.standardUserDefaults() // let b = BModel() // b.saveWithKey("amodel") // b.bName = "bbbbb" // // ud.setObject(NSKeyedArchiver.archivedDataWithRootObject(b), forKey: "amodel") // // ud.synchronize() let a = (NSKeyedUnarchiver.unarchiveObjectWithData(ud.objectForKey("amodel") as! NSData) as! BModel) print(a) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d7b66ff8613d7a8fab4eb1d2f26f744c
21.282609
105
0.645854
false
false
false
false
vimeo/VimeoNetworking
refs/heads/develop
Sources/Shared/Models/VIMUploadQuota.swift
mit
1
// // VIMUploadQuota.swift // VimeoNetworking // // Created by Lim, Jennifer on 3/26/18. // // Copyright © 2016 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public class VIMUploadQuota: VIMModelObject { /// The values within `VIMSpace` reflect the lowest of lifetime or period for free and max. @objc dynamic public private(set) var space: VIMSpace? /// Represents the current quota period @objc dynamic public private(set) var periodic: VIMPeriodic? /// Represents the lifetime quota period @objc dynamic public private(set) var lifetime: VIMSizeQuota? public override func getClassForObjectKey(_ key: String!) -> AnyClass? { if key == "space" { return VIMSpace.self } else if key == "periodic" { return VIMPeriodic.self } else if key == "lifetime" { return VIMSizeQuota.self } return nil } /// Determines whether the user has a periodic storage quota limit or has a lifetime upload quota storage limit only. @objc public lazy var isPeriodicQuota: Bool = { return self.space?.type == "periodic" }() }
3e9a826411962540af57a8e39833f3d7
38.155172
121
0.694848
false
false
false
false
polischouckserg/tutu-test
refs/heads/master
RoutePicker/RoutePicker/Sources/CoreData/Dispatcher/CoreDataDispatcher.swift
apache-2.0
1
// // CoreDataDispatcher.swift // RoutePicker // // Created by Sergey Polischouck on 28/10/16. // Copyright © 2016 Sergey Polischouck. All rights reserved. // import CoreData class CoreDataDispatcher: NSObject { private static let dataBaseName = "Routes" private var managedObjectContext: NSManagedObjectContext //MARK: Shared Instance public static let sharedInstance : CoreDataDispatcher = { let instance = CoreDataDispatcher() return instance }() override init() { guard let modelURL = Bundle.main.url(forResource: CoreDataDispatcher.dataBaseName, withExtension:"momd") else { fatalError("Error loading model from bundle") } guard let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator let persistentStorageURL = CoreDataDispatcher.getURLToPersistentStorage() print("Persistent storage URL: \(persistentStorageURL)") do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName:nil, at: persistentStorageURL, options: nil) } catch { fatalError("Error migrating store: \(error)") } } // MARK: private functions private class func getURLToPersistentStorage() -> URL { let dataBaseURL = URLForStoringDataBase() if (FileManager.default.fileExists(atPath: dataBaseURL.path)) { print("Use existing data base") } else { print("Create new database") } return dataBaseURL } private class func URLForStoringDataBase() -> URL { let userDomainFolders = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let destinationDocumentFolderURL = userDomainFolders.first! return destinationDocumentFolderURL.appendingPathComponent(CoreDataDispatcher.dataBaseName + ".sqlite") } // MARK: public functions public class func isThereExistingDataBase() -> Bool { return FileManager.default.fileExists(atPath: URLForStoringDataBase().path) } public class func copyDataBaseFromBundleResources() { print("Copy data base") let sourcePath = Bundle.main.path(forResource: CoreDataDispatcher.dataBaseName, ofType: "sqlite") let destinationPath = URLForStoringDataBase().path print("From source path: \(sourcePath)") print("To destination path: \(destinationPath)") if FileManager.default.fileExists(atPath: sourcePath!) { do { let startDate = Date() try FileManager.default.copyItem(atPath: sourcePath!, toPath: destinationPath) print("Copying duration: \(NSDate().timeIntervalSince(startDate))") } catch { print(error.localizedDescription) } } } #if DATABASE_SEEDER public class func purgeExistingDataBase() { let dataBaseURL = URLForStoringDataBase() if (FileManager.default.fileExists(atPath: dataBaseURL.path)) { print("Purge existing data base") try! FileManager.default.removeItem(at: dataBaseURL) } } #endif // MARK: Data base management public func fetchedResultsController<T>(with fetchRequest: NSFetchRequest<T>, and sectionNameKeyPath: String) -> NSFetchedResultsController<T>? { return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) } public func createEntity(_ name: String) -> NSManagedObject { return NSEntityDescription.insertNewObject(forEntityName: name, into: managedObjectContext) } public func removeEntity(_ entity: NSManagedObject) { managedObjectContext.delete(entity) } public func save() throws { try managedObjectContext.save() } }
fc06bfe329c96b95b82546959f1faf94
31.904762
147
0.609469
false
false
false
false