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
rechsteiner/Parchment
refs/heads/main
Parchment/Classes/PagingMenuView.swift
mit
1
import UIKit open class PagingMenuView: UIView { // MARK: Public Properties /// The size for each of the menu items. _Default: /// .sizeToFit(minWidth: 150, height: 40)_ public var menuItemSize: PagingMenuItemSize { get { return options.menuItemSize } set { options.menuItemSize = newValue } } /// Determine the spacing between the menu items. _Default: 0_ public var menuItemSpacing: CGFloat { get { return options.menuItemSpacing } set { options.menuItemSpacing = newValue } } /// Determine the horizontal constraints of menu item label. _Default: 20_ public var menuItemLabelSpacing: CGFloat { get { return options.menuItemLabelSpacing } set { options.menuItemLabelSpacing = newValue } } /// Determine the insets at around all the menu items. _Default: /// UIEdgeInsets.zero_ public var menuInsets: UIEdgeInsets { get { return options.menuInsets } set { options.menuInsets = newValue } } /// Determine whether the menu items should be centered when all the /// items can fit within the bounds of the view. _Default: .left_ public var menuHorizontalAlignment: PagingMenuHorizontalAlignment { get { return options.menuHorizontalAlignment } set { options.menuHorizontalAlignment = newValue } } /// Determine the transition behaviour of menu items while scrolling /// the content. _Default: .scrollAlongside_ public var menuTransition: PagingMenuTransition { get { return options.menuTransition } set { options.menuTransition = newValue } } /// Determine how users can interact with the menu items. /// _Default: .scrolling_ public var menuInteraction: PagingMenuInteraction { get { return options.menuInteraction } set { options.menuInteraction = newValue } } /// The class type for collection view layout. Override this if you /// want to use your own subclass of the layout. Setting this /// property will initialize the new layout type and update the /// collection view. /// _Default: PagingCollectionViewLayout.self_ public var menuLayoutClass: PagingCollectionViewLayout.Type { get { return options.menuLayoutClass } set { options.menuLayoutClass = newValue } } /// Determine how the selected menu item should be aligned when it /// is selected. Effectivly the same as the /// `UICollectionViewScrollPosition`. _Default: .preferCentered_ public var selectedScrollPosition: PagingSelectedScrollPosition { get { return options.selectedScrollPosition } set { options.selectedScrollPosition = newValue } } /// Add an indicator view to the selected menu item. The indicator /// width will be equal to the selected menu items width. Insets /// only apply horizontally. _Default: .visible_ public var indicatorOptions: PagingIndicatorOptions { get { return options.indicatorOptions } set { options.indicatorOptions = newValue } } /// The class type for the indicator view. Override this if you want /// your use your own subclass of PagingIndicatorView. _Default: /// PagingIndicatorView.self_ public var indicatorClass: PagingIndicatorView.Type { get { return options.indicatorClass } set { options.indicatorClass = newValue } } /// Determine the color of the indicator view. public var indicatorColor: UIColor { get { return options.indicatorColor } set { options.indicatorColor = newValue } } /// Add a border at the bottom of the menu items. The border will be /// as wide as all the menu items. Insets only apply horizontally. /// _Default: .visible_ public var borderOptions: PagingBorderOptions { get { return options.borderOptions } set { options.borderOptions = newValue } } /// The class type for the border view. Override this if you want /// your use your own subclass of PagingBorderView. _Default: /// PagingBorderView.self_ public var borderClass: PagingBorderView.Type { get { return options.borderClass } set { options.borderClass = newValue } } /// Determine the color of the border view. public var borderColor: UIColor { get { return options.borderColor } set { options.borderColor = newValue } } /// Updates the content inset for the menu items based on the /// .safeAreaInsets property. _Default: true_ public var includeSafeAreaInsets: Bool { get { return options.includeSafeAreaInsets } set { options.includeSafeAreaInsets = newValue } } /// The font used for title label on the menu items. public var font: UIFont { get { return options.font } set { options.font = newValue } } /// The font used for the currently selected menu item. public var selectedFont: UIFont { get { return options.selectedFont } set { options.selectedFont = newValue } } /// The color of the title label on the menu items. public var textColor: UIColor { get { return options.textColor } set { options.textColor = newValue } } /// The text color for the currently selected menu item. public var selectedTextColor: UIColor { get { return options.selectedTextColor } set { options.selectedTextColor = newValue } } /// The background color for the menu items. open override var backgroundColor: UIColor? { didSet { if let backgroundColor = backgroundColor { options.backgroundColor = backgroundColor } } } /// The background color for the selected menu item. public var selectedBackgroundColor: UIColor { get { return options.selectedBackgroundColor } set { options.selectedBackgroundColor = newValue } } /// The background color for the view behind the menu items. public var menuBackgroundColor: UIColor { get { return options.menuBackgroundColor } set { options.menuBackgroundColor = newValue } } public weak var delegate: PagingMenuDelegate? { didSet { pagingController.delegate = delegate } } public weak var dataSource: PagingMenuDataSource? { didSet { pagingController.dataSource = dataSource } } /// The current state of the menu items. Indicates whether an item /// is currently selected or is scrolling to another item. Can be /// used to get the distance and progress of any ongoing transition. public var state: PagingState { return pagingController.state } /// The `PagingItem`'s that are currently visible in the collection /// view. The items in this array are not necessarily the same as /// the `visibleCells` property on `UICollectionView`. public var visibleItems: PagingItems { return pagingController.visibleItems } /// A custom collection view layout that lays out all the menu items /// horizontally. You can customize the behavior of the layout by /// setting the customization properties on `PagingViewController`. /// You can also use your own subclass of the layout by defining the /// `menuLayoutClass` property. public private(set) lazy var collectionViewLayout: PagingCollectionViewLayout = { createLayout(layout: options.menuLayoutClass.self) }() /// Used to display the menu items that scrolls along with the /// content. Using a collection view means you can create custom /// cells that display pretty much anything. By default, scrolling /// is enabled in the collection view. public lazy var collectionView: UICollectionView = { UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) }() /// An instance that stores all the customization so that it's /// easier to share between other classes. public private(set) var options = PagingOptions() { didSet { if options.menuLayoutClass != oldValue.menuLayoutClass { let layout = createLayout(layout: options.menuLayoutClass.self) collectionViewLayout = layout collectionViewLayout.options = options collectionView.setCollectionViewLayout(layout, animated: false) } else { collectionViewLayout.options = options } pagingController.options = options } } // MARK: Private Properties private lazy var pagingController = PagingController(options: options) // MARK: Initializers /// Creates an instance of `PagingViewController`. You need to call /// `select(pagingItem:animated:)` in order to set the initial view /// controller before any items become visible. public override init(frame: CGRect) { super.init(frame: frame) configure() } public required init?(coder: NSCoder) { super.init(coder: coder) configure() } // TODO: Figure out how we can remove this method. open func viewAppeared() { pagingController.viewAppeared() } open func transitionSize() { pagingController.transitionSize() } open func contentScrolled(progress: CGFloat) { pagingController.contentScrolled(progress: progress) } open func contentFinishedScrolling() { pagingController.contentFinishedScrolling() } /// Reload data around given paging item. This will set the given /// paging item as selected and generate new items around it. /// /// - Parameter pagingItem: The `PagingItem` that will be selected /// after the data reloads. open func reload(around pagingItem: PagingItem) { pagingController.reloadMenu(around: pagingItem) } /// Selects a given paging item. This need to be called after you /// initilize the `PagingViewController` to set the initial /// `PagingItem`. This can be called both before and after the view /// has been loaded. You can also use this to programmatically /// navigate to another `PagingItem`. /// /// - Parameter pagingItem: The `PagingItem` to be displayed. /// - Parameter animated: A boolean value that indicates whether /// the transtion should be animated. Default is false. open func select(pagingItem: PagingItem, animated: Bool = false) { pagingController.select(pagingItem: pagingItem, animated: animated) } // MARK: Private Methods private func configure() { collectionView.backgroundColor = options.menuBackgroundColor collectionView.delegate = self addSubview(collectionView) constrainToEdges(collectionView) pagingController.collectionView = collectionView pagingController.collectionViewLayout = collectionViewLayout } } extension PagingMenuView: UICollectionViewDelegate { public func scrollViewDidScroll(_: UIScrollView) { pagingController.menuScrolled() } public func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) { pagingController.select(indexPath: indexPath, animated: true) } }
92e3cc1a02ebb9634d068b6be0da3cf5
36.003268
91
0.675174
false
false
false
false
miracl/amcl
refs/heads/master
version3/swift/rom_nums384w.swift
apache-2.0
1
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // rom.swift // // Created by Michael Scott on 12/06/2015. // Copyright (c) 2015 Michael Scott. All rights reserved. // public struct ROM{ #if D32 // Base Bits= 29 // nums384 Modulus static public let Modulus:[Chunk] = [0x1FFFFEC3,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7F] static let R2modp:[Chunk] = [0x0,0x4448000,0x6,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let MConst:Chunk = 0x13D // nums384 Weierstrass Curve static let CURVE_Cof_I:Int = 1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = -34568 static let CURVE_B:[Chunk] = [0x1FFF77BB,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7F] static public let CURVE_Order:[Chunk] = [0x1B0E61B9,0x26C0FB3,0xDF89E98,0x153A7A98,0x16881BED,0x178F75AE,0x1FFF587A,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7F] static public let CURVE_Gx:[Chunk] = [0x98152A,0x1CE5D021,0x18711EFA,0x1DDA201E,0xC742522,0x148D9536,0x7D3CEF4,0x19BF703F,0x60225C1,0x12082F8D,0x12203288,0x2DE3038,0x17956F0B,0x3A] static public let CURVE_Gy:[Chunk] = [0x6180716,0x3A5C763,0x1D2B4997,0xD69B77F,0x837EBCD,0x1BE890D,0xE72E482,0xEFF0FEE,0x1EB00469,0x2C267B,0x15F8CF4C,0x3371C71,0xDEE368E,0x56] #endif #if D64 // Base Bits= 58 // nums384 Modulus static public let Modulus:[Chunk] = [0x3FFFFFFFFFFFEC3,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0xFFFFFFFFF] static let R2modp:[Chunk] = [0x88900000000000,0x6,0x0,0x0,0x0,0x0,0x0] static let MConst:Chunk = 0x13D // nums384 Weierstrass Curve static let CURVE_Cof_I:Int = 1 static let CURVE_Cof:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0] static let CURVE_A:Int = -3 static let CURVE_B_I:Int = -34568 static let CURVE_B:[Chunk] = [0x3FFFFFFFFFF77BB,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0xFFFFFFFFF] static public let CURVE_Order:[Chunk] = [0x4D81F67B0E61B9,0x2A74F530DF89E98,0x2F1EEB5D6881BED,0x3FFFFFFFFFF587A,0x3FFFFFFFFFFFFFF,0x3FFFFFFFFFFFFFF,0xFFFFFFFFF] static public let CURVE_Gx:[Chunk] = [0x39CBA042098152A,0x3BB4403D8711EFA,0x291B2A6CC742522,0x337EE07E7D3CEF4,0x24105F1A60225C1,0x5BC60712203288,0x757956F0B] static public let CURVE_Gy:[Chunk] = [0x74B8EC66180716,0x1AD36EFFD2B4997,0x37D121A837EBCD,0x1DFE1FDCE72E482,0x584CF7EB00469,0x66E38E35F8CF4C,0xACDEE368E] #endif }
02d3463f395ccedff97c8200e3140578
44.972603
187
0.803933
false
false
false
false
biohazardlover/WeiWeiStudio
refs/heads/master
WeiWeiStudio/ClassesViewController.swift
mit
1
import UIKit import CoreData class ClassesViewController: UITableViewController { private var fetchedResultsControllerDelegate: FetchedResultsControllerDelegate? private var tableViewDataSource: TableViewDataSource? var _fetchedResultsController: NSFetchedResultsController<Class>? = nil var fetchedResultsController: NSFetchedResultsController<Class> { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest: NSFetchRequest<Class> = Class.fetchRequest() fetchRequest.fetchBatchSize = 20 let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] _fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: AppDelegate.shared.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: "Classes") try? _fetchedResultsController!.performFetch() return _fetchedResultsController! } override func viewDidLoad() { super.viewDidLoad() let configure: ((UITableViewCell, Any?) -> Void) = { (cell, object) in let aClass = object as? Class cell.textLabel?.text = aClass?.name } fetchedResultsControllerDelegate = FetchedResultsControllerDelegate(tableView: tableView, configure: configure) fetchedResultsController.delegate = fetchedResultsControllerDelegate tableViewDataSource = TableViewDataSource(sections: fetchedResultsController.sections, cellIdentifier: "ClassCell", configure: configure) tableView.dataSource = tableViewDataSource } @IBAction func classViewControllerUnwound(_ segue: UIStoryboardSegue) { } }
2f04ab72ca3075a73d3e16cbc0027ea1
37.833333
211
0.70118
false
true
false
false
Moya/Moya
refs/heads/master
Tests/MoyaTests/MoyaProvider+ReactiveSpec.swift
mit
1
import Quick import Nimble import ReactiveSwift import OHHTTPStubs #if canImport(OHHTTPStubsSwift) import OHHTTPStubsSwift #endif @testable import Moya @testable import ReactiveMoya final class MoyaProviderReactiveSpec: QuickSpec { override func spec() { describe("failing") { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.immediatelyStub) } it("returns the correct error message") { var receivedError: MoyaError? waitUntil { done in provider.reactive.request(.zen).startWithFailed { error in receivedError = error done() } } switch receivedError { case .some(.underlying(let error, _)): expect(error.localizedDescription) == "Houston, we have a problem" default: fail("expected an Underlying error that Houston has a problem") } } it("returns an error") { var errored = false let target: GitHub = .zen provider.reactive.request(target).startWithFailed { _ in errored = true } expect(errored).to(beTruthy()) } } describe("provider with SignalProducer") { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub) } it("returns a Response object") { var called = false provider.reactive.request(.zen).startWithResult { _ in called = true } expect(called).to(beTruthy()) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .zen provider.reactive.request(target).startWithResult { result in if case .success(let response) = result { message = String(data: response.data, encoding: .utf8) } } let sampleString = String(data: target.sampleData, encoding: .utf8) expect(message!).to(equal(sampleString)) } it("returns correct data for user profile request") { var receivedResponse: NSDictionary? let target: GitHub = .userProfile("ashfurrow") provider.reactive.request(target).startWithResult { result in if case .success(let response) = result { receivedResponse = try! JSONSerialization.jsonObject(with: response.data, options: []) as? NSDictionary } } let sampleData = target.sampleData let sampleResponse = try! JSONSerialization.jsonObject(with: sampleData, options: []) as! NSDictionary expect(receivedResponse).toNot(beNil()) expect(receivedResponse) == sampleResponse } } describe("provider with inflight tracking") { var provider: MoyaProvider<GitHub>! beforeEach { HTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in return HTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil) }) provider = MoyaProvider<GitHub>(trackInflights: true) } it("returns identical signalproducers for inflight requests") { let target: GitHub = .zen let signalProducer1: SignalProducer<Moya.Response, MoyaError> = provider.reactive.request(target) let signalProducer2: SignalProducer<Moya.Response, MoyaError> = provider.reactive.request(target) expect(provider.inflightRequests.keys.count).to( equal(0) ) var receivedResponse: Moya.Response! signalProducer1.startWithResult { result in if case .success(let response) = result { receivedResponse = response expect(provider.inflightRequests.count).to( equal(1) ) } } signalProducer2.startWithResult { result in if case .success(let response) = result { expect(receivedResponse).toNot( beNil() ) expect(receivedResponse).to( beIdenticalToResponse(response) ) expect(provider.inflightRequests.count).to( equal(1) ) } } // Allow for network request to complete expect(provider.inflightRequests.count).toEventually( equal(0) ) } } describe("a provider with progress tracking") { var provider: MoyaProvider<GitHubUserContent>! beforeEach { //delete downloaded filed before each test let directoryURLs = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) let file = directoryURLs.first!.appendingPathComponent("logo_github.png") try? FileManager.default.removeItem(at: file) //`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes. HTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in return HTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4) }) provider = MoyaProvider<GitHubUserContent>() } it("tracks progress of request") { let target: GitHubUserContent = .downloadMoyaWebContent("logo_github.png") let expectedNextProgressValues = [0.25, 0.5, 0.75, 1.0, 1.0] let expectedNextResponseCount = 1 let expectedFailedEventsCount = 0 let expectedInterruptedEventsCount = 0 let expectedCompletedEventsCount = 1 let timeout = DispatchTimeInterval.seconds(5) var nextProgressValues: [Double] = [] var nextResponseCount = 0 var failedEventsCount = 0 var interruptedEventsCount = 0 var completedEventsCount = 0 _ = provider.reactive.requestWithProgress(target) .start({ event in switch event { case let .value(element): nextProgressValues.append(element.progress) if element.response != nil { nextResponseCount += 1 } case .failed: failedEventsCount += 1 case .completed: completedEventsCount += 1 case .interrupted: interruptedEventsCount += 1 } }) expect(completedEventsCount).toEventually(equal(expectedCompletedEventsCount), timeout: timeout) expect(failedEventsCount).toEventually(equal(expectedFailedEventsCount), timeout: timeout) expect(interruptedEventsCount).toEventually(equal(expectedInterruptedEventsCount), timeout: timeout) expect(nextResponseCount).toEventually(equal(expectedNextResponseCount), timeout: timeout) expect(nextProgressValues).toEventually(equal(expectedNextProgressValues), timeout: timeout) } } } }
91c52fbcd83fe40494ce3f0183642d19
40.421875
170
0.556268
false
false
false
false
dorentus/bna-swift
refs/heads/master
bna/AuthenticatorCell.swift
mit
1
// // AuthenticatorCell.swift // bna // // Created by Rox Dorentus on 2014-6-23. // Copyright (c) 2014年 rubyist.today. All rights reserved. // import UIKit import QuartzCore import Padlock @IBDesignable class AuthenticatorCell: UITableViewCell { class SelectionBackgroundView: UIView { } @IBOutlet weak var token_label: UILabel! @IBOutlet weak var serial_label: UILabel! var timer: CADisplayLink? var authenticator: Authenticator? { didSet { serial_label.text = authenticator?.serial.description update_token() } } override func awakeFromNib() { super.awakeFromNib() self.selectedBackgroundView = SelectionBackgroundView() } func update_token() { if let a = authenticator { let (token, progress) = a.token() token_label.text = token token_label.textColor = color(progress: progress) } } func start_timer() { timer = CADisplayLink(target: self, selector: Selector("update_token")) timer!.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes) } func stop_timer() { if let t = timer { t.invalidate() } timer = nil } }
46ba164eb7475a84701f8f10b80aa70f
22.388889
86
0.619161
false
false
false
false
JustinM1/Flock
refs/heads/master
Sources/SupervisordTasks.swift
mit
1
// // SystemdTasks.swift // Flock // // Created by Jake Heiser on 11/3/16. // // public protocol SupervisordProvider { /// The namespace that the tasks of this provider will be placed under; e.g. if namespace is "svr", tasks will be "svr:start" and the like var taskNamespace: String { get } /// The supervisorctl configuration for this project /// Defaults to spawning a single instance of your executable with no arguments /// /// - Parameter server: the server on which the configuration file will be placed /// - Returns: an instance of SupervisordConfFile representing this project's config file func confFile(for server: Server) -> SupervisordConfFile } public extension SupervisordProvider { // Defaults func confFile(for server: Server) -> SupervisordConfFile { return SupervisordConfFile(programName: supervisordName) } // Add-ons var supervisordName: String { return Config.supervisordName ?? Config.projectName } var confFilePath: String { return "/etc/supervisor/conf.d/\(supervisordName).conf" } public func createTasks() -> [Task] { return [ DependenciesTask(provider: self), WriteConfTask(provider: self), StartTask(provider: self), StopTask(provider: self), RestartTask(provider: self), StatusTask(provider: self) ] } } // MARK: - SupervisordConfFile public struct SupervisordConfFile { public var programName: String public var command = Paths.executable public var processName = "%(process_num)s" public var autoStart = true public var autoRestart = "unexpected" public var stdoutLogfile = Config.outputLog public var stderrLogfile = Config.errorLog private var extraLines: [String] = [] public init(programName: String) { self.programName = programName } public mutating func add(_ line: String) { extraLines.append(line) } func toString() -> String { let config = [ "[program:\(programName)]", "command=\(command)", "process_name=\(processName)", "autostart=\(autoStart)", "autorestart=\(autoRestart)", "stdout_logfile=\(stdoutLogfile)", "stderr_logfile=\(stderrLogfile)" ] + extraLines + [""] return config.joined(separator: "\n") } } public class SupervisordTask: Task { public var name: String { return "" } public var hookTimes: [HookTime] { return [] } public let namespace: String let provider: SupervisordProvider init(provider: SupervisordProvider) { self.namespace = provider.taskNamespace self.provider = provider } public func run(on server: Server) throws { throw TaskError.commandFailed } func executeSupervisorctl(command: String, on server: Server) throws { let persmissionsMatcher = OutputMatcher(regex: "Permission denied:") { (match) in print("Make sure this user has the ability to run supervisorctl commands -- see https://github.com/jakeheis/Flock#permissions".yellow) } try server.executeWithOutputMatchers("supervisorctl \(command)", matchers: [persmissionsMatcher]) } } class DependenciesTask: SupervisordTask { override var name: String { return "dependencies" } override var hookTimes: [HookTime] { return [.after("tools:dependencies")] } override func run(on server: Server) throws { try server.execute("sudo apt-get -qq install supervisor") if let supervisordUser = Config.supervisordUser { let chownLine = "chown=\(supervisordUser)" do { try server.execute("sudo grep \"\(chownLine)\" < /etc/supervisor/supervisord.conf") } catch { // grep fails when it has no matches - no matches means line is not in file, so add it try server.execute("sudo sed -i '/\\[unix_http_server\\]/a\(chownLine)' /etc/supervisor/supervisord.conf") } try server.execute("sudo touch \(provider.confFilePath)") let nonexistentMatcher = OutputMatcher(regex: "invalid user:") { (match) in print("\(supervisordUser) (Config.supervisordUser) must already exist on the server before running `flock tools`".yellow) } try server.executeWithOutputMatchers("sudo chown \(supervisordUser) \(provider.confFilePath)", matchers: [nonexistentMatcher]) } try server.execute("sudo service supervisor restart") } } class WriteConfTask: SupervisordTask { override var name: String { return "write-conf" } override func run(on server: Server) throws { // Supervisor requires the directories containing the logs to already be created let outputParent = parentDirectory(of: Config.outputLog) let errorParent = parentDirectory(of: Config.outputLog) if let op = outputParent { try server.execute("mkdir -p \(op)") } if let ep = errorParent, errorParent != outputParent { try server.execute("mkdir -p \(ep)") } let persmissionsMatcher = OutputMatcher(regex: "Permission denied") { (match) in print("Make sure this user has write access to \(self.provider.confFilePath) -- see https://github.com/jakeheis/Flock#permissions".yellow) } try server.executeWithOutputMatchers("echo \"\(provider.confFile(for: server).toString())\" > \(provider.confFilePath)", matchers: [persmissionsMatcher]) try executeSupervisorctl(command: "reread", on: server) try executeSupervisorctl(command: "update", on: server) } private func parentDirectory(of path: String) -> String? { if let lastPathComponentIndex = path.range(of: "/", options: .backwards, range: nil, locale: nil) { return path.substring(to: lastPathComponentIndex.lowerBound) } return nil } } class StartTask: SupervisordTask { override var name: String { return "start" } override func run(on server: Server) throws { try invoke("\(namespace):write-conf") try executeSupervisorctl(command: "start \(provider.supervisordName):*", on: server) } } class StopTask: SupervisordTask { override var name: String { return "stop" } override func run(on server: Server) throws { try executeSupervisorctl(command: "stop \(provider.supervisordName):*", on: server) } } class RestartTask: SupervisordTask { override var name: String { return "restart" } override var hookTimes: [HookTime] { return [.after("deploy:link")] } override func run(on server: Server) throws { try invoke("\(namespace):write-conf") try executeSupervisorctl(command: "restart \(provider.supervisordName):*", on: server) } } class StatusTask: SupervisordTask { override var name: String { return "status" } override func run(on server: Server) throws { try executeSupervisorctl(command: "status \(provider.supervisordName):*", on: server) } }
0e986950d930d7ab43581e3ccf390315
30.52521
161
0.621885
false
true
false
false
mercadopago/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/Fingerprint.swift
mit
1
// // Fingerprint.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class Fingerprint : NSObject { public var fingerprint : [String : AnyObject]? public override init () { super.init() self.fingerprint = deviceFingerprint() } public func toJSONString() -> String { return JSON(self.fingerprint!).toString() } public func deviceFingerprint() -> [String : AnyObject] { let device : UIDevice = UIDevice.currentDevice() var dictionary : [String : AnyObject] = [String : AnyObject]() dictionary["os"] = "iOS" let devicesId : [AnyObject]? = devicesID() if devicesId != nil { dictionary["vendor_ids"] = devicesId! } if !String.isNullOrEmpty(device.hwmodel) { dictionary["model"] = device.hwmodel } dictionary["os"] = "iOS" if !String.isNullOrEmpty(device.systemVersion) { dictionary["system_version"] = device.systemVersion } let screenSize: CGRect = UIScreen.mainScreen().bounds let width = NSString(format: "%.0f", screenSize.width) let height = NSString(format: "%.0f", screenSize.height) dictionary["resolution"] = "\(width)x\(height)" dictionary["ram"] = device.totalMemory dictionary["disk_space"] = device.totalDiskSpace dictionary["free_disk_space"] = device.freeDiskSpace var moreData = [String : AnyObject]() moreData["feature_camera"] = device.cameraAvailable moreData["feature_flash"] = device.cameraFlashAvailable moreData["feature_front_camera"] = device.frontCameraAvailable moreData["video_camera_available"] = device.videoCameraAvailable moreData["cpu_count"] = device.cpuCount moreData["retina_display_capable"] = device.retinaDisplayCapable if device.userInterfaceIdiom == UIUserInterfaceIdiom.Pad { moreData["device_idiom"] = "Pad" } else { moreData["device_idiom"] = "Phone" } if device.canSendSMS { moreData["can_send_sms"] = 1 } else { moreData["can_send_sms"] = 0 } if device.canMakePhoneCalls { moreData["can_make_phone_calls"] = 1 } else { moreData["can_make_phone_calls"] = 0 } if NSLocale.preferredLanguages().count > 0 { moreData["device_languaje"] = NSLocale.preferredLanguages()[0] } if !String.isNullOrEmpty(device.model) { moreData["device_model"] = device.model } if !String.isNullOrEmpty(device.platform) { moreData["platform"] = device.platform } moreData["device_family"] = device.deviceFamily.rawValue if !String.isNullOrEmpty(device.name) { moreData["device_name"] = device.name } /*var simulator : Bool = false #if TARGET_IPHONE_SIMULATOR simulator = YES #endif if simulator { moreData["simulator"] = 1 } else { moreData["simulator"] = 0 }*/ moreData["simulator"] = 0 dictionary["vendor_specific_attributes"] = moreData return dictionary } public func devicesID() -> [AnyObject]? { let systemVersionString : String = UIDevice.currentDevice().systemVersion let systemVersion : Float = (systemVersionString.componentsSeparatedByString(".")[0] as NSString).floatValue if systemVersion < 6 { let uuid : String = NSUUID().UUIDString if !String.isNullOrEmpty(uuid) { var dic : [String : AnyObject] = ["name" : "uuid"] dic["value"] = uuid return [dic] } } else { let vendorId : String = UIDevice.currentDevice().identifierForVendor!.UUIDString let uuid : String = NSUUID().UUIDString var dicVendor : [String : AnyObject] = ["name" : "vendor_id"] dicVendor["value"] = vendorId var dic : [String : AnyObject] = ["name" : "uuid"] dic["value"] = uuid return [dicVendor, dic] } return nil } }
1fddec36290ec59dd9501a42db198c68
30.685315
116
0.557616
false
false
false
false
kukat/CircleTransition
refs/heads/master
CircleTransition/CircleTransitionPopAnimator.swift
mit
1
// // CircleTransitionPopAnimator.swift // CircleTransition // // Created by Cheng Yao on 10/4/15. // Copyright (c) 2015 Rounak Jain. All rights reserved. // import UIKit class CircleTransitionPopAnimator: NSObject, UIViewControllerAnimatedTransitioning { weak var transitionContext: UIViewControllerContextTransitioning? func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var containerView = transitionContext.containerView() var fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! ViewController var toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController var button = fromViewController.button containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view) var extremePoint = CGPoint(x: button.center.x - 0, y: button.center.y - CGRectGetHeight(toViewController.view.bounds)) var radius = sqrt((extremePoint.x*extremePoint.x) + (extremePoint.y*extremePoint.y)) var circleMaskPathFinal = UIBezierPath(ovalInRect: button.frame) var circleMaskPathInitial = UIBezierPath(ovalInRect: CGRectInset(button.frame, -radius, -radius)) var maskLayer = CAShapeLayer() maskLayer.path = circleMaskPathFinal.CGPath fromViewController.view.layer.mask = maskLayer var maskLayerAnimation = CABasicAnimation(keyPath: "path") maskLayerAnimation.fromValue = circleMaskPathInitial.CGPath maskLayerAnimation.toValue = circleMaskPathFinal.CGPath maskLayerAnimation.duration = self.transitionDuration(transitionContext) maskLayerAnimation.delegate = self maskLayer.addAnimation(maskLayerAnimation, forKey: "path") } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { self.transitionContext?.completeTransition(!self.transitionContext!.transitionWasCancelled()) self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey)?.view.layer.mask = nil } }
f4ef5180279ce3f6421bc8c95ec413be
44.961538
132
0.745188
false
false
false
false
imclean/JLDishWashers
refs/heads/master
JLDishwasher/ProductDetail.swift
gpl-3.0
1
// // ProductDetail.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class ProductDetail { public var crumbs : Array<Crumbs>? public var media : Media? public var productId : String? public var defaultCategory : DefaultCategory? public var ageRestriction : Int? public var type : String? public var displaySpecialOffer : String? public var seoURL : String? public var setId : String? public var code : Int? public var title : String? public var skus : Array<Skus>? public var isFBL : String? public var setInformation : String? public var storeOnly : String? public var additionalServices : AdditionalServices? public var deliverySummary : Array<DeliverySummary>? public var details : Details? public var promotionalFeatures : Array<PromotionalFeatures>? public var price : Price? public var defaultSku : Int? public var isInTopNkuCategory : String? public var specialOffers : SpecialOffers? public var deliveries : Array<Deliveries>? public var templateType : String? public var seoInformation : SeoInformation? public var releaseDateTimestamp : Int? public var emailMeWhenAvailable : String? /** Returns an array of models based on given dictionary. Sample usage: let ProductDetail_list = ProductDetail.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of ProductDetail Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [ProductDetail] { var models:[ProductDetail] = [] for item in array { models.append(ProductDetail(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let ProductDetail = ProductDetail(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: ProductDetail Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["crumbs"] != nil) { crumbs = Crumbs.modelsFromDictionaryArray(array: dictionary["crumbs"] as! NSArray) } if (dictionary["media"] != nil) { media = Media(dictionary: dictionary["media"] as! NSDictionary) } productId = dictionary["productId"] as? String if (dictionary["defaultCategory"] != nil) { defaultCategory = DefaultCategory(dictionary: dictionary["defaultCategory"] as! NSDictionary) } ageRestriction = dictionary["ageRestriction"] as? Int type = dictionary["type"] as? String displaySpecialOffer = dictionary["displaySpecialOffer"] as? String seoURL = dictionary["seoURL"] as? String setId = dictionary["setId"] as? String code = dictionary["code"] as? Int title = dictionary["title"] as? String if (dictionary["skus"] != nil) { skus = Skus.modelsFromDictionaryArray(array: dictionary["skus"] as! NSArray) } isFBL = dictionary["isFBL"] as? String setInformation = dictionary["setInformation"] as? String storeOnly = dictionary["storeOnly"] as? String if (dictionary["additionalServices"] != nil) { additionalServices = AdditionalServices(dictionary: dictionary["additionalServices"] as! NSDictionary) } if (dictionary["deliverySummary"] != nil) { deliverySummary = DeliverySummary.modelsFromDictionaryArray(array: dictionary["deliverySummary"] as! NSArray) } if (dictionary["details"] != nil) { details = Details(dictionary: dictionary["details"] as! NSDictionary) } if (dictionary["promotionalFeatures"] != nil) { promotionalFeatures = PromotionalFeatures.modelsFromDictionaryArray(array: dictionary["promotionalFeatures"] as! NSArray) } if (dictionary["price"] != nil) { price = Price(dictionary: dictionary["price"] as! NSDictionary) } defaultSku = dictionary["defaultSku"] as? Int isInTopNkuCategory = dictionary["isInTopNkuCategory"] as? String if (dictionary["specialOffers"] != nil) { specialOffers = SpecialOffers(dictionary: dictionary["specialOffers"] as! NSDictionary) } if (dictionary["deliveries"] != nil) { deliveries = Deliveries.modelsFromDictionaryArray(array: dictionary["deliveries"] as! NSArray) } templateType = dictionary["templateType"] as? String if (dictionary["seoInformation"] != nil) { seoInformation = SeoInformation(dictionary: dictionary["seoInformation"] as! NSDictionary) } releaseDateTimestamp = dictionary["releaseDateTimestamp"] as? Int emailMeWhenAvailable = dictionary["emailMeWhenAvailable"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.media?.dictionaryRepresentation(), forKey: "media") dictionary.setValue(self.productId, forKey: "productId") dictionary.setValue(self.defaultCategory?.dictionaryRepresentation(), forKey: "defaultCategory") dictionary.setValue(self.ageRestriction, forKey: "ageRestriction") dictionary.setValue(self.type, forKey: "type") dictionary.setValue(self.displaySpecialOffer, forKey: "displaySpecialOffer") dictionary.setValue(self.seoURL, forKey: "seoURL") dictionary.setValue(self.setId, forKey: "setId") dictionary.setValue(self.code, forKey: "code") dictionary.setValue(self.title, forKey: "title") dictionary.setValue(self.isFBL, forKey: "isFBL") dictionary.setValue(self.setInformation, forKey: "setInformation") dictionary.setValue(self.storeOnly, forKey: "storeOnly") dictionary.setValue(self.additionalServices?.dictionaryRepresentation(), forKey: "additionalServices") dictionary.setValue(self.details?.dictionaryRepresentation(), forKey: "details") dictionary.setValue(self.price?.dictionaryRepresentation(), forKey: "price") dictionary.setValue(self.defaultSku, forKey: "defaultSku") dictionary.setValue(self.isInTopNkuCategory, forKey: "isInTopNkuCategory") dictionary.setValue(self.specialOffers?.dictionaryRepresentation(), forKey: "specialOffers") dictionary.setValue(self.templateType, forKey: "templateType") dictionary.setValue(self.seoInformation?.dictionaryRepresentation(), forKey: "seoInformation") dictionary.setValue(self.releaseDateTimestamp, forKey: "releaseDateTimestamp") dictionary.setValue(self.emailMeWhenAvailable, forKey: "emailMeWhenAvailable") return dictionary } }
1cd9f34c1c3a341e3b6cab37959c65a0
47.566434
179
0.694456
false
false
false
false
asp2insp/tippical
refs/heads/master
tippical/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // tippical // // Created by Josiah Gaskin on 4/9/15. // Copyright (c) 2015 Josiah Gaskin. All rights reserved. // import UIKit let kSegmentSettingsKey = "SEGMENT_SETTINGS_ARRAY" let kDefaultTipAmount = "DEFAULT_TIP_AMOUNT" class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var valueSlider: UISlider! @IBOutlet weak var defaultTipControl: UISegmentedControl! @IBOutlet weak var tipChoicesTable: UITableView! @IBAction func doneTap(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } var TIP: [Double] = [] var SELECTED = 0 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.TIP.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = self.tipChoicesTable.dequeueReusableCellWithIdentifier("cell") as UITableViewCell cell.textLabel?.text = "\(Int(self.TIP[indexPath.row]*100))%" return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { valueSlider.value = Float(TIP[indexPath.row]) } func refreshChoices() { defaultTipControl.removeAllSegments() for t in TIP { let fmt = Int(t*100) defaultTipControl.insertSegmentWithTitle("\(fmt)%", atIndex: TIP.count, animated:false) } let selectedIndex = tipChoicesTable.indexPathForSelectedRow() tipChoicesTable.reloadData() tipChoicesTable.selectRowAtIndexPath(selectedIndex, animated: false, scrollPosition: UITableViewScrollPosition.None) } override func viewDidLoad() { super.viewDidLoad() let defaults = NSUserDefaults.standardUserDefaults() if let savedTips = defaults.arrayForKey(kSegmentSettingsKey) { TIP = savedTips as [Double] } else { TIP = [0.15, 0.18, 0.2, 0.25] defaults.setObject(TIP, forKey: kSegmentSettingsKey) } refreshChoices() defaultTipControl.selectedSegmentIndex = defaults.integerForKey(kDefaultTipAmount) self.tipChoicesTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } func save() { let defaults = NSUserDefaults.standardUserDefaults() defaults.setInteger(SELECTED, forKey: kDefaultTipAmount) defaults.setObject(TIP, forKey: kSegmentSettingsKey) } @IBAction func defaultChanged(sender: AnyObject) { SELECTED = defaultTipControl.selectedSegmentIndex save() } @IBAction func sliderChanged(sender: AnyObject) { if let selectedIndex = tipChoicesTable.indexPathForSelectedRow()?.row { TIP[selectedIndex] = Double(valueSlider.value); } refreshChoices() save() } }
67fc3fa01bf0fd73af4e7722fea54cd8
32.811111
124
0.672913
false
false
false
false
csnu17/My-Swift-learning
refs/heads/master
initialization/BlastOff.playground/Contents.swift
mit
1
import Foundation struct RocketConfiguration { let name: String = "Athena 9 Heavy" let numberOfFirstStageCores: Int = 3 let numberOfSecondStageCores: Int = 1 let numberOfStageReuseLandingLegs: Int? = nil } struct RocketStageConfiguration { let propellantMass: Double let liquidOxygenMass: Double let nominalBurnTime: Int } extension RocketStageConfiguration { init(propellantMass: Double, liquidOxygenMass: Double) { self.propellantMass = propellantMass self.liquidOxygenMass = liquidOxygenMass self.nominalBurnTime = 180 } } struct Weather { let temperatureCelsius: Double let windSpeedKilometersPerHour: Double init(temperatureFahrenheit: Double = 72, windSpeedMilesPerHour: Double = 5) { self.temperatureCelsius = (temperatureFahrenheit - 32) / 1.8 self.windSpeedKilometersPerHour = windSpeedMilesPerHour * 1.609344 } } struct GuidanceSensorStatus { var currentZAngularVelocityRadiansPerMinute: Double let initialZAngularVelocityRadiansPerMinute: Double var needsCorrection: Bool init(zAngularVelocityDegreesPerMinute: Double, needsCorrection: Bool = false) { let radiansPerMinute = zAngularVelocityDegreesPerMinute * 0.01745329251994 self.currentZAngularVelocityRadiansPerMinute = radiansPerMinute self.initialZAngularVelocityRadiansPerMinute = radiansPerMinute self.needsCorrection = needsCorrection } init(zAngularVelocityDegreesPerMinute: Double, needsCorrection: Int) { self.init(zAngularVelocityDegreesPerMinute: zAngularVelocityDegreesPerMinute, needsCorrection: (needsCorrection > 0)) } } struct CombustionChamberStatus { var temperatureKelvin: Double var pressureKiloPascals: Double init(temperatureKelvin: Double, pressureKiloPascals: Double) { print("Phase 1 init") self.temperatureKelvin = temperatureKelvin self.pressureKiloPascals = pressureKiloPascals print("CombustionChamberStatus fully initialized") print("Phase 2 init") } init(temperatureCelsius: Double, pressureAtmospheric: Double) { print("Phase 1 delegating init") let temperatureKelvin = temperatureCelsius + 273.15 let pressureKiloPascals = pressureAtmospheric * 101.325 self.init(temperatureKelvin: temperatureKelvin, pressureKiloPascals: pressureKiloPascals) print("Phase 2 delegating init") } } struct TankStatus { var currentVolume: Double var currentLiquidType: String? init?(currentVolume: Double, currentLiquidType: String?) { if currentVolume < 0 { return nil } if currentVolume > 0 && currentLiquidType == nil { return nil } self.currentVolume = currentVolume self.currentLiquidType = currentLiquidType } } enum InvalidAstronautDataError: Error { case EmptyName case InvalidAge } struct Astronaut { let name: String let age: Int init(name: String, age: Int) throws { if name.isEmpty { throw InvalidAstronautDataError.EmptyName } if age < 18 || age > 70 { throw InvalidAstronautDataError.InvalidAge } self.name = name self.age = age } } let athena9Heavy = RocketConfiguration() let stageOneConfiguration = RocketStageConfiguration(propellantMass: 119.1, liquidOxygenMass: 276.0) let currentWeather = Weather() currentWeather.temperatureCelsius currentWeather.windSpeedKilometersPerHour let guidanceStatus = GuidanceSensorStatus(zAngularVelocityDegreesPerMinute: 2.2) guidanceStatus.currentZAngularVelocityRadiansPerMinute // 0.038 guidanceStatus.needsCorrection // false CombustionChamberStatus(temperatureCelsius: 32, pressureAtmospheric: 0.96) if let tankStatus = TankStatus(currentVolume: -10.0, currentLiquidType: nil) { print("Nice, tank status created.") // Printed! } else { print("Oh no, an initialization failure occurred.") } let johnny = try? Astronaut(name: "Johnny Cosmoseed", age: 17)
082f59b0b77d4c34eb48194c277e74a6
30.219697
100
0.716262
false
false
false
false
novi/i2c-swift-example
refs/heads/master
Sources/I2CDeviceModule/BMP180.swift
mit
1
// // BMP180.swift // I2CDeviceModule // // Created by Yusuke Ito on 2/5/17. // Copyright © 2017 Yusuke Ito. All rights reserved. // import Foundation import I2C public final class BMP180 { public let address: UInt8 public let device: I2CDevice public init(device: I2CDevice, address: UInt8 = 0x77) { self.device = device self.address = address } fileprivate var calibration: CalibrationData? = nil } public enum BMP180Error: Error { case registerAccessError(address: UInt8) case invalidDeviceID case notCalibratedError } fileprivate extension BMP180 { enum ControlRegister: UInt8 { case outXLSB = 0xf8 case outLSB = 0xf7 case outMSB = 0xf6 case ctrlMeas = 0xf4 case softReset = 0xe0 case id = 0xd0 } enum CalibrationRegister: UInt8 { case MD = 0xbf case MC = 0xbd case MB = 0xbb case B2 = 0xb9 case B1 = 0xb7 case AC6 = 0xb5 case AC5 = 0xb3 case AC4 = 0xb1 case AC3 = 0xaf case AC2 = 0xad case AC1 = 0xab } struct CalibrationData { let MD: Int16 let MC: Int16 let MB: Int16 let B2: Int16 let B1: Int16 let AC6: UInt16 let AC5: UInt16 let AC4: UInt16 let AC3: Int16 let AC2: Int16 let AC1: Int16 } func readRegister(address: UInt8) throws -> UInt8 { let data = try device.write(toAddress: self.address, data: [address], readBytes: 1) guard data.count == 1 else { throw BMP180Error.registerAccessError(address: address) } return data[0] } func readRegister(_ register: ControlRegister) throws -> UInt8 { return try readRegister(address: register.rawValue) } func readRegister(address: UInt8) throws -> UInt16 { return UInt16(try readRegister(address: address) as UInt8) } func writeRegister(_ register: ControlRegister, value: UInt8) throws { try device.write(toAddress: self.address, data: [register.rawValue, value]) } func getCalibration(_ register: CalibrationRegister) throws -> UInt16 { let lsb = try readRegister(address: register.rawValue) as UInt16 let msb = try readRegister(address: register.rawValue-1) as UInt16 return UInt16( (msb << 8) | lsb ) } func getCalibration(_ register: CalibrationRegister) throws -> Int16 { let val: UInt16 = try getCalibration(register) return unsafeBitCast(val, to: Int16.self) } func getCalibration() throws -> CalibrationData { return try CalibrationData(MD: getCalibration(.MD), MC: getCalibration(.MC), MB: getCalibration(.MB), B2: getCalibration(.B1), B1: getCalibration(.B1), AC6: getCalibration(.AC6), AC5: getCalibration(.AC5), AC4: getCalibration(.AC4), AC3: getCalibration(.AC3), AC2: getCalibration(.AC2), AC1: getCalibration(.AC1)) } func checkID() throws { guard try readRegister(address: ControlRegister.id.rawValue) == 0x55 as UInt8 else { throw BMP180Error.invalidDeviceID } } } public extension BMP180 { func reset() throws { try checkID() try writeRegister(.softReset, value: 0xb6) usleep(1000*10) // 10ms } func calibrate() throws { try checkID() usleep(1000*1) // 1ms self.calibration = try getCalibration() } public struct MesurementResult { public let temperature: Int16 // in 0.1 celsius public let pressure: Int64 // in pa } enum OversamplingSetting: UInt8 { case oss0 = 0 case oss1 = 1 case oss2 = 2 case oss3 = 3 fileprivate var waitMs: UInt { switch self { case .oss0: return 5 case .oss1: return 8 case .oss2: return 14 case .oss3: return 24 } } } func mesure(oversampling oss: OversamplingSetting) throws -> MesurementResult { try checkID() guard let calibration = self.calibration else { throw BMP180Error.notCalibratedError } let b5: Int64 let t: Int64 do { try writeRegister(.ctrlMeas, value: 0x2e) usleep(1000*7) // wait 7ms let utLSB = Int64(try readRegister(.outLSB)) let utMSB = Int64(try readRegister(.outMSB)) let ut = (utMSB << 8) | utLSB let x1 = ((ut - Int64(calibration.AC6)) * Int64(calibration.AC5)) >> 15 let x2 = (Int64(calibration.MC) << 11) / (x1 + Int64(calibration.MD)) b5 = x1 + x2 t = (b5 + 8) >> 4 } let p: Int64 do { try writeRegister(.ctrlMeas, value: 0x34 | (oss.rawValue << 6)) usleep(useconds_t(oss.waitMs + 2) * 1000) // wait let upXLSB = Int64(try readRegister(.outXLSB)) let upLSB = Int64(try readRegister(.outLSB)) let upMSB = Int64(try readRegister(.outMSB)) let up = Int64(upMSB << 16 | upLSB << 8 | upXLSB) >> Int64(8-oss.rawValue) let b6 = (b5 - 4000) var x1 = ((Int64(calibration.B2) * ((b6 * b6) >> 12) )) >> 11 var x2 = (Int64(calibration.AC2) * b6) >> 11 var x3 = x1 + x2 let b3 = ( (((Int64(calibration.AC1) * 4) + x3) << Int64(oss.rawValue)) + 2 ) / 4 x1 = (Int64(calibration.AC4) * b6) >> 13 x2 = ((Int64(calibration.B1) * ((b6 * b6) >> 12) )) >> 16 x3 = (x1 + x2 + 2) >> 2 let b4 = (Int64(calibration.AC4) * (x3 + 32768)) >> 15 let b7 = (up - b3) * (50000 >> Int64(oss.rawValue)) let p0: Int64 if b7 < 0x80000000 { p0 = (b7 << 1) / b4 } else { p0 = (b7 / b4) << 1 } let xx1 = (((p0 >> 8) * (p0 >> 8)) * 3038) >> 16 let xx2 = (-7357 * p0) >> 16 p = p0 + ((xx1 + xx2 + 3791) >> 4) } return MesurementResult(temperature: Int16(t), pressure: p) } }
baa8df7ecd05e72f2eb0573d5583b261
30.079812
93
0.520242
false
false
false
false
khizkhiz/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00202-swift-parser-parseexprpostfix.swift
apache-2.0
1
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func c<b:c func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? { for (mx : e?) in c { } } protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } struct c<e> { let d: i h } func f(h: b) -> <e>(()-> e func c<g>() -> (g, g -> g) -> g { d b d.f = { } { g) { i } } i c { class func f() } class d: c{ class func f {} struct d<c : f,f where g.i == c.i> func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2 class func g() { } } (h() as p).dynamicType.g() protocol p { } protocol h : p { } protocol g : p { } protocol n { o t = p } struct h : n { t : n q m.t == m> (h: m) { } func q<t : n q t.t == g> (h: t) { } q(h()) func r(g: m) -> <s>(() -> s) -> n import Foundation class Foo<T>: NSObject { var foo: T init(foo: T) { B>(t: T) { t.c() } x x) { } class a { var _ = i() { } } a=1 as a=1 class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } } func i(f: g) -> <j>(() -> j) -> g { func g k, l { typealias l = m<k<m>, f> } func i(c: () -> ()) { } class a { var _ = i() { } } protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { t.c() } } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } func h<j>() -> (j, j -> j) -> j { var f: ({ (c: e, f: e -> e) -> return f(c) }(k, i) let o: e = { c, g return f(c) }(l) -> m) -> p>, e> } class n<j : n> b prot q g: n } func p<n>() -> [q<n>] { o : g.l) { } } class p { typealias g = g class a { typealias b = b } import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } }
4444c8e9aefb9ff3303efebc3e04c053
14.542484
87
0.445753
false
false
false
false
avito-tech/Paparazzo
refs/heads/master
Paparazzo/Core/Helpers/CaptureSessionPreviewService.swift
mit
1
import AVFoundation import ImageSource /// Delete `@objc` when the problem in Swift will be resolved /// https://bugs.swift.org/browse/SR-55 @objc public protocol CameraCaptureOutputHandler: class { var imageBuffer: CVImageBuffer? { get set } } final class CaptureSessionPreviewService: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { // MARK: - CaptureSessionPreviewService @discardableResult static func startStreamingPreview( of captureSession: AVCaptureSession, to handler: CameraCaptureOutputHandler, isMirrored: Bool = false) -> DispatchQueue { return service(for: captureSession, isMirrored: isMirrored).startStreamingPreview(to: handler) } func startStreamingPreview(to handler: CameraCaptureOutputHandler) -> DispatchQueue { queue.async { [weak self] in self?.handlers.append(WeakWrapper(value: handler)) } return queue } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate @objc func captureOutput( _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer), !isInBackground { handlers.forEach { handlerWrapper in handlerWrapper.value?.imageBuffer = imageBuffer } } } // MARK: - Deinit deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Private private static var sharedServices = NSMapTable<AVCaptureSession, CaptureSessionPreviewService>.weakToStrongObjects() private let queue = DispatchQueue(label: "ru.avito.AvitoMediaPicker.CaptureSessionPreviewService.queue") private var handlers = [WeakWrapper<CameraCaptureOutputHandler>]() private var isInBackground = false private init(captureSession: AVCaptureSession, isMirrored: Bool) { super.init() subscribeForAppStateChangeNotifications() setUpVideoDataOutput(for: captureSession, isMirrored: isMirrored) } private static func service(for captureSession: AVCaptureSession, isMirrored: Bool) -> CaptureSessionPreviewService { if let service = sharedServices.object(forKey: captureSession) { return service } else { let service = CaptureSessionPreviewService(captureSession: captureSession, isMirrored: isMirrored) sharedServices.setObject(service, forKey: captureSession) return service } } private func subscribeForAppStateChangeNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(handleAppWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil ) notificationCenter.addObserver( self, selector: #selector(handleAppDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil ) } private func setUpVideoDataOutput(for captureSession: AVCaptureSession, isMirrored: Bool) { let captureOutput = AVCaptureVideoDataOutput() // CoreImage wants BGRA pixel format captureOutput.videoSettings = [ kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: kCVPixelFormatType_32BGRA) ] captureOutput.setSampleBufferDelegate(self, queue: queue) do { try captureSession.configure { if captureSession.canAddOutput(captureOutput) { captureSession.addOutput(captureOutput) } for connection in captureOutput.connections { if connection.isVideoOrientationSupported { connection.videoOrientation = .portrait connection.isVideoMirrored = isMirrored } } } } catch { debugPrint("Couldn't configure AVCaptureSession: \(error)") } } @objc private func handleAppWillResignActive(_: NSNotification) { // Синхронно, потому что после выхода из этого метода не должно быть никаких обращений к OpenGL // (флаг isInBackground проверяется в очереди `queue`) queue.sync { glFinish() self.isInBackground = true } } @objc private func handleAppDidBecomeActive(_: NSNotification) { queue.async { self.isInBackground = false } } }
f3f40f9259ec3e70fb3c1ac252dddaeb
33.824818
121
0.640956
false
false
false
false
mmick66/CalendarView
refs/heads/master
KDCalendar/CalendarView/EventsManager.swift
mit
1
/* * EventsLoader.swift * Created by Michael Michailidis on 26/10/2017. * http://blog.karmadust.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #if KDCALENDAR_EVENT_MANAGER_ENABLED import Foundation import EventKit enum EventsManagerError: Error { case Authorization } open class EventsManager { private static let store = EKEventStore() static func load(from fromDate: Date, to toDate: Date, complete onComplete: @escaping ([CalendarEvent]?) -> Void) { let q = DispatchQueue.main guard EKEventStore.authorizationStatus(for: .event) == .authorized else { return EventsManager.store.requestAccess(to: EKEntityType.event, completion: {(granted, error) -> Void in guard granted else { return q.async { onComplete(nil) } } EventsManager.fetch(from: fromDate, to: toDate) { events in q.async { onComplete(events) } } }) } EventsManager.fetch(from: fromDate, to: toDate) { events in q.async { onComplete(events) } } } static func add(event calendarEvent: CalendarEvent) -> Bool { guard EKEventStore.authorizationStatus(for: .event) == .authorized else { return false } let secondsFromGMTDifference = TimeInterval(TimeZone.current.secondsFromGMT()) * -1 let event = EKEvent(eventStore: store) event.title = calendarEvent.title event.startDate = calendarEvent.startDate.addingTimeInterval(secondsFromGMTDifference) event.endDate = calendarEvent.endDate.addingTimeInterval(secondsFromGMTDifference) event.calendar = store.defaultCalendarForNewEvents do { try store.save(event, span: .thisEvent) return true } catch { return false } } private static func fetch(from fromDate: Date, to toDate: Date, complete onComplete: @escaping ([CalendarEvent]) -> Void) { let predicate = store.predicateForEvents(withStart: fromDate, end: toDate, calendars: nil) let secondsFromGMTDifference = TimeInterval(TimeZone.current.secondsFromGMT()) let events = store.events(matching: predicate).map { return CalendarEvent( title: $0.title, startDate: $0.startDate.addingTimeInterval(secondsFromGMTDifference), endDate: $0.endDate.addingTimeInterval(secondsFromGMTDifference) ) } onComplete(events) } } #endif
5fa1a7f79f1f1ecef50bb157f512b77a
37.708333
127
0.653122
false
false
false
false
kylebrowning/waterwheel.swift
refs/heads/4.x
Sources/iOS/Buttons/waterwheelAuthButton.swift
mit
1
// // waterwheelAuthButton.swift // Only For use in iOS import UIKit import Alamofire import SwiftyJSON /** Provide an enum to handle. - Login: login Auth Action - Logout: logout Auth Action */ public enum AuthAction: String { case Login = "Login", Logout = "Logout" } /// A UIButton subclass that will always display the logged in state. open class waterwheelAuthButton: UIButton { open var didPressLogin: () -> Void = { _ in } open var didPressLogout: (_ success: Bool, _ error: NSError?) -> Void = { success, error in } /** A initializer to handle run once code for the button. */ fileprivate func initButton() -> Void { // Incase of logout or login, we attach to the notification Center for the purpose of seeing requests. NotificationCenter.default.addObserver( self, selector: #selector(configureButton), name: NSNotification.Name(rawValue: waterwheelNotifications.waterwheelDidFinishRequest.rawValue), object: nil) self.translatesAutoresizingMaskIntoConstraints = false self.setTitleColor(UIButton(type: UIButtonType.system).titleColor(for: UIControlState())!, for: UIControlState()) self.configureButton() } /** Override init to setup our button. - parameter frame: frame for view - returns: */ override public init(frame: CGRect) { super.init(frame: frame) self.initButton() } /** Configures the button for its current state. */ open func configureButton() { if waterwheel.isLoggedIn() { self.setTitle("Logout", for: UIControlState()) self.removeTarget(self, action: #selector(waterwheelAuthButton.loginAction), for: .touchUpInside) self.addTarget(self, action: #selector(waterwheelAuthButton.logoutAction), for: .touchUpInside) } else { self.setTitle("Login", for: UIControlState()) self.removeTarget(self, action: #selector(waterwheelAuthButton.logoutAction), for: .touchUpInside) self.addTarget(self, action: #selector(waterwheelAuthButton.loginAction), for: .touchUpInside) } } /// This is required for Swift required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initButton() } /** This method provies an action to take when the button is in a logged in state. We automatically log the user out, but provide a closure that can be used to do anything else base on the outcome. */ open func logoutAction() { waterwheel.logout { (success, _, _, error) in self.didPressLogout(success, error) } } /** This method provies an action to take when the button is in a logged out state. */ open func loginAction() { self.didPressLogin() } }
5337668caeb1820bf2fe141b030af1ba
30.150538
121
0.649638
false
false
false
false
blstream/StudyBox_iOS
refs/heads/master
StudyBox_iOS/LoginViewController.swift
apache-2.0
1
// // LoginViewController.swift // StudyBox_iOS // // Created by Damian Malarczyk on 27.02.2016. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import Reachability import SVProgressHUD class LoginViewController: UserViewController, InputViewControllerDataSource { @IBOutlet weak var logInButton: UIButton! @IBOutlet weak var emailTextField: EmailValidatableTextField! @IBOutlet weak var passwordTextField: ValidatableTextField! @IBOutlet weak var unregisteredUserButton: UIButton! @IBOutlet weak var registerUserButton: UIButton! var inputViews = [UITextField]() override func viewDidLoad() { super.viewDidLoad() inputViews.appendContentsOf([emailTextField, passwordTextField]) inputViews.forEach { if let validable = $0 as? ValidatableTextField { validable.validColor = UIColor.sb_DarkBlue() validable.invalidColor = UIColor.sb_Raspberry() validable.textColor = validable.validColor } } logInButton.layer.cornerRadius = 10.0 logInButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false) disableButton(logInButton) unregisteredUserButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false) registerUserButton.titleLabel?.font = UIFont.sbFont(size: sbFontSizeMedium, bold: false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dataSource = self } func loginToServer(withEmail email: String, password: String) { let newDataManager = UIApplication.appDelegate().dataManager newDataManager.login(email, password: password, completion: { response in var errorMessage = "Błąd logowania" switch response { case .Success(let user): newDataManager.remoteDataManager.saveEmailPassInDefaults(user.email, pass: user.password) SVProgressHUD.dismiss() self.successfulLoginTransition() case .Error(let err): if case .ErrorWithMessage(let txt)? = (err as? ServerError){ errorMessage = txt } SVProgressHUD.showErrorWithStatus(errorMessage) } }) } func loginWithInputData(login: String? = nil, password: String? = nil) { var alertMessage: String? if !Reachability.isConnected() { alertMessage = "Brak połączenia z Internetem" } for inputView in inputViews { if let validatableTextField = inputView as? ValidatableTextField { if let message = validatableTextField.invalidMessage { alertMessage = message break } } } if areTextFieldsEmpty() { alertMessage = "Wypełnij wszystkie pola!" } if let message = alertMessage { SVProgressHUD.showErrorWithStatus(message) return } inputViews.forEach { $0.resignFirstResponder() } if let login = login, password = password { loginToServer(withEmail: login, password: password) } else if let email = emailTextField.text, password = passwordTextField.text { loginToServer(withEmail: email, password: password) } } @IBAction func login(sender: UIButton) { SVProgressHUD.showWithStatus("Logowanie...") loginWithInputData() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { var validationResult = true var invalidMessage: String? if let text = textField.text as NSString? { textField.text = text.stringByReplacingCharactersInRange(range, withString: string) } if textField == emailTextField, let _ = textField.text { validationResult = emailTextField.isValid() if !validationResult { invalidMessage = ValidationMessage.EmailIncorrect.rawValue } } else if textField == passwordTextField, let text = textField.text { validationResult = text.isValidPassword(minimumCharacters: Utils.UserAccount.MinimumPasswordLength) if !validationResult { invalidMessage = ValidationMessage.PasswordIncorrect.rawValue } } if let validatableTextField = textField as? ValidatableTextField { validatableTextField.invalidMessage = invalidMessage } if areTextFieldsValid() { enableButton(logInButton) } else { disableButton(logInButton) } return false } @IBAction func loginWithoutAccount(sender: AnyObject) { successfulLoginTransition() } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == passwordTextField { textField.resignFirstResponder() loginWithInputData() return false } else if textField == emailTextField { passwordTextField.becomeFirstResponder() } return true } }
60c60246ebb4a3db77f470db1f8f257c
34.064103
132
0.613346
false
false
false
false
stephanmantler/SwiftyGPIO
refs/heads/master
Sources/SwiftyGPIO.swift
mit
1
/* SwiftyGPIO Copyright (c) 2016 Umberto Raimondi Licensed under the MIT license, as follows: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.) */ #if os(Linux) import Glibc #else import Darwin.C #endif import Foundation internal let GPIOBASEPATH="/sys/class/gpio/" // MARK: GPIO public class GPIO { public var bounceTime: TimeInterval? public private(set) var name: String = "" public private(set) var id: Int = 0 var exported = false var listening = false var intThread: Thread? var intFalling: (func: ((GPIO) -> Void), lastCall: Date?)? var intRaising: (func: ((GPIO) -> Void), lastCall: Date?)? var intChange: (func: ((GPIO) -> Void), lastCall: Date?)? public init(name: String, id: Int) { self.name = name self.id = id } public var direction: GPIODirection { set(dir) { if !exported {enableIO(id)} performSetting("gpio" + String(id) + "/direction", value: dir.rawValue) } get { if !exported { enableIO(id)} return GPIODirection(rawValue: getStringValue("gpio"+String(id)+"/direction")!)! } } public var edge: GPIOEdge { set(dir) { if !exported {enableIO(id)} performSetting("gpio"+String(id)+"/edge", value: dir.rawValue) } get { if !exported {enableIO(id)} return GPIOEdge(rawValue: getStringValue("gpio"+String(id)+"/edge")!)! } } public var activeLow: Bool { set(act) { if !exported {enableIO(id)} performSetting("gpio"+String(id)+"/active_low", value: act ? "1":"0") } get { if !exported {enableIO(id)} return getIntValue("gpio"+String(id)+"/active_low")==0 } } public var pull: GPIOPull { set(dir) { fatalError("Unsupported parameter.") } get{ fatalError("Parameter cannot be read.") } } public var value: Int { set(val) { if !exported {enableIO(id)} performSetting("gpio"+String(id)+"/value", value: val) } get { if !exported {enableIO(id)} return getIntValue("gpio"+String(id)+"/value")! } } public func isMemoryMapped() -> Bool { return false } public func onFalling(_ closure: @escaping (GPIO) -> Void) { intFalling = (func: closure, lastCall: nil) if intThread == nil { intThread = makeInterruptThread() listening = true intThread?.start() } } public func onRaising(_ closure: @escaping (GPIO) -> Void) { intRaising = (func: closure, lastCall: nil) if intThread == nil { intThread = makeInterruptThread() listening = true intThread?.start() } } public func onChange(_ closure: @escaping (GPIO) -> Void) { intChange = (func: closure, lastCall: nil) if intThread == nil { intThread = makeInterruptThread() listening = true intThread?.start() } } public func clearListeners() { (intFalling, intRaising, intChange) = (nil, nil, nil) listening = false } } fileprivate extension GPIO { func enableIO(_ id: Int) { writeToFile(GPIOBASEPATH+"export", value:String(id)) exported = true } func performSetting(_ filename: String, value: String) { writeToFile(GPIOBASEPATH+filename, value:value) } func performSetting(_ filename: String, value: Int) { writeToFile(GPIOBASEPATH+filename, value: String(value)) } func getStringValue(_ filename: String) -> String? { return readFromFile(GPIOBASEPATH+filename) } func getIntValue(_ filename: String) -> Int? { if let res = readFromFile(GPIOBASEPATH+filename) { return Int(res) } return nil } func writeToFile(_ path: String, value: String) { let fp = fopen(path, "w") if fp != nil { #if swift(>=3.2) let len = value.count #else let len = value.characters.count #endif let ret = fwrite(value, MemoryLayout<CChar>.stride, len, fp) if ret<len { if ferror(fp) != 0 { perror("Error while writing to file") abort() } } fclose(fp) } } func readFromFile(_ path: String) -> String? { let MAXLEN = 8 let fp = fopen(path, "r") var res: String? if fp != nil { let buf = UnsafeMutablePointer<CChar>.allocate(capacity: MAXLEN) let len = fread(buf, MemoryLayout<CChar>.stride, MAXLEN, fp) if len < MAXLEN { if ferror(fp) != 0 { perror("Error while reading from file") abort() } } fclose(fp) //Remove the trailing \n buf[len-1]=0 res = String.init(validatingUTF8: buf) #if swift(>=4.1) buf.deallocate() #else buf.deallocate(capacity: MAXLEN) #endif } return res } func makeInterruptThread() -> Thread? { //Ignored by Linux guard #available(iOS 10.0, macOS 10.12, *) else {return nil} let thread = Thread { let gpath = GPIOBASEPATH+"gpio"+String(self.id)+"/value" self.direction = .IN self.edge = .BOTH let fp = open(gpath, O_RDONLY) var buf: [Int8] = [0, 0, 0] //Dummy read to discard current value read(fp, &buf, 3) #if swift(>=4.0) var pfd = pollfd(fd:fp, events:Int16(truncatingIfNeeded:POLLPRI), revents:0) #else var pfd = pollfd(fd:fp, events:Int16(truncatingBitPattern:POLLPRI), revents:0) #endif while self.listening { let ready = poll(&pfd, 1, -1) if ready > -1 { lseek(fp, 0, SEEK_SET) read(fp, &buf, 2) buf[1]=0 let res = String(validatingUTF8: buf)! switch res { case "0": self.interrupt(type: &(self.intFalling)) case "1": self.interrupt(type: &(self.intRaising)) default: break } self.interrupt(type: &(self.intChange)) } } } return thread } func interrupt(type: inout (func: ((GPIO) -> Void), lastCall: Date?)?) { guard let itype = type else { return } if let interval = self.bounceTime, let lastCall = itype.lastCall, Date().timeIntervalSince(lastCall) < interval { return } itype.func(self) type?.lastCall = Date() } } extension GPIO: CustomStringConvertible { public var description: String { return "\(name)<\(direction),\(edge),\(activeLow)>: \(value)" } } // MARK: GPIO:Raspberry public final class RaspberryGPIO: GPIO { var setGetId: UInt32 = 0 var baseAddr: Int = 0 var inited = false let BCM2708_PERI_BASE: Int let GPIO_BASE: Int var gpioBasePointer: UnsafeMutablePointer<UInt32>! var gpioGetPointer: UnsafeMutablePointer<UInt32>! var gpioSetPointer: UnsafeMutablePointer<UInt32>! var gpioClearPointer: UnsafeMutablePointer<UInt32>! public init(name: String, id: Int, baseAddr: Int) { self.setGetId = UInt32(1<<id) self.BCM2708_PERI_BASE = baseAddr self.GPIO_BASE = BCM2708_PERI_BASE + 0x200000 /* GPIO controller */ super.init(name:name, id:id) } public override var value: Int { set(val) { if !inited {initIO()} gpioSet(val) } get { if !inited {initIO()} return gpioGet() } } public override var direction: GPIODirection { set(dir) { if !inited {initIO()} if dir == .IN { gpioAsInput() } else { gpioAsOutput() } } get { if !inited {initIO()} return gpioGetDirection() } } public override var pull: GPIOPull { set(pull) { if !exported {enableIO(id)} setGpioPull(pull) } get{ fatalError("Parameter cannot be read.") } } public override func isMemoryMapped() -> Bool { return true } private func initIO() { var mem_fd: Int32 = 0 //Try to open one of the mem devices for device in ["/dev/gpiomem", "/dev/mem"] { mem_fd=open(device, O_RDWR | O_SYNC) if mem_fd>0 { break } } guard mem_fd > 0 else { fatalError("Can't open /dev/mem , use sudo!") } let gpio_map = mmap( nil, //Any adddress in our space will do PAGE_SIZE, //Map length PROT_READ|PROT_WRITE, // Enable reading & writting to mapped memory MAP_SHARED, //Shared with other processes mem_fd, //File to map off_t(GPIO_BASE) //Offset to GPIO peripheral, i.e. GPFSEL0 )! close(mem_fd) if (Int(bitPattern: gpio_map) == -1) { //MAP_FAILED not available, but its value is (void*)-1 perror("mmap error") abort() } gpioBasePointer = gpio_map.assumingMemoryBound(to: UInt32.self) gpioGetPointer = gpioBasePointer.advanced(by: 13) // GPLEV0 gpioSetPointer = gpioBasePointer.advanced(by: 7) // GPSET0 gpioClearPointer = gpioBasePointer.advanced(by: 10) // GPCLR0 inited = true } private func gpioAsInput() { let ptr = gpioBasePointer.advanced(by: id/10) // GPFSELn 0..5 ptr.pointee &= ~(7<<((UInt32(id)%10)*3)) // SEL=000 input } private func gpioAsOutput() { let ptr = gpioBasePointer.advanced(by: id/10) // GPFSELn 0..5 ptr.pointee &= ~(7<<((UInt32(id)%10)*3)) ptr.pointee |= (1<<((UInt32(id)%10)*3)) // SEL=001 output } private func gpioGetDirection() -> GPIODirection { let ptr = gpioBasePointer.advanced(by: id/10) // GPFSELn 0..5 let d = (ptr.pointee & (7<<((UInt32(id)%10)*3))) return (d == 0) ? .IN : .OUT } func setGpioPull(_ value: GPIOPull){ let gpioGPPUDPointer = gpioBasePointer.advanced(by: 37) gpioGPPUDPointer.pointee = value.rawValue // Configure GPPUD usleep(10); // 150 cycles or more let gpioGPPUDCLK0Pointer = gpioBasePointer.advanced(by: 38) gpioGPPUDCLK0Pointer.pointee = setGetId // Configure GPPUDCLK0 for specific gpio (Ids always lower than 31, no GPPUDCLK1 needed) usleep(10); // 150 cycles or more gpioGPPUDPointer.pointee = 0 // Reset GPPUD usleep(10); // 150 cycles or more gpioGPPUDCLK0Pointer.pointee = 0 // Reset GPPUDCLK0/1 for specific gpio usleep(10); // 150 cycles or more } private func gpioGet() -> Int { return ((gpioGetPointer.pointee & setGetId)>0) ? 1 : 0 } private func gpioSet(_ value: Int) { let ptr = value==1 ? gpioSetPointer : gpioClearPointer ptr!.pointee = setGetId } } public struct SwiftyGPIO { public static func GPIOs(for board: SupportedBoard) -> [GPIOName: GPIO] { switch board { case .RaspberryPiRev1: return GPIORPIRev1 case .RaspberryPiRev2: return GPIORPIRev2 case .RaspberryPiPlusZero: return GPIORPIPlusZERO case .RaspberryPi2: fallthrough case .RaspberryPi3: return GPIORPI2 case .CHIP: return GPIOCHIP case .BeagleBoneBlack: return GPIOBEAGLEBONE case .OrangePi: return GPIOORANGEPI case .OrangePiZero: return GPIOORANGEPIZERO } } } // MARK: - Global Enums public enum SupportedBoard: String { case RaspberryPiRev1 // Pi A,B Revision 1 case RaspberryPiRev2 // Pi A,B Revision 2 case RaspberryPiPlusZero // Pi A+,B+,Zero with 40 pin header case RaspberryPi2 // Pi 2 with 40 pin header case RaspberryPi3 // Pi 3 with 40 pin header case CHIP case BeagleBoneBlack case OrangePi case OrangePiZero } public enum GPIOName: String { case P0 case P1 case P2 case P3 case P4 case P5 case P6 case P7 case P8 case P9 case P10 case P11 case P12 case P13 case P14 case P15 case P16 case P17 case P18 case P19 case P20 case P21 case P22 case P23 case P24 case P25 case P26 case P27 case P28 case P29 case P30 case P31 case P32 case P33 case P34 case P35 case P36 case P37 case P38 case P39 case P40 case P41 case P42 case P43 case P44 case P45 case P46 case P47 } public enum GPIODirection: String { case IN="in" case OUT="out" } public enum GPIOEdge: String { case NONE="none" case RISING="rising" case FALLING="falling" case BOTH="both" } public enum GPIOPull: UInt32 { case neither = 0 case down = 1 case up = 2 } public enum ByteOrder { case MSBFIRST case LSBFIRST } // MARK: - Codable #if swift(>=4.0) extension SupportedBoard: Codable { } extension GPIOName: Codable { } extension GPIODirection: Codable { } extension GPIOEdge: Codable { } extension GPIOPull: Codable { } #endif // MARK: - Constants let PAGE_SIZE = (1 << 12) // MARK: - Darwin / Xcode Support #if os(OSX) || os(iOS) private var O_SYNC: CInt { fatalError("Linux only") } #endif
7e3582fb38fea0fb3af0221755a33dff
26.730216
140
0.550266
false
false
false
false
cpmpercussion/microjam
refs/heads/develop
chirpey/MixerTableViewController.swift
mit
1
// // MixerTableViewController.swift // microjam // A controller for mixing different jams in layers. // // Created by Charles Martin on 6/11/18. // Copyright © 2018 Charles Martin. All rights reserved. // import UIKit let mixerTableReuseIdentifier = "mixerTableReuseIdentifier" class MixerTableViewController: UITableViewController { /// The ChirpJamViewController that sent us here. var controllerToMix: ChirpJamViewController? /// The layered jams to mix here. var chirpsToMix: [ChirpView]? /// An optional recording chirp. var recordingChirp: ChirpRecordingView? /// Local reference to the PerformerProfileStore. let profilesStore = PerformerProfileStore.shared override func viewWillAppear(_ animated: Bool) { super.viewDidAppear(animated) setColourTheme() // set colours } convenience init(withChirps chirps: [ChirpView]) { self.init() chirpsToMix = chirps self.modalPresentationStyle = .pageSheet tableView.register(MixerTableViewCell.self, forCellReuseIdentifier: mixerTableReuseIdentifier) tableView.rowHeight = 80 // do some more init. } convenience init(withChirps chirps: [ChirpView], andRecording recorder: ChirpRecordingView) { self.init(withChirps: chirps) self.recordingChirp = recorder chirpsToMix?.insert(recorder, at: 0) // just put the recording chirp at the top. } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let chirpsToMix = chirpsToMix else { return 0 } print("Mixer: \(chirpsToMix.count) layers") return chirpsToMix.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: mixerTableReuseIdentifier, for: indexPath) as! MixerTableViewCell cell.chirp = chirpsToMix![indexPath.row] // cell.instrumentLabel.text = cell.chirp?.performance?.instrument cell.volumeSlider.tintColor = cell.chirp?.performance?.colour cell.volumeSlider.thumbTintColor = cell.chirp?.performance?.colour cell.setVolume(vol: Float(cell.chirp?.volume ?? 1.0)) cell.setMute(muted: cell.chirp?.muted ?? false) cell.controllerToMix = controllerToMix if let perf = cell.chirp?.performance, let profile = profilesStore.getProfile(forPerformance: perf) { cell.avatarView.image = profile.avatar } else if cell.chirp is ChirpRecordingView { // it's a recording view. cell.avatarView.image = UserProfile.shared.profile.avatar } else { cell.avatarView.image = #imageLiteral(resourceName: "empty-profile-image") } cell.setColourTheme() // set colour theme if reloading. return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } // Set up dark and light mode. extension MixerTableViewController { @objc func setColourTheme() { if UserDefaults.standard.bool(forKey: SettingsKeys.darkMode) { setDarkMode() } else { setLightMode() } } func setDarkMode() { tableView.backgroundColor = DarkMode.background } func setLightMode() { tableView.backgroundColor = LightMode.background } }
dc56123f1e91e304026eb7dca533059c
34.11875
136
0.663997
false
false
false
false
LiuDeng/LazyCocoa
refs/heads/master
Source/LazyCocoa-MacApp/ChangeHeaderViewController.swift
mit
2
// // ChangeHeaderViewController.swift // The Lazy Cocoa Project // // Copyright (c) 2015 Yichi Zhang. 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 AppKit class ChangeHeaderViewController : BaseViewController { var dataArray:[PlainTextFile]? var loadingView:LoadingView? @IBOutlet var originalFileTextView: NSTextView! @IBOutlet var newFileTextView: NSTextView! @IBOutlet var newHeaderCommentTextView: NSTextView! @IBOutlet weak var fileTableView: NSTableView! @IBOutlet weak var filePathRegexCheckBox: NSButton! @IBOutlet weak var filePathRegexTextField: NSTextField! @IBOutlet weak var originalHeaderRegexCheckBox: NSButton! @IBOutlet weak var originalHeaderRegexTextField: NSTextField! @IBOutlet weak var applyChangesButton: NSButton! // MARK: Load and update data func updateFiles() { if dataArray != nil { for textFile in dataArray! { var filePathRegexString:String? = nil if filePathRegexCheckBox.state == NSOnState { filePathRegexString = filePathRegexTextField.stringValue } var originalHeaderRegexString:String? = nil if originalHeaderRegexCheckBox.state == NSOnState { originalHeaderRegexString = originalHeaderRegexTextField.stringValue } textFile.updateInclusiveness(filePathRegexString: filePathRegexString, originalHeaderRegexString: originalHeaderRegexString) } } fileTableView.reloadData() } func updateTextViews() { // NSTableView's selectedRow property // When multiple rows are selected, this property contains only the index of the last one in the selection. // If no row is selected, the value of this property is -1. updateTextViewsWith(textFileAtRow: fileTableView.selectedRow) } func updateTextViewsWith(textFileAtRow row:Int) { // "row < dataArray?.count" is false if dataArray is nil. if row >= 0 && row < dataArray?.count { let textFile = dataArray![row] if let string = textFile.fileString { let headerChanger = HeaderChanger(string: string, newComment: newHeaderCommentTextView.string!, filename: textFile.filename) originalFileTextView.textStorage?.setAttributedString(headerChanger.originalAttributedString) newFileTextView.textStorage?.setAttributedString(headerChanger.newAttributedString) originalFileTextView.scrollRectToVisible(NSRect(origin: CGPointZero, size: CGSizeZero)) newFileTextView.scrollRectToVisible(NSRect(origin: CGPointZero, size: CGSizeZero)) } } } // MARK: Update views func updateControlSettings(#enabled:Bool) { newHeaderCommentTextView.userInteractionEnabled = enabled fileTableView.userInteractionEnabled = enabled filePathRegexCheckBox.userInteractionEnabled = enabled filePathRegexTextField.userInteractionEnabled = enabled originalHeaderRegexCheckBox.userInteractionEnabled = enabled originalHeaderRegexTextField.userInteractionEnabled = enabled applyChangesButton.userInteractionEnabled = enabled originalFileTextView.selectable = enabled newFileTextView.selectable = enabled } // MARK: Base View Controller override func loadData() { if let baseURL = NSURL(fileURLWithPath: basePath) { loadingView?.removeFromSuperview() loadingView = nil loadingView = LoadingView.newViewWithNibName("LoadingView") if let v = loadingView { v.delegate = self let layer = CALayer() layer.backgroundColor = NSColor.windowBackgroundColor().CGColor v.wantsLayer = true v.layer = layer v.frame = NSRect(origin: CGPointZero, size: self.view.frame.size) // Add loading view self.view.addSubview(v, positioned: NSWindowOrderingMode.Above, relativeTo: nil) v.progressIndicator.startAnimation(self) v.setupConstraintsMakingViewAdhereToEdgesOfSuperview() // Set up view updateControlSettings(enabled: false) // Set up variables self.loadingCancelled = false self.dataArray = [PlainTextFile]() self.fileTableView.reloadData() dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0)) { let acceptableSuffixArray = [".h", ".m", ".swift"] let fileManager = NSFileManager() let keys = [NSURLIsDirectoryKey] let enumerator = fileManager.enumeratorAtURL(baseURL, includingPropertiesForKeys: keys, options: NSDirectoryEnumerationOptions.allZeros, errorHandler: { (url:NSURL!, err:NSError!) -> Bool in // Handle the error. // Return true if the enumeration should continue after the error. return true }) while let element = enumerator?.nextObject() as? NSURL { if self.loadingCancelled == true { break } var error:NSError? var isDirectory:AnyObject? if !element.getResourceValue(&isDirectory, forKey: NSURLIsDirectoryKey, error: &error) { } for suffix in acceptableSuffixArray { if element.absoluteString!.hasSuffix(suffix) { // check the extension dispatch_async(dispatch_get_main_queue()) { self.loadingView?.messageTextField.stringValue = "\(relativePathFrom(fullPath: element.absoluteString!))" } self.dataArray?.append(PlainTextFile(fileURL: element)) } } } if self.loadingCancelled == false { dispatch_async(dispatch_get_main_queue()) { self.fileTableView.reloadData() self.loadingView?.removeFromSuperview() self.loadingView = nil self.updateControlSettings(enabled: true) self.updateFiles() } } else { dispatch_async(dispatch_get_main_queue()) { self.loadingView?.removeFromSuperview() self.loadingView = nil } } } } } } override func cancelLoading() { loadingCancelled = true self.dataArray?.removeAll(keepCapacity: true) } // MARK: View life cycle override func viewDidLoad() { super.viewDidLoad() originalFileTextView.setUpTextStyleWith(size: 12) originalFileTextView.editable = false newFileTextView.setUpTextStyleWith(size: 12) newFileTextView.editable = false newHeaderCommentTextView.setUpTextStyleWith(size: 12) newHeaderCommentTextView.string = String.stringInBundle(name:"MIT_template") fileTableView.setDataSource(self) fileTableView.setDelegate(self) fileTableView.reloadData() filePathRegexCheckBox.action = "checkBoxStateChanged:" filePathRegexTextField.delegate = self originalHeaderRegexCheckBox.action = "checkBoxStateChanged:" originalHeaderRegexTextField.delegate = self applyChangesButton.action = "applyChangesButtonTapped:" } // MARK: UI actions func checkBoxStateChanged(sender: NSButton) { updateFiles() } func applyChangesButtonTapped(sender: NSButton) { if dataArray != nil { var count = 0 let listMax = 10 var fileListString = "" for file in dataArray! { if file.included { if count < listMax { fileListString = fileListString + relativePathFrom(fullPath: file.path) + StringConst.NewLine } else if count == listMax { fileListString = fileListString + "..." + StringConst.NewLine } count++ } } if count > 0 { let alert = NSAlert() let fileString = count>1 ? "files" : "file" alert.alertStyle = NSAlertStyle.InformationalAlertStyle alert.messageText = "You are about to change \(count) \(fileString). You might want to back up first to prevent possible data loss. Do you wish to proceed? Files to be changed: " alert.informativeText = fileListString alert.addButtonWithTitle("OK") alert.addButtonWithTitle("Cancel") if alert.runModal() == NSAlertFirstButtonReturn { let newHeaderComment = newHeaderCommentTextView.string! for file in dataArray! { if file.included { if let string = file.fileString { let headerChanger = HeaderChanger(string: string, newComment: newHeaderComment, filename: file.filename) file.updateFileWith(newFileString: headerChanger.newFileString as String) } } } } } } updateTextViews() } } extension ChangeHeaderViewController : LoadingViewDelegate { func loadingViewCancelButtonTapped(vc: LoadingView) { self.cancelLoading() } } extension ChangeHeaderViewController : NSTextFieldDelegate { override func controlTextDidChange(obj: NSNotification) { updateFiles() } } extension ChangeHeaderViewController : NSTableViewDelegate { func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool { if tableView.selectedRow != row { updateTextViewsWith(textFileAtRow: row) } return true } } extension ChangeHeaderViewController : NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { if let dataArray = dataArray { return dataArray.count } return 0 } func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { if let tableColumn = tableColumn { if let cellView = tableView.makeViewWithIdentifier("Cell", owner: self) as? NSTableCellView { let currentFile = dataArray![row] switch tableColumn.title { case "File": cellView.textField?.stringValue = relativePathFrom(fullPath: currentFile.path) case "Included": cellView.textField?.stringValue = currentFile.included ? "Yes" : "No" break default: break } return cellView } } return nil } func relativePathFrom(#fullPath:String) -> String { if let range = fullPath.rangeOfString(basePath) { var relPath = fullPath.substringFromIndex(range.endIndex) if count(relPath)>0 && relPath.characterAtIndex(0) == Character("/") { relPath = relPath.substringFromIndex( advance(relPath.startIndex, 1) ) } return relPath } else { return fullPath } } }
865e811ea51ddd0efe20352e43113b03
28.568
195
0.710137
false
false
false
false
lwg123/swift_LWGWB
refs/heads/master
LWGWB/LWGWB/classes/Main/Visitor/BaseViewController.swift
mit
1
// // BaseViewController.swift // LWGWB // // Created by weiguang on 2017/1/11. // Copyright © 2017年 weiguang. All rights reserved. // import UIKit class BaseViewController: UITableViewController { // MARK:- 懒加载属性 lazy var visitorView : VisitorView = VisitorView.visitorView() // MARK: - 定义变量 var isLogin : Bool = false // MARK:- 系统回调函数 override func loadView() { //1.从沙盒中读取归档的信息 var path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! path = (path as NSString).strings(byAppendingPaths: ["account.plist"])[0] as String // 2 如果能读取到用户信息,并且日期不过期则直接登录,否则显示访客视图 let account = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? UserAccount if let account = account { // 取出过期日期 if let expiresDate = account.expires_date { isLogin = expiresDate.compare(Date()) == ComparisonResult.orderedDescending } } isLogin ? super.loadView() : setupVisitorView() } override func viewDidLoad() { super.viewDidLoad() setupNavigationItems() } } // MARK:- 设置UI界面 extension BaseViewController { fileprivate func setupVisitorView() { view = visitorView // 监听访客视图中`注册`和`登录`按钮的点击 visitorView.registerBtn.addTarget(self, action: #selector(BaseViewController.registerBtnClick), for: .touchUpInside) visitorView.loginBtn.addTarget(self, action: #selector(BaseViewController.loginBtnClick), for: .touchUpInside) } /// 设置导航栏左右的Item fileprivate func setupNavigationItems() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(BaseViewController.registerBtnClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(BaseViewController.loginBtnClick)) } } // MARK:- 事件监听 extension BaseViewController { @objc fileprivate func registerBtnClick(){ print("registerBtnClick") } @objc fileprivate func loginBtnClick(){ let oauthVC = OAuthViewController() // 包装导航控制器 let oathNav = UINavigationController(rootViewController: oauthVC) // 弹出控制器 present(oathNav, animated: true, completion: nil) } }
fcf359ff0dcf07b8355f2cee275ddea7
27.313953
156
0.646407
false
false
false
false
amraboelela/SwiftLevelDB
refs/heads/master
Sources/SwiftLevelDB/LevelDB.swift
mit
1
// // LevelDB.swift // // Copyright 2011-2016 Pave Labs. // // Modified by: Amr Aboelela <[email protected]> // Date: Aug 2016 // // See LICENCE for details. // import Foundation import CLevelDB public typealias LevelDBKeyCallback = (String, UnsafeMutablePointer<Bool>) -> Void public func SearchPathForDirectoriesInDomains(_ directory: FileManager.SearchPathDirectory, _ domainMask: FileManager.SearchPathDomainMask, _ expandTilde: Bool) -> [String] { let bundle = Bundle.main let bundlePath = bundle.bundlePath if domainMask == .userDomainMask { switch directory { case .libraryDirectory: return [bundlePath + "/Library"] case .documentDirectory: return [bundlePath + "/Documents"] default: break } } return [""] } enum LevelDBError: Error { case initError case accessError case writingError case otherError } public actor LevelDB { public var parentPath = "" var name = "Database" var dictionaryEncoder: (String, [String : Any]) -> Data? var dictionaryDecoder: (String, Data) -> [String : Any]? var encoder: (String, Data) -> Data? var decoder: (String, Data) -> Data? public var db: UnsafeMutableRawPointer? public func setParentPath(_ parentPath: String) { self.parentPath = parentPath } public var dbPath: String { return parentPath + "/" + name } public func setEncoder(_ encoder: @escaping (String, Data) -> Data?) { self.encoder = encoder } public func setDecoder(_ decoder: @escaping (String, Data) -> Data?) { self.decoder = decoder } public func setDictionaryEncoder(_ encoder: @escaping (String, [String : Any]) -> Data?) { self.dictionaryEncoder = encoder } public func setDictionaryDecoder(_ decoder: @escaping (String, Data) -> [String : Any]?) { self.dictionaryDecoder = decoder } // MARK: - Life cycle public init(parentPath: String, name: String) { //NSLog("LevelDB init") self.parentPath = parentPath self.name = name //NSLog("LevelDB self.name: \(name)") //NSLog("LevelDB path: \(path)") self.dictionaryEncoder = { key, value in #if DEBUG NSLog("No encoder block was set for this database [\(name)]") NSLog("Using a convenience encoder/decoder pair using NSKeyedArchiver.") #endif return key.data(using: .utf8) } //NSLog("LevelDB self.encoder") self.dictionaryDecoder = {key, data in return ["" : ""] } self.encoder = { key, value in #if DEBUG NSLog("No encoder block was set for this database [\(name)]") NSLog("Using a convenience encoder/decoder pair using NSKeyedArchiver.") #endif return key.data(using: .utf8) } //NSLog("LevelDB self.encoder") self.decoder = {key, data in return Data() } //NSLog("LevelDB self.decoder") #if os(Linux) do { let dirpath = NSURL(fileURLWithPath:dbPath).deletingLastPathComponent?.path ?? "" //NSLog("LevelDB dirpath: \(dirpath)") let fileManager = FileManager.default if !fileManager.fileExists(atPath: dirpath) { try fileManager.createDirectory(atPath: dirpath, withIntermediateDirectories:false, attributes:nil) } //NSLog("try FileManager.default") } catch { NSLog("Problem creating parent directory: \(error)") } #endif self.open() setupCoders() } public convenience init(name: String) { self.init(parentPath: LevelDB.getLibraryPath(), name: name) } deinit { self.close() } func setupCoders() { if self.db == nil { //restore() //self.open() logger.log("db == nil") } else { backupIfNeeded() } self.encoder = {(key: String, value: Data) -> Data? in let data = value return data } self.decoder = {(key: String, data: Data) -> Data? in return data } } // MARK: - Class methods public static func getLibraryPath() -> String { #if os(Linux) let paths = SearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true) return paths[0] #elseif os(macOS) let libraryDirectory = URL(fileURLWithPath: #file.replacingOccurrences(of: "Sources/SwiftLevelDB/LevelDB.swift", with: "Library")) return libraryDirectory.absoluteString.replacingOccurrences(of: "file:///", with: "/") #else var libraryDirectory = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!.absoluteString.replacingOccurrences(of: "file:///", with: "/") libraryDirectory.removeLast() return libraryDirectory #endif } // MARK: - Accessors public func description() -> String { return "<LevelDB:\(self) dbPath: \(dbPath)>" } public func setValue<T: Codable>(_ value: T, forKey key: String) throws { try self.saveValue(value, forKey: key) } public func save<T: Codable>(array: [(String, T)]) throws { let toBeSavedArray = array.sorted { $0.0 < $1.0 } for item in toBeSavedArray { try saveValue(item.1, forKey: item.0) } } public func addEntriesFromDictionary<T: Codable>(_ dictionary: [String : T]) throws { for (key, value) in dictionary { try self.setValue(value, forKey: key) } } public func value<T: Codable>(forKey key: String) -> T? { var result: T? guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return result } var rawData: UnsafeMutableRawPointer? = nil var rawDataLength: Int = 0 let status = levelDBItemGet(db, key.cString, key.count, &rawData, &rawDataLength) if status != 0 { return result } if let rawData = rawData { let data = Data(bytes: rawData, count: rawDataLength) if let decodedData = decoder(key, data) { result = try? JSONDecoder().decode(T.self, from: decodedData) } } return result } public func values<T: Codable>(forKeys keys: [String]) -> [T?] { var result = [T?]() for key in keys { result.append(self.value(forKey: key)) } return result } public func valueExistsForKey(_ key: String) -> Bool { var result = false guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return result } var rawData: UnsafeMutableRawPointer? = nil var rawDataLength: Int = 0 let status = levelDBItemGet(db, key.cString, key.count, &rawData, &rawDataLength) if status == 0 { free(rawData) result = true } return result } public func removeValue(forKey key: String) { guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return } let status = levelDBItemDelete(db, key.cString, key.count) if status != 0 { NSLog("Problem removing value with key: \(key) in database") } } public func removeValuesForKeys(_ keys: [String]) { for key in keys { removeValue(forKey: key) } } public func removeAllValues() { self.removeAllValuesWithPrefix("") } public func removeAllValuesWithPrefix(_ prefix: String) { guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return } let iterator = levelDBIteratorNew(db) let prefixPtr = prefix.cString let prefixLen = prefix.count if prefixLen > 0 { levelDBIteratorSeek(iterator, prefix.cString, prefixLen) } else { levelDBIteratorMoveToFirst(iterator) } while levelDBIteratorIsValid(iterator) { var iKey: UnsafeMutablePointer<Int8>? = nil var iKeyLength: Int = 0 levelDBIteratorGetKey(iterator, &iKey, &iKeyLength) if let iKey = iKey { if prefixLen > 0 { if memcmp(iKey, prefixPtr, min(prefixLen, iKeyLength)) != 0 { break; } } } levelDBItemDelete(db, iKey, iKeyLength) levelDBIteratorMoveForward(iterator) } levelDBIteratorDelete(iterator) } public func allKeys() -> [String] { var keys = [String]() self.enumerateKeys() { key, stop in keys.append(key) } return keys } // MARK: - Enumeration public func enumerateKeys(backward: Bool, startingAtKey key: String?, andPrefix prefix: String?, callback: LevelDBKeyCallback) { self.enumerateKeysWith(predicate: nil, backward: backward, startingAtKey: key, andPrefix: prefix, callback: callback) } public func enumerateKeys(callback: LevelDBKeyCallback) { self.enumerateKeysWith(predicate: nil, backward: false, startingAtKey: nil, andPrefix: nil, callback: callback) } public func enumerateKeysWith(predicate: NSPredicate?, backward: Bool, startingAtKey key: String?, andPrefix prefix: String?, callback: LevelDBKeyCallback) { guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return } let iterator = levelDBIteratorNew(db) var stop = false guard let iteratorPointer = iterator else { NSLog("iterator is nil") return } _startIterator(iteratorPointer, backward: backward, prefix: prefix, start: key) while levelDBIteratorIsValid(iterator) { var iKey: UnsafeMutablePointer<Int8>? = nil var iKeyLength: Int = 0 levelDBIteratorGetKey(iterator, &iKey, &iKeyLength) if let iKey = iKey { if let prefix = prefix { if memcmp(iKey, prefix.cString, min(prefix.count, iKeyLength)) != 0 { break } } if let iKeyString = String(data: Data(bytes: iKey, count: iKeyLength), encoding: .utf8) { if predicate != nil { var iData: UnsafeMutableRawPointer? = nil var iDataLength: Int = 0 levelDBIteratorGetValue(iterator, &iData, &iDataLength) if let iData = iData { let v = decoder(iKeyString, Data(bytes: iData, count: iDataLength)) if predicate!.evaluate(with: v) { callback(iKeyString, &stop) } } } else { callback(iKeyString, &stop) } } else { NSLog("Couldn't get iKeyString") } } if stop { break } backward ? levelDBIteratorMoveBackward(iterator) : levelDBIteratorMoveForward(iterator) } levelDBIteratorDelete(iterator) } public func enumerateKeysAndDictionaries(backward: Bool, startingAtKey key: String?, andPrefix prefix: String?, callback: (String, [String : Any], UnsafeMutablePointer<Bool>) -> Void) { enumerateKeysAndDictionariesWith(predicate: nil, backward: backward, startingAtKey: key, andPrefix: prefix, callback: callback) } public func enumerateKeysAndValues<T:Codable>(backward: Bool, startingAtKey key: String? = nil, andPrefix prefix: String?, callback: (String, T, UnsafeMutablePointer<Bool>) -> Void) { enumerateKeysAndValuesWith(predicate: nil, backward: backward, startingAtKey: key, andPrefix: prefix, callback: callback) } public func enumerateKeysAndDictionaries(callback: (String, [String : Any], UnsafeMutablePointer<Bool>) -> Void) { enumerateKeysAndDictionariesWith(predicate: nil, backward: false, startingAtKey: nil, andPrefix: nil, callback: callback) } public func enumerateKeysAndValues<T:Codable>(callback: (String, T, UnsafeMutablePointer<Bool>) -> Void) { enumerateKeysAndValuesWith(predicate: nil, backward: false, startingAtKey: nil, andPrefix: nil, callback: callback) } public func enumerateKeysAndDictionariesWith(predicate: NSPredicate?, backward: Bool, startingAtKey key: String?, andPrefix prefix: String?, callback: (String, [String : Any], UnsafeMutablePointer<Bool>) -> Void) { guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return } let iterator = levelDBIteratorNew(db) var stop = false guard let iteratorPointer = iterator else { NSLog("iterator is nil") return } _startIterator(iteratorPointer, backward: backward, prefix: prefix, start: key) while levelDBIteratorIsValid(iterator) { var iKey: UnsafeMutablePointer<Int8>? = nil var iKeyLength: Int = 0 levelDBIteratorGetKey(iterator, &iKey, &iKeyLength); if let iKey = iKey { if let prefix = prefix { if memcmp(iKey, prefix.cString, min(prefix.count, iKeyLength)) != 0 { break } } if let iKeyString = String(data: Data(bytes: iKey, count: iKeyLength), encoding: .utf8) { var iData: UnsafeMutableRawPointer? = nil var iDataLength: Int = 0 levelDBIteratorGetValue(iterator, &iData, &iDataLength) if let iData = iData, let v = dictionaryDecoder(iKeyString, Data(bytes: iData, count: iDataLength)) { if predicate != nil { if predicate!.evaluate(with: v) { callback(iKeyString, v, &stop) } } else { callback(iKeyString, v, &stop) } } } else { NSLog("Couldn't get iKeyString") } } if (stop) { break; } backward ? levelDBIteratorMoveBackward(iterator) : levelDBIteratorMoveForward(iterator) } levelDBIteratorDelete(iterator) } public func enumerateKeysAndValuesWith<T:Codable>(predicate: NSPredicate?, backward: Bool, startingAtKey key: String?, andPrefix prefix: String?, callback: (String, T, UnsafeMutablePointer<Bool>) -> Void) { guard let db = db else { NSLog("Database reference is not existent (it has probably been closed)") return } let iterator = levelDBIteratorNew(db) var stop = false guard let iteratorPointer = iterator else { NSLog("iterator is nil") return } _startIterator(iteratorPointer, backward: backward, prefix: prefix, start: key) while levelDBIteratorIsValid(iterator) { var iKey: UnsafeMutablePointer<Int8>? = nil var iKeyLength: Int = 0 levelDBIteratorGetKey(iterator, &iKey, &iKeyLength); if let iKey = iKey { if let prefix = prefix { if memcmp(iKey, prefix.cString, min(prefix.count, iKeyLength)) != 0 { break } } let keyData = Data(bytes: iKey, count: iKeyLength) let iKeyString = keyData.simpleDescription //String(decoding: self, as: UTF8.self) //if let iKeyString = String(data: Data(bytes: iKey, count: iKeyLength), encoding: .utf8) { var iData: UnsafeMutableRawPointer? = nil var iDataLength: Int = 0 levelDBIteratorGetValue(iterator, &iData, &iDataLength) if let iData = iData, let data = decoder(iKeyString, Data(bytes: iData, count: iDataLength)), let v = try? JSONDecoder().decode(T.self, from: data) { if predicate != nil { if predicate!.evaluate(with: v) { callback(iKeyString, v, &stop) } } else { callback(iKeyString, v, &stop) } } /*} else { NSLog("Couldn't get iKeyString") }*/ } if (stop) { break; } backward ? levelDBIteratorMoveBackward(iterator) : levelDBIteratorMoveForward(iterator) } levelDBIteratorDelete(iterator) } // MARK: - Helper methods func saveValue<T: Codable>(_ value: T, forKey key: String) throws { guard let db = self.db else { NSLog("Database reference is not existent (it has probably been closed)") return } let newData = try JSONEncoder().encode(value) var status = 0 if let data = self.encoder(key, newData) { var localData = data localData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> () in status = levelDBItemPut(db, key.cString, key.count, mutableBytes, data.count) } if status != 0 { NSLog("setValue: Problem storing key/value pair in database, status: \(status), key: \(key), value: \(value)") throw LevelDBError.writingError } } } public func backupIfNeeded() { let dbBackupPath = dbPath + String(Date().dayOfWeek) let fileManager = FileManager.default let dbTempPath = dbBackupPath + ".temp" //logger.log("dbPath: \(dbPath)") try? fileManager.copyItem(atPath: self.dbPath, toPath: dbTempPath) try? fileManager.removeItem(atPath: dbBackupPath) try? fileManager.moveItem(atPath: dbTempPath, toPath: dbBackupPath) } public func deleteDatabaseFromDisk() throws { self.close() let fileManager = FileManager.default try fileManager.removeItem(atPath: dbPath) } public func open() { self.db = levelDBOpen(dbPath.cString) } public func close() { if let db = db { levelDBDelete(db) self.db = nil } } public func closed() -> Bool { return db == nil } // MARK: - Private functions fileprivate func _startIterator(_ iterator: UnsafeMutableRawPointer, backward: Bool, prefix: String?, start key: String?) { var startingKey: String if let prefix = prefix { startingKey = prefix if let key = key { if key.hasPrefix(prefix) { startingKey = key } } let len = startingKey.count // If a prefix is provided and the iteration is backwards // we need to start on the next key (maybe discarding the first iteration) if backward { var i: Int = len - 1 let startingKeyPtr = malloc(len)!.bindMemory(to: Int8.self, capacity: len) memcpy(startingKeyPtr, startingKey.cString, len) var keyChar = startingKeyPtr while true { if i < 0 { levelDBIteratorMoveToLast(iterator) break } keyChar += i if keyChar[0] < 127 { keyChar[0] += 1 levelDBIteratorSeek(iterator, startingKeyPtr, len) if !levelDBIteratorIsValid(iterator) { levelDBIteratorMoveToLast(iterator) } break } i -= 1 } free(startingKeyPtr) if !levelDBIteratorIsValid(iterator) { return } var iKey: UnsafeMutablePointer<Int8>? = nil var iKeyLength: Int = 0 levelDBIteratorGetKey(iterator, &iKey, &iKeyLength) if len > 0, let iKey = iKey { let cmp = memcmp(iKey, startingKey.cString, len) if cmp > 0 { levelDBIteratorMoveBackward(iterator) } } } else { // Otherwise, we start at the provided prefix levelDBIteratorSeek(iterator, startingKey.cString, len) if !levelDBIteratorIsValid(iterator) { levelDBIteratorMoveToFirst(iterator) } } } else if let key = key { levelDBIteratorSeek(iterator, key.cString, key.count) } else if backward { levelDBIteratorMoveToLast(iterator) } else { levelDBIteratorMoveToFirst(iterator) } } }
40ffb321d11f19af8e4edbe92e22bb1b
36.942808
218
0.552323
false
false
false
false
VanHack/binners-project-ios
refs/heads/develop
ios-binners-project/BPClockViewController.swift
mit
1
// // BPClockViewController.swift // ios-binners-project // // Created by Matheus Ruschel on 3/1/16. // Copyright © 2016 Rodrigo de Souza Reis. All rights reserved. import UIKit enum TimeMode { case hours case minutes } enum TimePeriod { case am case pm } class BPClockViewController: CloseButtonViewController { @IBOutlet weak var labelAmPm: UILabel! @IBOutlet weak var labelTwoDots: UILabel! @IBOutlet weak var minutesButton: UIButton! @IBOutlet weak var hoursButton: UIButton! @IBOutlet weak var pmButton: UIButton! @IBOutlet weak var amButton: UIButton! @IBOutlet weak var clockView: BEMAnalogClockView! var viewInitialized = false var isPresenting = false @IBOutlet weak var labelDescription: UILabel! var timeMode: TimeMode = .hours var hours: Int = 0 var minutes: Int = 0 var pickup: BPPickup? var timePeriod: TimePeriod = .am override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.binnersGrayBackgroundColor() self.labelDescription.sizeToFit() self.labelDescription.adjustsFontSizeToFitWidth = true setupNavigationBar() configureClock() configureButtonsAndLabels() hideCloseButton = !isPresenting } func checkIfNowIsPMorAM() { let hour = Date().getHour() if hour < 12 { aMButtonClicked() } else { pMButtonClicked() } } override func viewDidLayoutSubviews() { if !viewInitialized { checkIfNowIsPMorAM() viewInitialized = true } } func setupNavigationBar() { let buttonRight = UIBarButtonItem( title: "Next", style: .done, target: self, action: #selector(BPClockViewController.checkmarkButtonClicked)) buttonRight.setTitleTextAttributes( [NSFontAttributeName:UIFont.binnersFontWithSize(16)!], for: UIControlState()) buttonRight.tintColor = UIColor.white self.navigationItem.rightBarButtonItem = buttonRight self.title = "Time" } func checkmarkButtonClicked() { var hours = Int(self.hoursButton.titleLabel!.text!)! let minutes = Int(self.minutesButton.titleLabel!.text!)! if timePeriod == .pm { hours += 12 } let pickupDate = self.pickup?.date.changeHour(hours - 3).changeMinute(minutes) if(pickupDate!.compare(Date()) == .orderedAscending) { // hour on clock is earlier than hour now BPMessageFactory.makeMessage( .alert, message: "You have to schedule the pickup for at least X hours before it happens").show() } else { self.pickup?.date = self.pickup?.date.changeHour(hours) self.pickup?.date = self.pickup?.date.changeMinute(minutes) self.performSegue(withIdentifier: "quantitySegue", sender: self) } } func configureClock() { clockView.delegate = self clockView.enableDigit = true clockView.secondHandAlpha = 0.0 clockView.currentTime = true clockView.setTimeViaTouch = true clockView.faceBackgroundColor = UIColor.binnersGreenColor() if timeMode == .hours { clockView.minuteHandAlpha = 0.0 } else { clockView.hourHandAlpha = 0.0 } } func aMButtonClicked() { timePeriod = .am amButton.layer.masksToBounds = true amButton.layer.cornerRadius = amButton.layer.bounds.height / 2.0 amButton.backgroundColor = UIColor.binnersGreenColor() amButton.tintColor = UIColor.white pmButton.backgroundColor = UIColor.clear pmButton.tintColor = UIColor.binnersGreenColor() labelAmPm.text = "am" } func pMButtonClicked() { timePeriod = .pm pmButton.layer.masksToBounds = true pmButton.layer.cornerRadius = amButton.layer.bounds.height / 2.0 pmButton.backgroundColor = UIColor.binnersGreenColor() pmButton.tintColor = UIColor.white amButton.backgroundColor = UIColor.clear amButton.tintColor = UIColor.binnersGreenColor() labelAmPm.text = "pm" } func configureButtonsAndLabels() { minutesButton.tintColor = UIColor.binnersGreenColor() hoursButton.tintColor = UIColor.binnersGreenColor() labelTwoDots.textColor = UIColor.binnersGreenColor() amButton.tintColor = UIColor.binnersGreenColor() pmButton.tintColor = UIColor.binnersGreenColor() minutesButton.titleLabel?.font = UIFont.systemFont(ofSize: 50) hoursButton.titleLabel?.font = UIFont.systemFont(ofSize: 50) labelTwoDots.font = UIFont.systemFont(ofSize: 50) if timeMode == .hours { minutesButton.alpha = 0.5 } else { hoursButton.alpha = 0.5 } amButton.addTarget( self, action: #selector(BPClockViewController.aMButtonClicked), for: .touchUpInside) pmButton.addTarget( self, action: #selector(BPClockViewController.pMButtonClicked), for: .touchUpInside) minutesButton.addTarget( self, action: #selector(BPClockViewController.minuteButtonClicked), for: .touchUpInside) hoursButton.addTarget( self, action: #selector(BPClockViewController.hourButtonClicked), for: .touchUpInside) labelAmPm.textColor = UIColor.binnersGreenColor() labelAmPm.alpha = 0.5 self.view.bringSubview(toFront: amButton) self.view.bringSubview(toFront: pmButton) } func minuteButtonClicked() { minutesButton.alpha = 1.0 hoursButton.alpha = 0.5 clockView.hourHandAlpha = 0.0 clockView.minuteHandAlpha = 1.0 clockView.hourOrMinuteSelected = 1 timeMode = .minutes clockView.reloadClock() } func hourButtonClicked() { hoursButton.alpha = 1.0 minutesButton.alpha = 0.5 clockView.minuteHandAlpha = 0.0 clockView.hourHandAlpha = 1.0 clockView.hourOrMinuteSelected = 0 timeMode = .hours clockView.reloadClock() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "quantitySegue" { guard let destVc = segue.destination as? BPQuantityViewController else { fatalError("Could not convert view controller") } destVc.pickup = pickup } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension BPClockViewController :BEMAnalogClockDelegate { func currentTime(onClock clock: BEMAnalogClockView!, hours: String ,minutes: String , seconds: String ) { if timeMode == .hours { if clock.hours < 10 { hoursButton.setTitle("0\(hours)", for: UIControlState()) } else { hoursButton.setTitle("\(hours)", for: UIControlState()) } } else { if clock.minutes < 10 { minutesButton.setTitle("0\(minutes)", for: UIControlState()) } else { minutesButton.setTitle("\(minutes)", for: UIControlState()) } } self.hours = clock.hours self.minutes = clock.minutes } func clockDidFinishLoading(_ clock: BEMAnalogClockView!) { if clock.minutes < 10 { minutesButton.setTitle("0\(clock.minutes)", for: UIControlState()) } else { minutesButton.setTitle("\(clock.minutes)", for: UIControlState()) } if clock.hours < 10 { hoursButton.setTitle("0\(clock.hours)", for: UIControlState()) } else { hoursButton.setTitle("\(clock.hours)", for: UIControlState()) } self.hours = clock.hours self.minutes = clock.minutes clockView.currentTime = false } }
b192c9042e64ad95bcbcdfe9334fa4a6
27.914191
109
0.578815
false
false
false
false
markspanbroek/Shhwift
refs/heads/master
Demo/Pods/Mockingjay/Mockingjay/Matchers.swift
mit
2
// // Matchers.swift // Mockingjay // // Created by Kyle Fuller on 28/02/2015. // Copyright (c) 2015 Cocode. All rights reserved. // import Foundation import URITemplate // Collection of generic matchers /// Mockingjay matcher which returns true for every request public func everything(request:NSURLRequest) -> Bool { return true } /// Mockingjay matcher which matches URIs public func uri(uri:String) -> (request:NSURLRequest) -> Bool { return { (request:NSURLRequest) in let template = URITemplate(template:uri) if let URLString = request.URL?.absoluteString { if template.extract(URLString) != nil { return true } } if let path = request.URL?.path { if template.extract(path) != nil { return true } } return false } } public enum HTTPMethod : CustomStringConvertible { case GET case POST case PATCH case PUT case DELETE case OPTIONS case HEAD public var description : String { switch self { case .GET: return "GET" case .POST: return "POST" case .PATCH: return "PATCH" case .PUT: return "PUT" case .DELETE: return "DELETE" case .OPTIONS: return "OPTIONS" case .HEAD: return "HEAD" } } } public func http(method:HTTPMethod, uri:String) -> (request:NSURLRequest) -> Bool { return { (request:NSURLRequest) in if let requestMethod = request.HTTPMethod { if requestMethod == method.description { return Mockingjay.uri(uri)(request: request) } } return false } }
cbdc0571adbf8afa7e833b43196f1351
18.9625
83
0.632206
false
false
false
false
darina/omim
refs/heads/master
iphone/Chart/Chart/Views/ChartInfo/ChartMyPositionView.swift
apache-2.0
5
import UIKit class ChartMyPositionView: UIView { override class var layerClass: AnyClass { CAShapeLayer.self } var shapeLayer: CAShapeLayer { layer as! CAShapeLayer } var pinY: CGFloat = 0 { didSet { updatePin() } } fileprivate let pinView = MyPositionPinView(frame: CGRect(x: 0, y: 0, width: 12, height: 16)) override init(frame: CGRect) { super.init(frame: frame) shapeLayer.lineDashPattern = [3, 2] shapeLayer.lineWidth = 2 shapeLayer.strokeColor = UIColor(red: 0.142, green: 0.614, blue: 0.95, alpha: 0.3).cgColor addSubview(pinView) transform = CGAffineTransform.identity.scaledBy(x: 1, y: -1) pinView.transform = CGAffineTransform.identity.scaledBy(x: 1, y: -1) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let path = UIBezierPath() path.move(to: CGPoint(x: bounds.width / 2, y: 0)) path.addLine(to: CGPoint(x: bounds.width / 2, y: bounds.height)) shapeLayer.path = path.cgPath updatePin() } private func updatePin() { pinView.center = CGPoint(x: bounds.midX, y: pinY + pinView.bounds.height / 2) } } fileprivate class MyPositionPinView: UIView { override class var layerClass: AnyClass { CAShapeLayer.self } var shapeLayer: CAShapeLayer { layer as! CAShapeLayer } var path: UIBezierPath = { let p = UIBezierPath() p.addArc(withCenter: CGPoint(x: 6, y: 6), radius: 6, startAngle: -CGFloat.pi / 2, endAngle: atan(3.5 / 4.8733971724), clockwise: true) p.addLine(to: CGPoint(x: 6 + 0.75, y: 15.6614378)) p.addArc(withCenter: CGPoint(x: 6, y: 15), radius: 1, startAngle: atan(0.6614378 / 0.75), endAngle: CGFloat.pi - atan(0.6614378 / 0.75), clockwise: true) p.addLine(to: CGPoint(x: 6 - 4.8733971724, y: 9.5)) p.addArc(withCenter: CGPoint(x: 6, y: 6), radius: 6, startAngle: CGFloat.pi - atan(3.5 / 4.8733971724), endAngle: -CGFloat.pi / 2, clockwise: true) p.close() p.append(UIBezierPath(ovalIn: CGRect(x: 3, y: 3, width: 6, height: 6))) return p }() override init(frame: CGRect) { super.init(frame: frame) shapeLayer.lineWidth = 0 shapeLayer.fillColor = UIColor(red: 0.142, green: 0.614, blue: 0.95, alpha: 0.5).cgColor shapeLayer.fillRule = .evenOdd } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let sx = bounds.width / path.bounds.width let sy = bounds.height / path.bounds.height let p = path.copy() as! UIBezierPath p.apply(CGAffineTransform(scaleX: sx, y: sy)) shapeLayer.path = p.cgPath } }
511df73142dcf7e5ee263514a619521e
29.617021
95
0.631341
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Gallery/Photos/PhotosOverlayView.swift
apache-2.0
5
final class PhotosOverlayView: UIView { private var navigationBar: UINavigationBar! private var navigationItem: UINavigationItem! weak var photosViewController: PhotosViewController? var photo: HotelPhotoUrl? { didSet { guard let photo = photo else { navigationItem.title = nil return } guard let photosViewController = photosViewController else { return } if let index = photosViewController.photos.firstIndex(where: { $0 === photo }) { navigationItem.title = "\(index + 1) / \(photosViewController.photos.count)" } } } override init(frame: CGRect) { super.init(frame: frame) setupNavigationBar() } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc private func closeButtonTapped(_: UIBarButtonItem) { photosViewController?.dismiss(animated: true, completion: nil) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let hitView = super.hitTest(point, with: event), hitView != self { return hitView } return nil } private func setupNavigationBar() { navigationBar = UINavigationBar() navigationBar.translatesAutoresizingMaskIntoConstraints = false navigationBar.backgroundColor = UIColor.clear navigationBar.barTintColor = nil navigationBar.isTranslucent = true navigationBar.setBackgroundImage(UIImage(), for: .default) navigationItem = UINavigationItem(title: "") navigationBar.items = [navigationItem] addSubview(navigationBar) navigationBar.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor).isActive = true navigationBar.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true navigationBar.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_nav_bar_back"), style: .plain, target: self, action: #selector(closeButtonTapped(_:))) } func setHidden(_ hidden: Bool, animated: Bool, animation: @escaping (() -> Void)) { guard isHidden != hidden else { return } guard animated else { isHidden = hidden animation() return } isHidden = false alpha = hidden ? 1.0 : 0.0 UIView.animate(withDuration: kDefaultAnimationDuration, delay: 0.0, options: [.allowAnimatedContent, .allowUserInteraction], animations: { [weak self] in self?.alpha = hidden ? 0.0 : 1.0 animation() }, completion: { [weak self] _ in self?.alpha = 1.0 self?.isHidden = hidden }) } }
a5b581bd7076f0c1566f4cb3920acfc8
32.865854
180
0.657544
false
false
false
false
justindarc/firefox-ios
refs/heads/master
Client/Frontend/Library/DownloadsPanel.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 Storage private struct DownloadsPanelUX { static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemWidth = 170 } struct DownloadedFile: Equatable { let path: URL let size: UInt64 let lastModified: Date var canShowInWebView: Bool { return MIMEType.canShowInWebView(mimeType) } var filename: String { return path.lastPathComponent } var fileExtension: String { return path.pathExtension } var formattedSize: String { return ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file) } var mimeType: String { return MIMEType.mimeTypeFromFileExtension(fileExtension) } static public func ==(lhs: DownloadedFile, rhs: DownloadedFile) -> Bool { return lhs.path == rhs.path } } class DownloadsPanel: UIViewController, UITableViewDelegate, UITableViewDataSource, LibraryPanel, UIDocumentInteractionControllerDelegate { weak var libraryPanelDelegate: LibraryPanelDelegate? let profile: Profile var tableView = UITableView() private let events: [Notification.Name] = [.FileDidDownload, .PrivateDataClearedDownloadedFiles, .DynamicFontChanged] private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView() private var groupedDownloadedFiles = DateGroupedTableData<DownloadedFile>() private var fileExtensionIcons: [String: UIImage] = [:] // MARK: - Lifecycle init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadData() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) return } tableView.delegate = self tableView.dataSource = self tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: "TwoLineTableViewCell") tableView.layoutMargins = .zero tableView.keyboardDismissMode = .onDrag tableView.backgroundColor = UIColor.theme.tableView.rowBackground tableView.separatorColor = UIColor.theme.tableView.separator tableView.accessibilityIdentifier = "DownloadsTable" tableView.cellLayoutMarginsFollowReadableWidth = false // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } @objc func notificationReceived(_ notification: Notification) { DispatchQueue.main.async { self.reloadData() switch notification.name { case .FileDidDownload, .PrivateDataClearedDownloadedFiles: break case .DynamicFontChanged: if self.emptyStateOverlayView.superview != nil { self.emptyStateOverlayView.removeFromSuperview() } self.emptyStateOverlayView = self.createEmptyStateOverlayView() break default: // no need to do anything at all print("Error: Received unexpected notification \(notification.name)") break } } } func reloadData() { groupedDownloadedFiles = DateGroupedTableData<DownloadedFile>() let downloadedFiles = fetchData() for downloadedFile in downloadedFiles { groupedDownloadedFiles.add(downloadedFile, timestamp: downloadedFile.lastModified.timeIntervalSince1970) } fileExtensionIcons = [:] tableView.reloadData() updateEmptyPanelState() } private func fetchData() -> [DownloadedFile] { var downloadedFiles: [DownloadedFile] = [] do { let downloadsPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads") let files = try FileManager.default.contentsOfDirectory(at: downloadsPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants]) for file in files { let attributes = try FileManager.default.attributesOfItem(atPath: file.path) as NSDictionary let downloadedFile = DownloadedFile(path: file, size: attributes.fileSize(), lastModified: attributes.fileModificationDate() ?? Date()) downloadedFiles.append(downloadedFile) } } catch let error { print("Unable to get files in Downloads folder: \(error.localizedDescription)") return [] } return downloadedFiles.sorted(by: { a, b -> Bool in return a.lastModified > b.lastModified }) } private func deleteDownloadedFile(_ downloadedFile: DownloadedFile) -> Bool { do { try FileManager.default.removeItem(at: downloadedFile.path) return true } catch let error { print("Unable to delete downloaded file: \(error.localizedDescription)") } return false } private func shareDownloadedFile(_ downloadedFile: DownloadedFile, indexPath: IndexPath) { let helper = ShareExtensionHelper(url: downloadedFile.path, tab: nil) let controller = helper.createActivityViewController { completed, activityType in print("Shared downloaded file: \(completed)") } if let popoverPresentationController = controller.popoverPresentationController { guard let tableViewCell = tableView.cellForRow(at: indexPath) else { print("Unable to get table view cell at index path: \(indexPath)") return } popoverPresentationController.sourceView = tableViewCell popoverPresentationController.sourceRect = tableViewCell.bounds popoverPresentationController.permittedArrowDirections = .any } present(controller, animated: true, completion: nil) } private func iconForFileExtension(_ fileExtension: String) -> UIImage? { if let icon = fileExtensionIcons[fileExtension] { return icon } guard let icon = roundRectImageWithLabel(fileExtension, width: 29, height: 29) else { return nil } fileExtensionIcons[fileExtension] = icon return icon } private func roundRectImageWithLabel(_ label: String, width: CGFloat, height: CGFloat, radius: CGFloat = 5.0, strokeWidth: CGFloat = 1.0, strokeColor: UIColor = UIColor.theme.homePanel.downloadedFileIcon, fontSize: CGFloat = 9.0) -> UIImage? { UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0.0) let context = UIGraphicsGetCurrentContext() context?.setStrokeColor(strokeColor.cgColor) let rect = CGRect(x: strokeWidth / 2, y: strokeWidth / 2, width: width - strokeWidth, height: height - strokeWidth) let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: radius) bezierPath.lineWidth = strokeWidth bezierPath.stroke() let attributedString = NSAttributedString(string: label, attributes: [ .baselineOffset: -(strokeWidth * 2), .font: UIFont.systemFont(ofSize: fontSize), .foregroundColor: strokeColor ]) let stringHeight: CGFloat = fontSize * 2 let stringWidth = attributedString.boundingRect(with: CGSize(width: width, height: stringHeight), options: .usesLineFragmentOrigin, context: nil).size.width attributedString.draw(at: CGPoint(x: (width - stringWidth) / 2 + strokeWidth, y: (height - stringHeight) / 2 + strokeWidth)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // MARK: - Empty State private func updateEmptyPanelState() { if groupedDownloadedFiles.isEmpty { if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) view.bringSubviewToFront(emptyStateOverlayView) emptyStateOverlayView.snp.makeConstraints { make in make.edges.equalTo(self.tableView) } } } else { emptyStateOverlayView.removeFromSuperview() } } fileprivate func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() overlayView.backgroundColor = UIColor.theme.homePanel.panelBackground let logoImageView = UIImageView(image: UIImage.templateImageNamed("emptyDownloads")) logoImageView.tintColor = UIColor.Photon.Grey60 overlayView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.size.equalTo(60) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(LibraryPanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) } let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.DownloadsPanelEmptyStateTitle welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = UIColor.theme.homePanel.welcomeScreenText welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.top.equalTo(logoImageView.snp.bottom).offset(DownloadsPanelUX.WelcomeScreenPadding) make.width.equalTo(DownloadsPanelUX.WelcomeScreenItemWidth) } return overlayView } fileprivate func downloadedFileForIndexPath(_ indexPath: IndexPath) -> DownloadedFile? { let downloadedFilesInSection = groupedDownloadedFiles.itemsForSection(indexPath.section) return downloadedFilesInSection[safe: indexPath.row] } // MARK: - TableView Delegate / DataSource func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TwoLineTableViewCell", for: indexPath) as! TwoLineTableViewCell return configureDownloadedFile(cell, for: indexPath) } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel?.textColor = UIColor.theme.tableView.headerTextDark header.contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard groupedDownloadedFiles.numberOfItemsForSection(section) > 0 else { return nil } switch section { case 0: return Strings.TableDateSectionTitleToday case 1: return Strings.TableDateSectionTitleYesterday case 2: return Strings.TableDateSectionTitleLastWeek case 3: return Strings.TableDateSectionTitleLastMonth default: assertionFailure("Invalid Downloads section \(section)") } return nil } func configureDownloadedFile(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let downloadedFile = downloadedFileForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(downloadedFile.filename, detailText: downloadedFile.formattedSize) cell.imageView?.image = iconForFileExtension(downloadedFile.fileExtension) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let downloadedFile = downloadedFileForIndexPath(indexPath) { UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .download, value: .downloadsPanel) if downloadedFile.mimeType == MIMEType.Calendar { let dc = UIDocumentInteractionController(url: downloadedFile.path) dc.delegate = self dc.presentPreview(animated: true) return } guard downloadedFile.canShowInWebView else { shareDownloadedFile(downloadedFile, indexPath: indexPath) return } libraryPanelDelegate?.libraryPanel(didSelectURL: downloadedFile.path, visitType: VisitType.typed) } } func numberOfSections(in tableView: UITableView) -> Int { return 4 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupedDownloadedFiles.numberOfItemsForSection(section) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteTitle = NSLocalizedString("Delete", tableName: "DownloadsPanel", comment: "Action button for deleting downloaded files in the Downloads panel.") let shareTitle = NSLocalizedString("Share", tableName: "DownloadsPanel", comment: "Action button for sharing downloaded files in the Downloads panel.") let delete = UITableViewRowAction(style: .destructive, title: deleteTitle, handler: { (action, indexPath) in if let downloadedFile = self.downloadedFileForIndexPath(indexPath) { if self.deleteDownloadedFile(downloadedFile) { self.tableView.beginUpdates() self.groupedDownloadedFiles.remove(downloadedFile) self.tableView.deleteRows(at: [indexPath], with: .right) self.tableView.endUpdates() self.updateEmptyPanelState() UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .download, value: .downloadsPanel) } } }) let share = UITableViewRowAction(style: .normal, title: shareTitle, handler: { (action, indexPath) in if let downloadedFile = self.downloadedFileForIndexPath(indexPath) { self.shareDownloadedFile(downloadedFile, indexPath: indexPath) UnifiedTelemetry.recordEvent(category: .action, method: .share, object: .download, value: .downloadsPanel) } }) share.backgroundColor = view.tintColor return [delete, share] } // MARK: - UIDocumentInteractionControllerDelegate func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return self } } extension DownloadsPanel: Themeable { func applyTheme() { emptyStateOverlayView.removeFromSuperview() emptyStateOverlayView = createEmptyStateOverlayView() updateEmptyPanelState() tableView.reloadData() } }
9c962c67ed978cf7aba17b1c0c24a42f
40.555838
247
0.674281
false
false
false
false
fitpay/fitpay-ios-sdk
refs/heads/develop
FitpaySDK/Rtm/Models/ErrorResponse.swift
mit
1
import Foundation /// Error model for Session, Client and Web errors @objc public class ErrorResponse: NSError, Serializable { /// HTTP Status Code public let status: Int? /// Created Timestamp when run public let created: TimeInterval? @objc public let requestId: String? /// URL relative path @objc public let path: String? /// Short summary of error. ie: \"Not Found\" @objc public let summary: String? /// Longer summary of error @objc public let messageDescription: String? /// Specific issue // Parsed from different locations in the object @objc public let message: String? /// Specific issue // Parsed from different locations in the object @objc public let details: String? enum CodingKeys: String, CodingKey { case status case created case requestId case path case summary case messageDescription = "description" case details case message } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) status = try? container.decode(.status) created = try container.decode(.created, transformer: NSTimeIntervalTypeTransform()) requestId = try? container.decode(.requestId) path = try? container.decode(.path) summary = try? container.decode(.summary) messageDescription = try? container.decode(.messageDescription) if let detailsString: String = try? container.decode(.details), let data = detailsString.data(using: .utf8) { if let dict: [String: Any] = (try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]])?.first { details = dict["message"] as? String } else { details = detailsString } } else { details = nil } if let messageString: String = try? container.decode(.message), let data = messageString.data(using: .utf8) { if let dict: [String: Any] = (try? JSONSerialization.jsonObject(with: data, options: []) as! [[String: Any]])?.first { message = dict["message"] as? String } else { message = messageString } } else { message = nil } super.init(domain: "", code: status ?? 0, userInfo: [NSLocalizedDescriptionKey: messageDescription ?? ""]) logError() } init(domain: AnyClass, errorCode: Int?, errorMessage: String?) { status = errorCode created = nil requestId = nil path = nil summary = nil messageDescription = errorMessage details = nil message = nil super.init(domain: "\(domain)", code: status ?? 0, userInfo: [NSLocalizedDescriptionKey: errorMessage ?? ""]) logError() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Static Methods class func unhandledError(domain: AnyClass) -> ErrorResponse { return ErrorResponse(domain: domain, errorCode: 0, errorMessage: "Unhandled error") } class func clientUrlError(domain: AnyClass, client: RestClient?, url: String?, resource: String) -> ErrorResponse? { if client == nil { return ErrorResponse(domain: domain, errorCode: 0, errorMessage: "\(RestClient.self) is not set.") } if url == nil { return ErrorResponse(domain: domain, errorCode: 0, errorMessage: "Failed to retrieve url for resource '\(resource)'") } return nil } // MARK: - Private private func logError() { let status = "\(self.status ?? 0)" let messageDescription = "\(self.messageDescription ?? "")" log.error("ERROR_RESPONSE: Status: \(status) Message: \(messageDescription).") } }
e873aaee678013cfc6d50d64fc2dbba0
32.583333
130
0.599256
false
false
false
false
HotCatLX/SwiftStudy
refs/heads/master
02-FontChange/FontChange/ViewController.swift
mit
1
// // ViewController.swift // Fonts // // Created by suckerl on 2017/5/10. // Copyright © 2017年 suckerl. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { static let cellID = "cell" //字体名字 let fontNames = ["Copperplate-Bold", "Copperplate","Copperplate-Light"] var fontIndex = 0 var data = [ "《生活不止眼前的苟且》", "妈妈坐在门前,哼着花儿与少年", "虽已时隔多年,记得她泪水涟涟", "那些幽暗的时光,那些坚持与慌张", "在临别的门前,妈妈望着我说", "生活不止眼前的苟且,还有诗和远方的田野", "你赤手空拳来到人世间", "为找到那片海不顾一切", " --- 许巍"] fileprivate lazy var topView : UIView = { let topView = UIView() topView.backgroundColor = UIColor.black return topView }() fileprivate lazy var topLabel : UILabel = { let topLabel = UILabel() topLabel.text = "Custom Font" topLabel.textColor = UIColor.white topLabel.textAlignment = NSTextAlignment.center return topLabel }() fileprivate lazy var middleTabView : UITableView = { let middleTabView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain) middleTabView.dataSource = self as UITableViewDataSource middleTabView.delegate = self as UITableViewDelegate middleTabView.showsVerticalScrollIndicator = false middleTabView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: ViewController.cellID) return middleTabView }() fileprivate lazy var bottomView : UIView = { let bottomView = UIView() bottomView.backgroundColor = UIColor.black return bottomView }() fileprivate lazy var bottomButton : UIButton = { let bottomButton = UIButton() bottomButton.setTitle("Custom Font", for: UIControlState.normal) bottomButton.setTitleColor(UIColor.darkGray, for: UIControlState.normal) bottomButton.backgroundColor = UIColor.yellow bottomButton.addTarget(self, action: #selector(ViewController.bottomClick), for: UIControlEvents.touchUpInside) return bottomButton }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(topView) view.addSubview(topLabel) view.addSubview(middleTabView) view.addSubview(bottomView) view.addSubview(bottomButton) self.constructLayout() //打印所有字体 // for fonts in UIFont.familyNames { // print(fonts) // } } } //MARK:- dataSource & delegat extension ViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier:ViewController.cellID, for: indexPath) cell.selectionStyle = .none let str = data[indexPath.row] cell.textLabel?.text = str cell.textLabel?.textAlignment = NSTextAlignment.center cell.backgroundColor = UIColor.black cell.textLabel?.textColor = UIColor.white cell.textLabel?.font = UIFont(name: self.fontNames[fontIndex], size: 15) return cell } } //MARK:- 处理点击事件 extension ViewController { func bottomClick() { if fontIndex < (fontNames.count - 1){ fontIndex += 1 }else { fontIndex = 0 } self.middleTabView.reloadData() } } //MARK:- constructLayout extension ViewController { func constructLayout() { topView.snp.makeConstraints { (make) in make.top.equalTo(self.view) make.left.equalTo(self.view) make.right.equalTo(self.view) make.height.equalTo(80) } topLabel.snp.makeConstraints { (make) in make.center.equalTo(topView) make.width.equalTo(200) make.height.equalTo(60) } bottomView.snp.makeConstraints { (make) in make.bottom.equalTo(self.view) make.left.equalTo(self.view) make.right.equalTo(self.view) make.height.equalTo(160) } bottomButton.snp.makeConstraints { (make) in make.center.equalTo(bottomView) make.width.equalTo(120) make.height.equalTo(120) } bottomButton.layer.cornerRadius = 60 middleTabView.snp.makeConstraints { (make) in make.bottom.equalTo(bottomView.snp.top) make.top.equalTo(topView.snp.bottom) make.left.equalTo(self.view) make.right.equalTo(self.view) } } }
0596efc02f4e781d1ea63cc03d7c43a4
29.830303
119
0.603499
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
GoDToolOSX/View Controllers/GoDStringViewController.swift
gpl-2.0
1
// // GoDStringViewController.swift // GoD Tool // // Created by The Steez on 24/10/2018. // import Cocoa class GoDStringViewController: GoDViewController { @IBOutlet var text: NSTextView! @IBOutlet var stringid: NSTokenField! @IBOutlet var minimumid: NSTextField! @IBOutlet var freeid: NSTextField! @IBOutlet weak var filePathLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() title = "String Search" loadAllStrings(refresh: true) } @IBAction func findFreeID(_ sender: Any) { #if GAME_PBR freeid.stringValue = "\(PBRStringManager.messageDataTable.numberOfEntries + 1)" #else guard !isSearchingForFreeStringID else { GoDAlertViewController.displayAlert(title: "Please wait", text: "Please wait for previous string id search to complete.") return } if let val = minimumid.stringValue.integerValue { if let id = freeMSGID(from: val) { freeid.stringValue = id.string + " (\(id.hexString()))" } else { freeid.stringValue = "0" } } #endif } @IBAction func getString(_ sender: Any) { if let val = stringid.stringValue.integerValue { let msgString = getStringSafelyWithID(id: val) text.string = msgString.string #if !GAME_PBR filePathLabel.stringValue = msgString.table?.path ?? "File unknown" #else if let (tableID, _) = PBRStringManager.tableIDAndIndexForStringWithID(val), let table = getStringTableWithId(tableID) { filePathLabel.stringValue = table.file.path } else { filePathLabel.stringValue = "File unknown" } #endif } } @IBAction func replaceString(_ sender: Any) { if let val = stringid.stringValue.integerValue { if val < 1 { GoDAlertViewController.displayAlert(title: "Replacement failed!", text: "Please enter a valid string id") return } if text.string.length > 0 { if !XGString(string: text.string, sid: val).replace() { GoDAlertViewController.displayAlert(title: "Replacement failed!", text: "The string could not be replaced") } } else { GoDAlertViewController.displayAlert(title: "Replacement failed!", text: "Please add some text to replace") } } else { GoDAlertViewController.displayAlert(title: "Replacement failed!", text: "Please enter a valid string id") } } }
aba97e147799fd550ec110d3a68a811c
27.4375
124
0.701538
false
false
false
false
google/android-auto-companion-ios
refs/heads/main
Sources/AndroidAutoConnectedDeviceTransport/Peripheral.swift
apache-2.0
1
// Copyright 2021 Google LLC // // 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. // MARK: - PeripheralStatus /// Status of a peripheral. public enum PeripheralStatus: Equatable { /// Starting state. case discovered /// Connection to the peripheral has commenced. case connecting /// The peripheral is connected (possibly without encryption). case connected /// The connection to the peripheral has terminated. case disconnected /// The connection to the peripheral is being terminated. case disconnecting /// Other status with the specified description. case other(String) } // MARK: - TransportPeripheral /// Homogeneous protocol for a peripheral using a specific communication transport. public protocol TransportPeripheral: AnyTransportPeripheral, Hashable { /// Conform to Identifiable, but since that requires iOS 13+, just implement. associatedtype ID: Hashable, CustomStringConvertible /// Type for the context that may be provided during discovery of a peripheral. associatedtype DiscoveryContext /// Identifier for the peripheral. var id: ID { get } /// Handler of state change events for this peripheral. var onStatusChange: ((PeripheralStatus) -> Void)? { get set } } // MARK: - AnyTransportPeripheral /// Peripheral conformance independent of transport. public protocol AnyTransportPeripheral: AnyObject { var identifierString: String { get } var displayName: String { get } var logName: String { get } var isConnected: Bool { get } /// Current status for this peripheral. var status: PeripheralStatus { get } } // MARK: - AnyTransportPeripheral Extensions /// Default `AnyTransportPeripheral` conformance. extension AnyTransportPeripheral { /// By default, the logName is just the displayName. public var logName: String { displayName } public var isConnected: Bool { status == .connected } } // MARK: - TransportPeripheral Extensions /// Default `TransportPeripheral` implementations. extension TransportPeripheral { /// By default, the value is just `id.description`. public var identifierString: String { id.description } } /// Default `Hashable` conformance implementation for a peripheral. extension TransportPeripheral { public static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } }
52e78f3a3a8aa3900c9b7b0de86e930a
28.85567
83
0.73826
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
GoDToolOSX/Views/PopUp Buttons/GoDGCEnumerablePopUpButtons.swift
gpl-2.0
1
// // GoDGCEnumerablePopUpButtons.swift // GoD Tool // // Created by Stars Momodu on 21/02/2020. // import Foundation class GoDPocketPopUpButton: GoDPopUpButton, GoDEnumerableButton { typealias Element = XGBagSlots lazy var allValues = Element.allValues override func setUpItems() { setUpEnumerableItems() } } class GoDDirectionPopUpButton: GoDPopUpButton, GoDEnumerableButton { typealias Element = XGElevatorDirections lazy var allValues = Element.allValues override func setUpItems() { setUpEnumerableItems() } } class GoDTrainerClassPopUpButton: GoDPopUpButton, GoDEnumerableButton { typealias Element = XGTrainerClasses lazy var allValues = Element.allValues override func setUpItems() { setUpEnumerableItems() } } class GoDTrainerModelPopUpButton: GoDPopUpButton, GoDEnumerableButton { typealias Element = XGTrainerModels lazy var allValues = Element.allValues override func setUpItems() { setUpEnumerableItems() } } class GoDBattleTypePopUpButton: GoDPopUpButton, GoDEnumerableButton { typealias Element = XGBattleTypes lazy var allValues = Element.allValues override func setUpItems() { setUpEnumerableItems() } }
0ff4d8182d3e9833610b4941884f4a38
25.954545
71
0.77403
false
false
false
false
usagimaru/USGScrollingTabBar_Swift
refs/heads/master
ProjectFiles/USGScrollingTabBar/USGScrollingTabCell.swift
mit
1
// // USGScrollingTabCell.swift // ScrollingTabBar // // Created by Satori Maru on 16.07.04. // Copyright © 2015-2017 usagimaru. All rights reserved. // import UIKit class USGScrollingTabCell: UICollectionViewCell { var index: Int = 0 var normalString: NSAttributedString? var highlightedString: NSAttributedString? var selectedString: NSAttributedString? weak var collectionView: UICollectionView? weak var target: NSObjectProtocol? var buttonAction: Selector? override var isHighlighted: Bool { didSet { setNeedsLayout() } } override var isSelected: Bool { didSet { setNeedsLayout() } } @IBOutlet weak var label: UILabel! @IBOutlet weak var leftConstraint: NSLayoutConstraint! @IBOutlet weak var rightConstraint: NSLayoutConstraint! @IBOutlet weak var button: UIButton! fileprivate static var padding: UIEdgeInsets = UIEdgeInsets.zero override class func initialize() { super.initialize() if let cell = self.nib().instantiate(withOwner: nil, options: nil).first as? USGScrollingTabCell { padding = UIEdgeInsetsMake(0, cell.leftConstraint.constant, 0, cell.rightConstraint.constant) } } class func nib() -> UINib { return UINib(nibName: "USGScrollingTabCell", bundle: nil) } class func tabWidth(_ string: NSAttributedString, tabInset: CGFloat) -> CGFloat { // 文字列の必要な幅を計算 let bounds = string.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin], context: nil) // 余白をたす。繰上げしないと収まりきらない let w = max(ceil(bounds.size.width + padding.left + padding.right) + tabInset * 2.0, 1.0) return w } func setNormalStringWithoutAnimation(_ string: NSAttributedString) { normalString = string label.attributedText = string } override func layoutSubviews() { super.layoutSubviews() guard let collectionView = collectionView else { return } guard let indexPath = collectionView.indexPathsForSelectedItems!.first else { return } // TODO: fix animation setAttributedText(false, indexPath: indexPath) } fileprivate func setAttributedText(_ animated: Bool, indexPath: IndexPath) { var str: NSAttributedString? = nil if isHighlighted { str = highlightedString } else if isSelected == true && index == (indexPath as IndexPath).row { str = selectedString } else if (indexPath as IndexPath).row != index { str = normalString } if let str = str { label.attributedText = str let duration: TimeInterval = isHighlighted == true && animated == true ? 0.2 : 0.0 UIView.transition(with: label, duration: duration, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.label.attributedText = str }, completion: nil) } } @IBAction fileprivate func buttonAction(_ sender: AnyObject) { if let buttonAction = buttonAction { let _ = target?.perform(buttonAction, with: self) } } }
1d337efa05ae1675385927c8fa436151
25.198347
129
0.675079
false
false
false
false
MuYangZhe/Swift30Projects
refs/heads/master
LoveWeibo/LoveWeibo/ViewController.swift
mit
1
// // ViewController.swift // LoveWeibo // // Created by 牧易 on 17/7/6. // Copyright © 2017年 MuYi. All rights reserved. // import UIKit import Social class ViewController: UIViewController { @IBOutlet weak var nameTF: UITextField! @IBOutlet weak var genderControl: UISegmentedControl! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var workTF: UITextField! @IBOutlet weak var salarySlider: UISlider! @IBOutlet weak var salaryLabel: UILabel! @IBOutlet weak var straightSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() } @IBAction func changeSalary(_ sender: UISlider) { let i = Int(sender.value) salaryLabel.text = "¥\(i)k" } @IBAction func sendWeibo(_ sender: UIButton) { let name = nameTF.text let work = workTF.text let salary = salaryLabel.text if(name == "" || work == "" || salary == ""){ showAlert(title: "Info Miss", message: "Please fill out the form", buttonTitle: "Ok") return; } var interestedIn:String? = "Women" if(genderControl.selectedSegmentIndex == 0 && !straightSwitch.isOn){ interestedIn = "Man" } if(genderControl.selectedSegmentIndex == 1 && straightSwitch.isOn){ interestedIn = "Man" } let gregorian = Calendar(identifier: .gregorian) let now = Date() let component = (gregorian as NSCalendar).components(NSCalendar.Unit.year, from: datePicker.date, to: now, options: []) let age = component.year let weibo = "Hi, I am \(name!). As a \(age!)-year-old \(work!) earning \(salary!)/year, I am interested in \(interestedIn). Feel free to contact me!" sendWeibo(weibo) } fileprivate func sendWeibo(_ weibo:String){ if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeSinaWeibo){ let weiboViewController:SLComposeViewController = SLComposeViewController.init(forServiceType: SLServiceTypeSinaWeibo) weiboViewController.setInitialText(weibo); self.present(weiboViewController, animated: true, completion: nil) }else{ showAlert(title: "Weibo Unavailable", message: "Please configure your twitter account on device", buttonTitle: "Ok") } } fileprivate func showAlert(title:String,message:String,buttonTitle:String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert); alert.addAction(UIAlertAction(title: buttonTitle, style: .default, handler: nil)) self.present(alert, animated: true, completion: nil); } }
57a7830cd59b0016e8d7619c235d84e7
32.95122
157
0.630388
false
false
false
false
timfuqua/Bourgeoisie
refs/heads/master
Bourgeoisie/Bourgeoisie/Model/BourgAlgorithms.swift
mit
1
// // BourgAlgorithms.swift // Bourgeoisie // // Created by Tim Fuqua on 1/4/16. // Copyright © 2016 FuquaProductions. All rights reserved. // import Foundation import UIKit // MARK: BourgAlgorithms /** A namespace for algorithms relating to Bourgeoisie game logic */ final class BourgAlgorithms { // MARK: class vars enum FlushRanking: Int { case NoCards = 0 case OneCardFlushAce case OneCardFlushTwo case OneCardFlushThree case OneCardFlushFour case OneCardFlushFive case OneCardFlushSix case OneCardFlushSeven case OneCardFlushEight case OneCardFlushNine case OneCardFlushTen case TwoCardFlushAce case TwoCardFlushTwo case TwoCardFlushThree case TwoCardFlushFour case TwoCardFlushFive case TwoCardFlushSix case TwoCardFlushSeven case TwoCardFlushEight case TwoCardFlushNine case TwoCardFlushTen case ThreeCardFlushTwo case ThreeCardFlushThree case ThreeCardFlushFour case ThreeCardFlushFive case ThreeCardFlushSix case ThreeCardFlushSeven case ThreeCardFlushEight case ThreeCardFlushNine case ThreeCardFlushTen case FourCardFlushThree case FourCardFlushFour case FourCardFlushFive case FourCardFlushSix case FourCardFlushSeven case FourCardFlushEight case FourCardFlushNine case FourCardFlushTen case FiveCardFlushFour case FiveCardFlushFive case FiveCardFlushSix case FiveCardFlushSeven case FiveCardFlushEight case FiveCardFlushNine case FiveCardFlushTen static var Lowest: FlushRanking { get { return OneCardFlushAce } } static var TierOne: FlushRanking { get { return OneCardFlushAce } } static var TierTwo: FlushRanking { get { return TwoCardFlushAce } } static var TierThree: FlushRanking { get { return ThreeCardFlushTwo } } static var TierFour: FlushRanking { get { return FourCardFlushThree } } static var TierFive: FlushRanking { get { return FiveCardFlushFour } } static var Highest: FlushRanking { get { return FiveCardFlushTen } } func totalRanks() -> Int { return FlushRanking.Highest.rawValue - FlushRanking.Lowest.rawValue + 1 } func rankPercentile() -> CGFloat { return CGFloat(self.rawValue)/CGFloat(totalRanks())*100.0 } func description() -> String { switch self.rawValue { case NoCards.rawValue: return "No card flush" case OneCardFlushAce.rawValue: return "Ace high one card flush" case OneCardFlushTwo.rawValue: return "Two high one card flush" case OneCardFlushThree.rawValue: return "Three high one card flush" case OneCardFlushFour.rawValue: return "Four high one card flush" case OneCardFlushFive.rawValue: return "Five high one card flush" case OneCardFlushSix.rawValue: return "Six high one card flush" case OneCardFlushSeven.rawValue: return "Seven high one card flush" case OneCardFlushEight.rawValue: return "Eight high one card flush" case OneCardFlushNine.rawValue: return "Nine high one card flush" case OneCardFlushTen.rawValue: return "Ten high one card flush" case TwoCardFlushAce.rawValue: return "Ace high two card flush" case TwoCardFlushTwo.rawValue: return "Two high two card flush" case TwoCardFlushThree.rawValue: return "Three high two card flush" case TwoCardFlushFour.rawValue: return "Four high two card flush" case TwoCardFlushFive.rawValue: return "Five high two card flush" case TwoCardFlushSix.rawValue: return "Six high two card flush" case TwoCardFlushSeven.rawValue: return "Seven high two card flush" case TwoCardFlushEight.rawValue: return "Eight high two card flush" case TwoCardFlushNine.rawValue: return "Nine high two card flush" case TwoCardFlushTen.rawValue: return "Ten high two card flush" case ThreeCardFlushTwo.rawValue: return "Two high three card flush" case ThreeCardFlushThree.rawValue: return "Three high three card flush" case ThreeCardFlushFour.rawValue: return "Four high three card flush" case ThreeCardFlushFive.rawValue: return "Five high three card flush" case ThreeCardFlushSix.rawValue: return "Six high three card flush" case ThreeCardFlushSeven.rawValue: return "Seven high three card flush" case ThreeCardFlushEight.rawValue: return "Eight high three card flush" case ThreeCardFlushNine.rawValue: return "Nine high three card flush" case ThreeCardFlushTen.rawValue: return "Ten high three card flush" case FourCardFlushThree.rawValue: return "Three high four card flush" case FourCardFlushFour.rawValue: return "Four high four card flush" case FourCardFlushFive.rawValue: return "Five high four card flush" case FourCardFlushSix.rawValue: return "Six high four card flush" case FourCardFlushSeven.rawValue: return "Seven high four card flush" case FourCardFlushEight.rawValue: return "Eight high four card flush" case FourCardFlushNine.rawValue: return "Nine high four card flush" case FourCardFlushTen.rawValue: return "Ten high four card flush" case FiveCardFlushFour.rawValue: return "Four high five card flush" case FiveCardFlushFive.rawValue: return "Five high five card flush" case FiveCardFlushSix.rawValue: return "Six high five card flush" case FiveCardFlushSeven.rawValue: return "Seven high five card flush" case FiveCardFlushEight.rawValue: return "Eight high five card flush" case FiveCardFlushNine.rawValue: return "Nine high five card flush" case FiveCardFlushTen.rawValue: return "Ten high five card flush" default: fatalError("Not a FlushRanking") } } } enum StraightRanking: Int { case NoCards = 0 case OneCardStraightAce case OneCardStraightTwo case OneCardStraightThree case OneCardStraightFour case OneCardStraightFive case OneCardStraightSix case OneCardStraightSeven case OneCardStraightEight case OneCardStraightNine case OneCardStraightTen case TwoCardStraightTwo case TwoCardStraightThree case TwoCardStraightFour case TwoCardStraightFive case TwoCardStraightSix case TwoCardStraightSeven case TwoCardStraightEight case TwoCardStraightNine case TwoCardStraightTen case ThreeCardStraightThree case ThreeCardStraightFour case ThreeCardStraightFive case ThreeCardStraightSix case ThreeCardStraightSeven case ThreeCardStraightEight case ThreeCardStraightNine case ThreeCardStraightTen case FourCardStraightFour case FourCardStraightFive case FourCardStraightSix case FourCardStraightSeven case FourCardStraightEight case FourCardStraightNine case FourCardStraightTen case FiveCardStraightFive case FiveCardStraightSix case FiveCardStraightSeven case FiveCardStraightEight case FiveCardStraightNine case FiveCardStraightTen static var Lowest: StraightRanking { get { return OneCardStraightAce } } static var TierOne: StraightRanking { get { return OneCardStraightAce } } static var TierTwo: StraightRanking { get { return TwoCardStraightTwo } } static var TierThree: StraightRanking { get { return ThreeCardStraightThree } } static var TierFour: StraightRanking { get { return FourCardStraightFour } } static var TierFive: StraightRanking { get { return FiveCardStraightFive } } static var Highest: StraightRanking { get { return FiveCardStraightTen } } func totalRanks() -> Int { return StraightRanking.Highest.rawValue - StraightRanking.Lowest.rawValue + 1 } func rankPercentile() -> CGFloat { return CGFloat(self.rawValue)/CGFloat(totalRanks())*100 } func description() -> String { switch self.rawValue { case NoCards.rawValue: return "No card straight" case OneCardStraightAce.rawValue: return "Ace high one card straight" case OneCardStraightTwo.rawValue: return "Two high one card straight" case OneCardStraightThree.rawValue: return "Three high one card straight" case OneCardStraightFour.rawValue: return "Four high one card straight" case OneCardStraightFive.rawValue: return "Five high one card straight" case OneCardStraightSix.rawValue: return "Six high one card straight" case OneCardStraightSeven.rawValue: return "Seven high one card straight" case OneCardStraightEight.rawValue: return "Eight high one card straight" case OneCardStraightNine.rawValue: return "Nine high one card straight" case OneCardStraightTen.rawValue: return "Ten high one card straight" case TwoCardStraightTwo.rawValue: return "Two high two card straight" case TwoCardStraightThree.rawValue: return "Three high two card straight" case TwoCardStraightFour.rawValue: return "Four high two card straight" case TwoCardStraightFive.rawValue: return "Five high two card straight" case TwoCardStraightSix.rawValue: return "Six high two card straight" case TwoCardStraightSeven.rawValue: return "Seven high two card straight" case TwoCardStraightEight.rawValue: return "Eight high two card straight" case TwoCardStraightNine.rawValue: return "Nine high two card straight" case TwoCardStraightTen.rawValue: return "Ten high two card straight" case ThreeCardStraightThree.rawValue: return "Three high three card straight" case ThreeCardStraightFour.rawValue: return "Four high three card straight" case ThreeCardStraightFive.rawValue: return "Five high three card straight" case ThreeCardStraightSix.rawValue: return "Six high three card straight" case ThreeCardStraightSeven.rawValue: return "Seven high three card straight" case ThreeCardStraightEight.rawValue: return "Eight high three card straight" case ThreeCardStraightNine.rawValue: return "Nine high three card straight" case ThreeCardStraightTen.rawValue: return "Ten high three card straight" case FourCardStraightFour.rawValue: return "Four high four card straight" case FourCardStraightFive.rawValue: return "Five high four card straight" case FourCardStraightSix.rawValue: return "Six high four card straight" case FourCardStraightSeven.rawValue: return "Seven high four card straight" case FourCardStraightEight.rawValue: return "Eight high four card straight" case FourCardStraightNine.rawValue: return "Nine high four card straight" case FourCardStraightTen.rawValue: return "Ten high four card straight" case FiveCardStraightFive.rawValue: return "Five high five card straight" case FiveCardStraightSix.rawValue: return "Six high five card straight" case FiveCardStraightSeven.rawValue: return "Seven high five card straight" case FiveCardStraightEight.rawValue: return "Eight high five card straight" case FiveCardStraightNine.rawValue: return "Nine high five card straight" case FiveCardStraightTen.rawValue: return "Ten high five card straight" default: fatalError("Not a StraightRanking") } } } enum BookRanking: Int { case NoCards = 0 case OneCardBookAce case OneCardBookTwo case OneCardBookThree case OneCardBookFour case OneCardBookFive case OneCardBookSix case OneCardBookSeven case OneCardBookEight case OneCardBookNine case OneCardBookTen case TwoCardBookAce case TwoCardBookTwo case TwoCardBookThree case TwoCardBookFour case TwoCardBookFive case TwoCardBookSix case TwoCardBookSeven case TwoCardBookEight case TwoCardBookNine case TwoCardBookTen case TwoPairBookAceTwo case TwoPairBookAceThree case TwoPairBookTwoThree case TwoPairBookAceFour case TwoPairBookTwoFour case TwoPairBookThreeFour case TwoPairBookAceFive case TwoPairBookTwoFive case TwoPairBookThreeFive case TwoPairBookFourFive case TwoPairBookAceSix case TwoPairBookTwoSix case TwoPairBookThreeSix case TwoPairBookFourSix case TwoPairBookFiveSix case TwoPairBookAceSeven case TwoPairBookTwoSeven case TwoPairBookThreeSeven case TwoPairBookFourSeven case TwoPairBookFiveSeven case TwoPairBookSixSeven case TwoPairBookAceEight case TwoPairBookTwoEight case TwoPairBookThreeEight case TwoPairBookFourEight case TwoPairBookFiveEight case TwoPairBookSixEight case TwoPairBookSevenEight case TwoPairBookAceNine case TwoPairBookTwoNine case TwoPairBookThreeNine case TwoPairBookFourNine case TwoPairBookFiveNine case TwoPairBookSixNine case TwoPairBookSevenNine case TwoPairBookEightNine case TwoPairBookAceTen case TwoPairBookTwoTen case TwoPairBookThreeTen case TwoPairBookFourTen case TwoPairBookFiveTen case TwoPairBookSixTen case TwoPairBookSevenTen case TwoPairBookEightTen case TwoPairBookNineTen case ThreeCardBookAce case ThreeCardBookTwo case ThreeCardBookThree case ThreeCardBookFour case ThreeCardBookFive case ThreeCardBookSix case ThreeCardBookSeven case ThreeCardBookEight case ThreeCardBookNine case ThreeCardBookTen case FullHouseBookAceTwo case FullHouseBookAceThree case FullHouseBookAceFour case FullHouseBookAceFive case FullHouseBookAceSix case FullHouseBookAceSeven case FullHouseBookAceEight case FullHouseBookAceNine case FullHouseBookAceTen case FullHouseBookTwoAce case FullHouseBookTwoThree case FullHouseBookTwoFour case FullHouseBookTwoFive case FullHouseBookTwoSix case FullHouseBookTwoSeven case FullHouseBookTwoEight case FullHouseBookTwoNine case FullHouseBookTwoTen case FullHouseBookThreeAce case FullHouseBookThreeTwo case FullHouseBookThreeFour case FullHouseBookThreeFive case FullHouseBookThreeSix case FullHouseBookThreeSeven case FullHouseBookThreeEight case FullHouseBookThreeNine case FullHouseBookThreeTen case FullHouseBookFourAce case FullHouseBookFourTwo case FullHouseBookFourThree case FullHouseBookFourFive case FullHouseBookFourSix case FullHouseBookFourSeven case FullHouseBookFourEight case FullHouseBookFourNine case FullHouseBookFourTen case FullHouseBookFiveAce case FullHouseBookFiveTwo case FullHouseBookFiveThree case FullHouseBookFiveFour case FullHouseBookFiveSix case FullHouseBookFiveSeven case FullHouseBookFiveEight case FullHouseBookFiveNine case FullHouseBookFiveTen case FullHouseBookSixAce case FullHouseBookSixTwo case FullHouseBookSixThree case FullHouseBookSixFour case FullHouseBookSixFive case FullHouseBookSixSeven case FullHouseBookSixEight case FullHouseBookSixNine case FullHouseBookSixTen case FullHouseBookSevenAce case FullHouseBookSevenTwo case FullHouseBookSevenThree case FullHouseBookSevenFour case FullHouseBookSevenFive case FullHouseBookSevenSix case FullHouseBookSevenEight case FullHouseBookSevenNine case FullHouseBookSevenTen case FullHouseBookEightAce case FullHouseBookEightTwo case FullHouseBookEightThree case FullHouseBookEightFour case FullHouseBookEightFive case FullHouseBookEightSix case FullHouseBookEightSeven case FullHouseBookEightNine case FullHouseBookEightTen case FullHouseBookNineAce case FullHouseBookNineTwo case FullHouseBookNineThree case FullHouseBookNineFour case FullHouseBookNineFive case FullHouseBookNineSix case FullHouseBookNineSeven case FullHouseBookNineEight case FullHouseBookNineTen case FullHouseBookTenAce case FullHouseBookTenTwo case FullHouseBookTenThree case FullHouseBookTenFour case FullHouseBookTenFive case FullHouseBookTenSix case FullHouseBookTenSeven case FullHouseBookTenEight case FullHouseBookTenNine case FourCardBookAce case FourCardBookTwo case FourCardBookThree case FourCardBookFour case FourCardBookFive case FourCardBookSix case FourCardBookSeven case FourCardBookEight case FourCardBookNine case FourCardBookTen case FiveCardBookAce case FiveCardBookTwo case FiveCardBookThree case FiveCardBookFour case FiveCardBookFive case FiveCardBookSix case FiveCardBookSeven case FiveCardBookEight case FiveCardBookNine case FiveCardBookTen static var Lowest: BookRanking { get { return OneCardBookAce } } static var TierOne: BookRanking { get { return OneCardBookAce } } static var TierTwo: BookRanking { get { return TwoCardBookAce } } static var TierThree: BookRanking { get { return TwoPairBookAceTwo } } static var TierFour: BookRanking { get { return ThreeCardBookAce } } static var TierFive: BookRanking { get { return FullHouseBookAceTwo } } static var TierSix: BookRanking { get { return FourCardBookAce } } static var TierSeven: BookRanking { get { return FiveCardBookAce } } static var Highest: BookRanking { get { return FiveCardBookTen } } func totalRanks() -> Int { return BookRanking.Highest.rawValue - BookRanking.Lowest.rawValue + 1 } func rankPercentile() -> CGFloat { return CGFloat(self.rawValue)/CGFloat(totalRanks())*100.0 } func description() -> String { switch self.rawValue { case NoCards.rawValue: return "No card book" case OneCardBookAce.rawValue: return "Ace high one of kind" case OneCardBookTwo.rawValue: return "Two high one of kind" case OneCardBookThree.rawValue: return "Three high one of kind" case OneCardBookFour.rawValue: return "Four high one of kind" case OneCardBookFive.rawValue: return "Five high one of kind" case OneCardBookSix.rawValue: return "Six high one of kind" case OneCardBookSeven.rawValue: return "Seven high one of kind" case OneCardBookEight.rawValue: return "Eight high one of kind" case OneCardBookNine.rawValue: return "Nine high one of kind" case OneCardBookTen.rawValue: return "Ten high one of kind" case TwoCardBookAce.rawValue: return "Ace high two of a kind" case TwoCardBookTwo.rawValue: return "Two high two of a kind" case TwoCardBookThree.rawValue: return "Three high two of a kind" case TwoCardBookFour.rawValue: return "Four high two of a kind" case TwoCardBookFive.rawValue: return "Five high two of a kind" case TwoCardBookSix.rawValue: return "Six high two of a kind" case TwoCardBookSeven.rawValue: return "Seven high two of a kind" case TwoCardBookEight.rawValue: return "Eight high two of a kind" case TwoCardBookNine.rawValue: return "Nine high two of a kind" case TwoCardBookTen.rawValue: return "Ten high two of a kind" case TwoPairBookAceTwo.rawValue: return "Two pair of Aces and Twos" case TwoPairBookAceThree.rawValue: return "Two pair of Aces and Threes" case TwoPairBookTwoThree.rawValue: return "Two pair of Twos and Threes" case TwoPairBookAceFour.rawValue: return "Two pair of Aces and Fours" case TwoPairBookTwoFour.rawValue: return "Two pair of Twos and Fours" case TwoPairBookThreeFour.rawValue: return "Two pair of Threes and Fours" case TwoPairBookAceFive.rawValue: return "Two pair of Aces and Fives" case TwoPairBookTwoFive.rawValue: return "Two pair of Twos and Fives" case TwoPairBookThreeFive.rawValue: return "Two pair of Threes and Fives" case TwoPairBookFourFive.rawValue: return "Two pair of Fours and Fives" case TwoPairBookAceSix.rawValue: return "Two pair of Aces and Sixes" case TwoPairBookTwoSix.rawValue: return "Two pair of Twos and Sixes" case TwoPairBookThreeSix.rawValue: return "Two pair of Threes and Sixes" case TwoPairBookFourSix.rawValue: return "Two pair of Fours and Sixes" case TwoPairBookFiveSix.rawValue: return "Two pair of Fives and Sixes" case TwoPairBookAceSeven.rawValue: return "Two pair of Aces and Sevens" case TwoPairBookTwoSeven.rawValue: return "Two pair of Twos and Sevens" case TwoPairBookThreeSeven.rawValue: return "Two pair of Threes and Sevens" case TwoPairBookFourSeven.rawValue: return "Two pair of Fours and Sevens" case TwoPairBookFiveSeven.rawValue: return "Two pair of Fives and Sevens" case TwoPairBookSixSeven.rawValue: return "Two pair of Sixes and Sevens" case TwoPairBookAceEight.rawValue: return "Two pair of Aces and Eights" case TwoPairBookTwoEight.rawValue: return "Two pair of Twos and Eights" case TwoPairBookThreeEight.rawValue: return "Two pair of Threes and Eights" case TwoPairBookFourEight.rawValue: return "Two pair of Fours and Eights" case TwoPairBookFiveEight.rawValue: return "Two pair of Fives and Eights" case TwoPairBookSixEight.rawValue: return "Two pair of Sixes and Eights" case TwoPairBookSevenEight.rawValue: return "Two pair of Sevens and Eights" case TwoPairBookAceNine.rawValue: return "Two pair of Aces and Nines" case TwoPairBookTwoNine.rawValue: return "Two pair of Twos and Nines" case TwoPairBookThreeNine.rawValue: return "Two pair of Threes and Nines" case TwoPairBookFourNine.rawValue: return "Two pair of Fours and Nines" case TwoPairBookFiveNine.rawValue: return "Two pair of Fives and Nines" case TwoPairBookSixNine.rawValue: return "Two pair of Sixes and Nines" case TwoPairBookSevenNine.rawValue: return "Two pair of Sevens and Nines" case TwoPairBookEightNine.rawValue: return "Two pair of Eights and Nines" case TwoPairBookAceTen.rawValue: return "Two pair of Aces and Tens" case TwoPairBookTwoTen.rawValue: return "Two pair of Twos and Tens" case TwoPairBookThreeTen.rawValue: return "Two pair of Threes and Tens" case TwoPairBookFourTen.rawValue: return "Two pair of Fours and Tens" case TwoPairBookFiveTen.rawValue: return "Two pair of Fives and Tens" case TwoPairBookSixTen.rawValue: return "Two pair of Sixes and Tens" case TwoPairBookSevenTen.rawValue: return "Two pair of Sevens and Tens" case TwoPairBookEightTen.rawValue: return "Two pair of Eights and Tens" case TwoPairBookNineTen.rawValue: return "Two pair of Nines and Tens" case ThreeCardBookAce.rawValue: return "Ace high three of a kind" case ThreeCardBookTwo.rawValue: return "Two high three of a kind" case ThreeCardBookThree.rawValue: return "Three high three of a kind" case ThreeCardBookFour.rawValue: return "Four high three of a kind" case ThreeCardBookFive.rawValue: return "Five high three of a kind" case ThreeCardBookSix.rawValue: return "Six high three of a kind" case ThreeCardBookSeven.rawValue: return "Seven high three of a kind" case ThreeCardBookEight.rawValue: return "Eight high three of a kind" case ThreeCardBookNine.rawValue: return "Nine high three of a kind" case ThreeCardBookTen.rawValue: return "Ten high three of a kind" case FullHouseBookAceTwo.rawValue: return "Full house of Aces over Twos" case FullHouseBookAceThree.rawValue: return "Full house of Aces over Threes" case FullHouseBookAceFour.rawValue: return "Full house of Aces over Fours" case FullHouseBookAceFive.rawValue: return "Full house of Aces over Fives" case FullHouseBookAceSix.rawValue: return "Full house of Aces over Sixes" case FullHouseBookAceSeven.rawValue: return "Full house of Aces over Sevens" case FullHouseBookAceEight.rawValue: return "Full house of Aces over Eights" case FullHouseBookAceNine.rawValue: return "Full house of Aces over Nines" case FullHouseBookAceTen.rawValue: return "Full house of Aces over Tens" case FullHouseBookTwoAce.rawValue: return "Full house of Twos over Aces" case FullHouseBookTwoThree.rawValue: return "Full house of Twos over Threes" case FullHouseBookTwoFour.rawValue: return "Full house of Twos over Fours" case FullHouseBookTwoFive.rawValue: return "Full house of Twos over Fives" case FullHouseBookTwoSix.rawValue: return "Full house of Twos over Sixes" case FullHouseBookTwoSeven.rawValue: return "Full house of Twos over Sevens" case FullHouseBookTwoEight.rawValue: return "Full house of Twos over Eights" case FullHouseBookTwoNine.rawValue: return "Full house of Twos over Nines" case FullHouseBookTwoTen.rawValue: return "Full house of Twos over Tens" case FullHouseBookThreeAce.rawValue: return "Full house of Threes over Aces" case FullHouseBookThreeTwo.rawValue: return "Full house of Threes over Twos" case FullHouseBookThreeFour.rawValue: return "Full house of Threes over Fours" case FullHouseBookThreeFive.rawValue: return "Full house of Threes over Fives" case FullHouseBookThreeSix.rawValue: return "Full house of Threes over Sixes" case FullHouseBookThreeSeven.rawValue: return "Full house of Threes over Sevens" case FullHouseBookThreeEight.rawValue: return "Full house of Threes over Eights" case FullHouseBookThreeNine.rawValue: return "Full house of Threes over Nines" case FullHouseBookThreeTen.rawValue: return "Full house of Threes over Tens" case FullHouseBookFourAce.rawValue: return "Full house of Fours over Aces" case FullHouseBookFourTwo.rawValue: return "Full house of Fours over Twos" case FullHouseBookFourThree.rawValue: return "Full house of Fours over Threes" case FullHouseBookFourFive.rawValue: return "Full house of Fours over Fives" case FullHouseBookFourSix.rawValue: return "Full house of Fours over Sixes" case FullHouseBookFourSeven.rawValue: return "Full house of Fours over Sevens" case FullHouseBookFourEight.rawValue: return "Full house of Fours over Eights" case FullHouseBookFourNine.rawValue: return "Full house of Fours over Nines" case FullHouseBookFourTen.rawValue: return "Full house of Fours over Tens" case FullHouseBookFiveAce.rawValue: return "Full house of Fives over Aces" case FullHouseBookFiveTwo.rawValue: return "Full house of Fives over Twos" case FullHouseBookFiveThree.rawValue: return "Full house of Fives over Threes" case FullHouseBookFiveFour.rawValue: return "Full house of Fives over Fours" case FullHouseBookFiveSix.rawValue: return "Full house of Fives over Sixes" case FullHouseBookFiveSeven.rawValue: return "Full house of Fives over Sevens" case FullHouseBookFiveEight.rawValue: return "Full house of Fives over Eights" case FullHouseBookFiveNine.rawValue: return "Full house of Fives over Nines" case FullHouseBookFiveTen.rawValue: return "Full house of Fives over Tens" case FullHouseBookSixAce.rawValue: return "Full house of Sixes over Aces" case FullHouseBookSixTwo.rawValue: return "Full house of Sixes over Twos" case FullHouseBookSixThree.rawValue: return "Full house of Sixes over Threes" case FullHouseBookSixFour.rawValue: return "Full house of Sixes over Fours" case FullHouseBookSixFive.rawValue: return "Full house of Sixes over Fives" case FullHouseBookSixSeven.rawValue: return "Full house of Sixes over Sevens" case FullHouseBookSixEight.rawValue: return "Full house of Sixes over Eights" case FullHouseBookSixNine.rawValue: return "Full house of Sixes over Nines" case FullHouseBookSixTen.rawValue: return "Full house of Sixes over Tens" case FullHouseBookSevenAce.rawValue: return "Full house of Sevens over Aces" case FullHouseBookSevenTwo.rawValue: return "Full house of Sevens over Twos" case FullHouseBookSevenThree.rawValue: return "Full house of Sevens over Threes" case FullHouseBookSevenFour.rawValue: return "Full house of Sevens over Fours" case FullHouseBookSevenFive.rawValue: return "Full house of Sevens over Fives" case FullHouseBookSevenSix.rawValue: return "Full house of Sevens over Sixes" case FullHouseBookSevenEight.rawValue: return "Full house of Sevens over Eights" case FullHouseBookSevenNine.rawValue: return "Full house of Sevens over Nines" case FullHouseBookSevenTen.rawValue: return "Full house of Sevens over Tens" case FullHouseBookEightAce.rawValue: return "Full house of Eights over Aces" case FullHouseBookEightTwo.rawValue: return "Full house of Eights over Twos" case FullHouseBookEightThree.rawValue: return "Full house of Eights over Threes" case FullHouseBookEightFour.rawValue: return "Full house of Eights over Fours" case FullHouseBookEightFive.rawValue: return "Full house of Eights over Fives" case FullHouseBookEightSix.rawValue: return "Full house of Eights over Sixes" case FullHouseBookEightSeven.rawValue: return "Full house of Eights over Sevens" case FullHouseBookEightNine.rawValue: return "Full house of Eights over Nines" case FullHouseBookEightTen.rawValue: return "Full house of Eights over Tens" case FullHouseBookNineAce.rawValue: return "Full house of Nines over Aces" case FullHouseBookNineTwo.rawValue: return "Full house of Nines over Twos" case FullHouseBookNineThree.rawValue: return "Full house of Nines over Threes" case FullHouseBookNineFour.rawValue: return "Full house of Nines over Fours" case FullHouseBookNineFive.rawValue: return "Full house of Nines over Fives" case FullHouseBookNineSix.rawValue: return "Full house of Nines over Sixes" case FullHouseBookNineSeven.rawValue: return "Full house of Nines over Sevens" case FullHouseBookNineEight.rawValue: return "Full house of Nines over Eights" case FullHouseBookNineTen.rawValue: return "Full house of Nines over Tens" case FullHouseBookTenAce.rawValue: return "Full house of Tens over Aces" case FullHouseBookTenTwo.rawValue: return "Full house of Tens over Twos" case FullHouseBookTenThree.rawValue: return "Full house of Tens over Threes" case FullHouseBookTenFour.rawValue: return "Full house of Tens over Fours" case FullHouseBookTenFive.rawValue: return "Full house of Tens over Fives" case FullHouseBookTenSix.rawValue: return "Full house of Tens over Sixes" case FullHouseBookTenSeven.rawValue: return "Full house of Tens over Sevens" case FullHouseBookTenEight.rawValue: return "Full house of Tens over Eights" case FullHouseBookTenNine.rawValue: return "Full house of Tens over Nines" case FourCardBookAce.rawValue: return "Ace high four of a kind" case FourCardBookTwo.rawValue: return "Two high four of a kind" case FourCardBookThree.rawValue: return "Three high four of a kind" case FourCardBookFour.rawValue: return "Four high four of a kind" case FourCardBookFive.rawValue: return "Five high four of a kind" case FourCardBookSix.rawValue: return "Six high four of a kind" case FourCardBookSeven.rawValue: return "Seven high four of a kind" case FourCardBookEight.rawValue: return "Eight high four of a kind" case FourCardBookNine.rawValue: return "Nine high four of a kind" case FourCardBookTen.rawValue: return "Ten high four of a kind" case FiveCardBookAce.rawValue: return "Ace high five of a kind" case FiveCardBookTwo.rawValue: return "Two high five of a kind" case FiveCardBookThree.rawValue: return "Three high five of a kind" case FiveCardBookFour.rawValue: return "Four high five of a kind" case FiveCardBookFive.rawValue: return "Five high five of a kind" case FiveCardBookSix.rawValue: return "Six high five of a kind" case FiveCardBookSeven.rawValue: return "Seven high five of a kind" case FiveCardBookEight.rawValue: return "Eight high five of a kind" case FiveCardBookNine.rawValue: return "Nine high five of a kind" case FiveCardBookTen.rawValue: return "Ten high five of a kind" default: fatalError("Not a BookRanking") } } } // MARK: private lets // MARK: private vars (computed) // MARK: private vars // MARK: private(set) vars // MARK: lets // MARK: vars (computed) // MARK: vars // MARK: init // MARK: public funcs // MARK: private funcs private init() {} // MARK: class funcs class func isAFlush(cards: [Card]) -> FlushRanking? { if cards.count > 0 { if cards.filter({return $0.suit == cards[0].suit}).count == cards.count { var flushTier: FlushRanking? = nil var flushTierIndexOffset: Int = 0 switch cards.count { case 1: flushTier = FlushRanking.TierOne case 2: flushTier = FlushRanking.TierTwo case 3: flushTier = FlushRanking.TierThree flushTierIndexOffset = 1 case 4: flushTier = FlushRanking.TierFour flushTierIndexOffset = 2 case 5: flushTier = FlushRanking.TierFive flushTierIndexOffset = 3 default: print("It is a flush, but too many cards for a Bourgeoisie hand. cards.count: \(cards.count)") } if flushTier != nil { return FlushRanking(rawValue: flushTier!.rawValue + cards.sort().last!.rank!.rawValue - flushTierIndexOffset - 1) } } return nil } else { return FlushRanking.NoCards } } class func isAStraight(cards: [Card]) -> StraightRanking? { if cards.count == 0 { return StraightRanking.NoCards } if cards.count == 1 { return StraightRanking(rawValue: StraightRanking.NoCards.rawValue + cards[0].rank!.rawValue) } var straightVal: StraightRanking? = nil var straightTier: StraightRanking? = nil var sortedCards = cards.sort() var expectedNextValue = sortedCards[0].rank.rawValue + 1 sortedCards.removeFirst() for card in sortedCards { if card.rank.rawValue != expectedNextValue { return nil } else { expectedNextValue++ } } switch cards.count { case 1: straightTier = StraightRanking.TierOne case 2: straightTier = StraightRanking.TierTwo case 3: straightTier = StraightRanking.TierThree case 4: straightTier = StraightRanking.TierFour case 5: straightTier = StraightRanking.TierFive default: print("It is a straight, but too many cards for a Bourgeoisie hand. cards.count: \(cards.count)") } if straightTier != nil { let straightTierIndexOffset = cards.count - 1 straightVal = StraightRanking(rawValue: straightTier!.rawValue + sortedCards.last!.rank!.rawValue - straightTierIndexOffset - 1) } return straightVal } class func isABook(cards: [Card]) -> BookRanking? { if cards.count == 0 { return BookRanking.NoCards } var bookDict: [Rank:Int] = [:] for card in cards { // if card.rank exists as a key in the dictionary if let rankVal = bookDict[card.rank] { bookDict.updateValue(rankVal+1, forKey: card.rank) } else { bookDict.updateValue(1, forKey: card.rank) } } var bookVal: BookRanking? = nil var bookTier: BookRanking? = nil switch cards.count { case 1: bookTier = BookRanking.TierOne bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1) case 2: if bookDict.keys.count == 1 { bookTier = BookRanking.TierTwo bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1) } case 3: if bookDict.keys.count == 1 { bookTier = BookRanking.TierFour bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1) } case 4: if bookDict.keys.count == 1 { bookTier = BookRanking.TierSix bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1) } else if bookDict.keys.count == 2 && bookDict.values.first == 2 { bookTier = BookRanking.TierThree let pairRanks = bookDict.keys.sort({return $0.rawValue < $1.rawValue}) let firstIndexOffset = (pairRanks[1].rawValue-2)*(pairRanks[1].rawValue-1)/2 let secondIndexOffset = pairRanks[0].rawValue-1 bookVal = BookRanking(rawValue: bookTier!.rawValue + firstIndexOffset + secondIndexOffset) } case 5: if bookDict.keys.count == 1 { bookTier = BookRanking.TierSeven bookVal = BookRanking(rawValue: bookTier!.rawValue + bookDict.keys.first!.rawValue - 1) } else if bookDict.keys.count == 2 && (bookDict.values.first == 2 || bookDict.values.first == 3) { bookTier = BookRanking.TierFive let ofRanks = bookDict.keys.sort({return $0.rawValue < $1.rawValue}) var threeOfRank: Rank! var twoOfRank: Rank! if bookDict[ofRanks[0]] == 3 { threeOfRank = ofRanks[0] twoOfRank = ofRanks[1] } else { threeOfRank = ofRanks[1] twoOfRank = ofRanks[0] } let firstIndexOffset = 9*(threeOfRank.rawValue - 1) let secondIndexOffset = (twoOfRank.rawValue < threeOfRank.rawValue) ? (twoOfRank.rawValue - 1) : (twoOfRank.rawValue - 2) bookVal = BookRanking(rawValue: bookTier!.rawValue + firstIndexOffset + secondIndexOffset) } default: print("Too many cards for a Bourgeoisie hand. cards.count: \(cards.count)") } return bookVal } }
686203f64d0fbfdcafd69fdaa7a70251
42.989583
134
0.730918
false
false
false
false
ReactiveX/RxSwift
refs/heads/develop
Example/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift
gpl-3.0
7
// // UISearchBar+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import RxSwift import UIKit extension Reactive where Base: UISearchBar { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy<UISearchBar, UISearchBarDelegate> { RxSearchBarDelegateProxy.proxy(for: base) } /// Reactive wrapper for `text` property. public var text: ControlProperty<String?> { value } /// Reactive wrapper for `text` property. public var value: ControlProperty<String?> { let source: Observable<String?> = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable<String?> in let text = searchBar?.text let textDidChange = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) let didEndEditing = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) ?? Observable.empty()) return Observable.merge(textDidChange, didEndEditing) .map { _ in searchBar?.text ?? "" } .startWith(text) } let bindingObserver = Binder(self.base) { (searchBar, text: String?) in searchBar.text = text } return ControlProperty(values: source, valueSink: bindingObserver) } /// Reactive wrapper for `selectedScopeButtonIndex` property. public var selectedScopeButtonIndex: ControlProperty<Int> { let source: Observable<Int> = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable<Int> in let index = source?.selectedScopeButtonIndex ?? 0 return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) .map { a in return try castOrThrow(Int.self, a[1]) } .startWith(index) } let bindingObserver = Binder(self.base) { (searchBar, index: Int) in searchBar.selectedScopeButtonIndex = index } return ControlProperty(values: source, valueSink: bindingObserver) } #if os(iOS) /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. public var cancelButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. public var bookmarkButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. public var resultsListButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } #endif /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. public var searchButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. public var textDidBeginEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. public var textDidEndEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Installs delegate as forwarding delegate on `delegate`. /// Delegate won't be retained. /// /// It enables using normal delegate mechanism with reactive delegate mechanism. /// /// - parameter delegate: Delegate object. /// - returns: Disposable object that can be used to unbind the delegate. public func setDelegate(_ delegate: UISearchBarDelegate) -> Disposable { RxSearchBarDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) } } #endif
d2d15e550a214cb567a9c9f0fea54240
36.955882
156
0.673964
false
false
false
false
AjayOdedara/CoreKitTest
refs/heads/master
Carthage/Checkouts/OAuth2/Sources/Flows/OAuth2CodeGrantBasicAuth.swift
apache-2.0
6
// // OAuth2CodeGrantBasicAuth.swift // OAuth2 // // Created by Pascal Pfiffner on 3/27/15. // Copyright 2015 Pascal Pfiffner // // 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 #if !NO_MODULE_IMPORT import Base #endif /** Enhancing the code grant flow by allowing to specify a specific "Basic xx" authorization header. This class allows you to manually set the "Authorization" header to a given string, as accepted in its `basicToken` property. It will override the superclasses automatic generation of an Authorization header if the client has a clientSecret, so you only need to use this subclass if you need a different header (this is different to version 1.2.3 and earlier of this framework). */ open class OAuth2CodeGrantBasicAuth: OAuth2CodeGrant { /// The full token string to be used in the authorization header. var basicToken: String? /** Adds support to override the basic Authorization header value by specifying: - basic: takes precedence over client_id and client_secret for the token request Authorization header */ override public init(settings: OAuth2JSON) { if let basic = settings["basic"] as? String { basicToken = basic } super.init(settings: settings) } /** Calls super's implementation to obtain a token request, then adds the custom "Basic" authorization header. */ override open func accessTokenRequest(with code: String, params: OAuth2StringDict? = nil) throws -> OAuth2AuthRequest { let req = try super.accessTokenRequest(with: code, params: params) if let basic = basicToken { logger?.debug("OAuth2", msg: "Overriding “Basic” authorization header, as specified during client initialization") req.set(header: "Authorization", to: "Basic \(basic)") } else { logger?.warn("OAuth2", msg: "Using extended code grant, but “basicToken” is not actually specified. Using standard code grant.") } return req } }
16b73862f044037f778e9c4d3b0f7b50
35.757576
133
0.744435
false
false
false
false
SergeMaslyakov/audio-player
refs/heads/master
app/src/controllers/common/XibView.swift
apache-2.0
1
// // XibView.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit class XibView: UIView { var contentView: UIView! override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } func xibSetup() { contentView = loadViewFromNib() contentView.frame = bounds contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] addSubview(contentView) } func loadViewFromNib() -> UIView! { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView return view } }
ecb2f3d319425579d7cbbe1180582f15
22.097561
108
0.636748
false
false
false
false
debugsquad/nubecero
refs/heads/master
nubecero/Firebase/Database/Model/FDatabaseModelAlbum.swift
mit
1
import Foundation class FDatabaseModelAlbum:FDatabaseModel { enum Property:String { case created = "created" case name = "name" } let created:TimeInterval let name:String private let kEmpty:String = "" private let kNoTime:TimeInterval = 0 init(name:String) { created = NSDate().timeIntervalSince1970 self.name = name super.init() } required init(snapshot:Any) { let snapshotDict:[String:Any]? = snapshot as? [String:Any] if let created:TimeInterval = snapshotDict?[Property.created.rawValue] as? TimeInterval { self.created = created } else { self.created = kNoTime } if let name:String = snapshotDict?[Property.name.rawValue] as? String { self.name = name } else { self.name = kEmpty } super.init() } override init() { fatalError() } override func modelJson() -> Any { let json:[String:Any] = [ Property.created.rawValue:created, Property.name.rawValue:name ] return json } }
1fd1b44476527b80e39067883c9f6888
19.31746
95
0.513281
false
false
false
false
QuaereVeritatem/TopHackIncStartup
refs/heads/master
TopHackIncStartUp/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // TopHackIncStartUp // // Created by Robert Martin on 10/3/16. // Copyright © 2016 Robert Martin. All rights reserved. // import UIKit class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var settingsArray: [String] = SettingsData.sharedInstance.settingsChoices override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.tintColor = UIColor.blue } @IBAction func logOutBtn(_ sender: UIBarButtonItem) { print( "logoutBtn called!" ) BackendlessManager.sharedInstance.logoutUser( completion: { self.performSegue(withIdentifier: "gotoLoginFromMenu", sender: sender) //self.dismiss(animated: true, completion: nil) }, error: { message in print("User failed to log out: \(message)") }) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "settingsCell", for: indexPath) as! SettingsTableViewCell let row = (indexPath as NSIndexPath).row cell.settingsLabel.text = settingsArray[row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return settingsArray.count } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
677d9c0422e27203f68645f060c5081a
29.861111
122
0.634113
false
false
false
false
moysklad/ios-remap-sdk
refs/heads/master
Sources/MoyskladiOSRemapSDK/Structs/Account.swift
mit
1
// // Account.swift // MoyskladNew // // Created by Anton Efimenko on 24.10.16. // Copyright © 2016 Andrey Parshakov. All rights reserved. // import Foundation /** Represents Account (related to counterparty or organization). Also see API reference for [ counterparty](https://online.moysklad.ru/api/remap/1.1/doc/index.html#контрагент-счета-контрагента-get) and [ organizaiton](https://online.moysklad.ru/api/remap/1.1/doc/index.html#юрлицо-счета-юрлица-get) */ public class MSAccount : Metable { public var meta: MSMeta public var id : MSID public var info : MSInfo public var accountId: String public var isDefault: Bool public var accountNumber: String public var bankName: String? public var bankLocation: String? public var correspondentAccount: String? public var bic: String? public var agent: MSMeta? public init(meta: MSMeta, id : MSID, info : MSInfo, accountId: String, isDefault: Bool, accountNumber: String, bankName: String?, bankLocation: String?, correspondentAccount: String?, bic: String?, agent: MSMeta?) { self.meta = meta self.id = id self.info = info self.accountId = accountId self.isDefault = isDefault self.accountNumber = accountNumber self.bankName = bankName self.bankLocation = bankLocation self.correspondentAccount = correspondentAccount self.bic = bic self.agent = agent } public func copy() -> MSAccount { return MSAccount(meta: meta, id: id, info: info, accountId: accountId, isDefault: isDefault, accountNumber: accountNumber, bankName: bankName, bankLocation: bankLocation, correspondentAccount: correspondentAccount, bic: bic, agent: agent) } }
0a44fe2997f81debaed0cd91c7a8451d
29.530303
133
0.608437
false
false
false
false
ElectricWizardry/iSub
refs/heads/master
Classes/HelperFunctions.swift
gpl-3.0
2
// // HelperFunctions.swift // iSub // // Created by Benjamin Baron on 1/10/15. // Copyright (c) 2015 Ben Baron. All rights reserved. // import Foundation // MARK: - Section Indexes - public class ISMSSectionIndex { var firstIndex: Int var sectionCount: Int var letter: Character init (firstIndex: Int, sectionCount: Int, letter: Character) { self.firstIndex = firstIndex self.sectionCount = sectionCount self.letter = letter } } public func sectionIndexesForItems(items: [ISMSItem]) -> [ISMSSectionIndex] { func isDigit(c: Character) -> Bool { let cset = NSCharacterSet.decimalDigitCharacterSet() let s = String(c) let ix = s.startIndex let ix2 = s.endIndex let result = s.rangeOfCharacterFromSet(cset, options: nil, range: ix..<ix2) return result != nil } func ignoredArticles() -> [String] { var ignoredArticles = [String]() let database = DatabaseSingleton.sharedInstance() as DatabaseSingleton database.songModelDbQueue.inDatabase({ (db: FMDatabase!) in let result = db.executeQuery("SELECT name FROM ignoredArticles", withArgumentsInArray:[]) while result.next() { ignoredArticles.append(result.stringForColumnIndex(0)) } result.close() }) return ignoredArticles } func nameIgnoringArticles(#name: String, #articles: [String]) -> String { if articles.count > 0 { for article in articles { let articlePlusSpace = article + " " if name.hasPrefix(articlePlusSpace) { let index = advance(name.startIndex, countElements(articlePlusSpace)) return name.substringFromIndex(index) } } } return (name as NSString).stringWithoutIndefiniteArticle() } var sectionIndexes: [ISMSSectionIndex] = [] var lastFirstLetter: Character? = nil let articles = ignoredArticles() var index: Int = 0 var count: Int = 0 for item in items { let name = nameIgnoringArticles(name: item.itemName, articles: articles) var firstLetter = Array(name.uppercaseString)[0] // Sort digits to the end in a single "#" section if isDigit(firstLetter) { firstLetter = "#" } if lastFirstLetter == nil { lastFirstLetter = firstLetter sectionIndexes.append(ISMSSectionIndex(firstIndex: 0, sectionCount: 0, letter: firstLetter)) } if lastFirstLetter != firstLetter { lastFirstLetter = firstLetter if var last = sectionIndexes.last { last.sectionCount = count sectionIndexes.removeLast() sectionIndexes.append(last) } count = 0 sectionIndexes.append(ISMSSectionIndex(firstIndex: index, sectionCount: 0, letter: firstLetter)) } index++ count++ } if var last = sectionIndexes.last { last.sectionCount = count sectionIndexes.removeLast() sectionIndexes.append(last) } return sectionIndexes } // MARK: - Play Songs - private func _playAll(#songs: [ISMSSong], #shuffle: Bool, #playIndex: Int) { // TODO: Implement fatalError("_playAll not implemented yet"); } public func playAll(#songs: [ISMSSong], #playIndex: Int) { _playAll(songs: songs, shuffle: false, playIndex: playIndex) } public func shuffleAll(#songs: [ISMSSong], #playIndex: Int) { _playAll(songs: songs, shuffle: true, playIndex: playIndex) } // MARK: - Strings - public func pluralizedString(#count: Int, #singularNoun: String) -> String { var pluralizedString = "\(count) \(singularNoun)" if count != 1 { pluralizedString += "s" } return pluralizedString }
61fa6dff114c3fff16f2ee3386071f77
28.88806
108
0.599251
false
false
false
false
between40and2/XALG
refs/heads/master
frameworks/Framework-XALG/Tree/Algo/XALG_Algo_BinaryTree_Traversal.swift
mit
1
// // XALG_Algo_BinaryTree_Traversal.swift // XALG // // Created by Juguang Xiao on 02/03/2017. // import Swift class XALG_Algo_BinaryTree_Traversal<TreeType> where TreeType : XALG_ADT_Tree_BinaryTree, TreeType.NodeType == TreeType.NodeType.NodeType { typealias NodeType = TreeType.NodeType typealias XALG_Block_BinaryTreeNode = (NodeType) -> Void enum TraversalOrder { case preorder case inorder case postorder // case levelorder } static func travel__recursive(_ root: NodeType? , order : TraversalOrder = .preorder, visit : XALG_Block_BinaryTreeNode) { guard let n = root else { return } switch order { case .preorder: visit(n) travel__recursive(n.lchild, order: order, visit: visit) travel__recursive(n.rchild, order: order, visit: visit) case .inorder : travel__recursive(n.lchild, order: order, visit: visit) visit(n) travel__recursive(n.rchild, order: order, visit: visit) case .postorder : travel__recursive(n.lchild, order: order, visit: visit) travel__recursive(n.rchild, order: order, visit: visit) visit(n) } } }
44f7700368fe7fbfb0fd92735ca36ba8
23.407407
126
0.582701
false
false
false
false
ostatnicky/kancional-ios
refs/heads/master
Pods/Trackable/Trackable/Trackable.swift
mit
1
// // Trackable.swift // Trackable // // Created by Vojta Stavik (vojtastavik.com) on 06/12/15. // Copyright © 2015 Vojta Stavik. All rights reserved. // import Foundation /** This function is called for the actual event tracking to remote services. Send data to remote servers here. - parameter eventName: Event identifier - parameter trackedProperties: Event properties */ public var trackEventToRemoteServiceClosure : ( (_ eventName: String, _ trackedProperties: [String: AnyObject]) -> Void )? = nil /* Three levels of trackable properties: ----------------------------------------- 3. high - on the event level -> by adding properties to trackEvent function 2. middle - on the instance level -> by calling setupTrackableChain(properties, parent: Trackable?) on the instance 1. low - on the class level -> by implementing trackableProperties computed variable Higher level property overrides lower level property with the same name. */ /** Conformance to this protocol allow a class to track events on *self* */ public protocol TrackableClass : class { var trackedProperties: Set<TrackedProperty> { get } } // Default implementation of Trackable. We don't want to return nil // as a default value, because we use nil internaly to identify released objects public extension TrackableClass { var trackedProperties: Set<TrackedProperty> { return [] } } // ----------------------------- // Track event functions public extension TrackableClass { /** Track event on *self* with properties. - parameter event: Event identifier - parameter trackedProperties: Properties added to the event */ public func track(_ event: Event, trackedProperties: Set<TrackedProperty>? = nil) { let trackClosure: () -> Void = { if let ownLink = ChainLink.responsibilityChainTable[self.uniqueIdentifier] { ownLink.track(event, trackedProperties: trackedProperties ?? []) } else { // we don't have own link in the chain. Just update properties and track the event var properties = self.trackedProperties if let eventProperties = trackedProperties { properties.updateValuesFrom(eventProperties) } trackEventToRemoteServiceClosure?(event.description, properties.dictionaryRepresentation) } } if Thread.isMainThread { trackClosure() } else { DispatchQueue.main.async { trackClosure() } } } } // ----------------------------- // Setup functions public extension TrackableClass { /** Setup *self* so it can be used as a part of a trackable chain. - parameter trackedProperties: Properties which will be added to all events tracked on self - parameter parent: Trackable parent for *self*. Events are not tracked directly but they are resend to parent. */ public func setupTrackableChain(trackedProperties: Set<TrackedProperty> = [], parent: TrackableClass? = nil) { let setupClosure: () -> Void = { var parentLink: ChainLink? = nil if let identifier = parent?.uniqueIdentifier { if let link = ChainLink.responsibilityChainTable[identifier] { // we have existing link for parent parentLink = link } else { // we create new link for paret weak var weakParent = parent parentLink = ChainLink.tracker(instanceProperties: [], classProperties: { weakParent?.trackedProperties }) ChainLink.responsibilityChainTable[identifier] = parentLink } } let newLink = ChainLink.chainer(instanceProperties: trackedProperties, classProperties: { [weak self] in self?.trackedProperties }, parent: parentLink) ChainLink.responsibilityChainTable[self.uniqueIdentifier] = newLink } if Thread.isMainThread { setupClosure() } else { DispatchQueue.main.async { setupClosure() } } } } extension TrackableClass { var uniqueIdentifier: ObjectIdentifier { return ObjectIdentifier(self) } }
58f0356c998b52de616115d34cb36274
36.598291
163
0.621732
false
false
false
false
Karumi/KataSuperHeroesIOS
refs/heads/master
KataSuperHeroes/SuperHeroDetailPresenter.swift
apache-2.0
1
import Combine import Foundation class SuperHeroDetailPresenter { private weak var ui: SuperHeroDetailUI? private let superHeroName: String private let getSuperHeroByName: GetSuperHeroByName private var subscriptions = Set<AnyCancellable>() init(ui: SuperHeroDetailUI, superHeroName: String, getSuperHeroByName: GetSuperHeroByName) { self.ui = ui self.superHeroName = superHeroName self.getSuperHeroByName = getSuperHeroByName } func viewDidLoad() { ui?.title = superHeroName ui?.showLoader() getSuperHeroByName .execute(superHeroName) .sink { superHero in self.ui?.hideLoader() self.ui?.show(superHero: superHero) } .store(in: &subscriptions) } } protocol SuperHeroDetailUI: AnyObject { func showLoader() func hideLoader() var title: String? { get set } func show(superHero: SuperHero?) }
572b74e3356288427d52ed8e7ae3f4cf
27.529412
96
0.653608
false
false
false
false
mspvirajpatel/SwiftyBase
refs/heads/master
SwiftyBase/Classes/Controller/SideMenu/SideMenuManager.swift
mit
1
// // SideMenuManager.swift // Pods // // Created by MacMini-2 on 30/08/17. // // /* Example usage: // Define the menus SideMenuManager.menuLeftNavigationController = storyboard!.instantiateViewController(withIdentifier: "LeftMenuNavigationController") as? UISideMenuNavigationController SideMenuManager.menuRightNavigationController = storyboard!.instantiateViewController(withIdentifier: "RightMenuNavigationController") as? UISideMenuNavigationController // Enable gestures. The left and/or right menus must be set up above for these to work. // Note that these continue to work on the Navigation Controller independent of the View Controller it displays! SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar) SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view) */ open class SideMenuManager: NSObject { @objc public enum MenuPushStyle: Int { case defaultBehavior, popWhenPossible, replace, preserve, preserveAndHideBackButton, subMenu } @objc public enum MenuPresentMode: Int { case menuSlideIn, viewSlideOut, viewSlideInOut, menuDissolveIn } // Bounds which has been allocated for the app on the whole device screen internal static var appScreenRect: CGRect { let appWindowRect = UIApplication.shared.keyWindow?.bounds ?? UIWindow().bounds return appWindowRect } /** The push style of the menu. There are six modes in MenuPushStyle: - defaultBehavior: The view controller is pushed onto the stack. - popWhenPossible: If a view controller already in the stack is of the same class as the pushed view controller, the stack is instead popped back to the existing view controller. This behavior can help users from getting lost in a deep navigation stack. - preserve: If a view controller already in the stack is of the same class as the pushed view controller, the existing view controller is pushed to the end of the stack. This behavior is similar to a UITabBarController. - preserveAndHideBackButton: Same as .preserve and back buttons are automatically hidden. - replace: Any existing view controllers are released from the stack and replaced with the pushed view controller. Back buttons are automatically hidden. This behavior is ideal if view controllers require a lot of memory or their state doesn't need to be preserved.. - subMenu: Unlike all other behaviors that push using the menu's presentingViewController, this behavior pushes view controllers within the menu. Use this behavior if you want to display a sub menu. */ public static var menuPushStyle: MenuPushStyle = .defaultBehavior /** The presentation mode of the menu. There are four modes in MenuPresentMode: - menuSlideIn: Menu slides in over of the existing view. - viewSlideOut: The existing view slides out to reveal the menu. - viewSlideInOut: The existing view slides out while the menu slides in. - menuDissolveIn: The menu dissolves in over the existing view controller. */ public static var menuPresentMode: MenuPresentMode = .viewSlideOut /// Prevents the same view controller (or a view controller of the same class) from being pushed more than once. Defaults to true. public static var menuAllowPushOfSameClassTwice = true /// Width of the menu when presented on screen, showing the existing view controller in the remaining space. Default is 75% of the screen width. public static var menuWidth: CGFloat = max(round(min((appScreenRect.width), (appScreenRect.height)) * 0.75), 240) /// Duration of the animation when the menu is presented without gestures. Default is 0.35 seconds. public static var menuAnimationPresentDuration: Double = 0.35 /// Duration of the animation when the menu is dismissed without gestures. Default is 0.35 seconds. public static var menuAnimationDismissDuration: Double = 0.35 /// Duration of the remaining animation when the menu is partially dismissed with gestures. Default is 0.2 seconds. public static var menuAnimationCompleteGestureDuration: Double = 0.20 /// Amount to fade the existing view controller when the menu is presented. Default is 0 for no fade. Set to 1 to fade completely. public static var menuAnimationFadeStrength: CGFloat = 0 /// The amount to scale the existing view controller or the menu view controller depending on the `menuPresentMode`. Default is 1 for no scaling. Less than 1 will shrink, greater than 1 will grow. public static var menuAnimationTransformScaleFactor: CGFloat = 1 /// The background color behind menu animations. Depending on the animation settings this may not be visible. If `menuFadeStatusBar` is true, this color is used to fade it. Default is black. public static var menuAnimationBackgroundColor: UIColor? /// The shadow opacity around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 0.5 for 50% opacity. public static var menuShadowOpacity: Float = 0.5 /// The shadow color around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is black. public static var menuShadowColor = UIColor.black /// The radius of the shadow around the menu view controller or existing view controller depending on the `menuPresentMode`. Default is 5. public static var menuShadowRadius: CGFloat = 5 /// Enable or disable interaction with the presenting view controller while the menu is displayed. Enabling may make it difficult to dismiss the menu or cause exceptions if the user tries to present and already presented menu. Default is false. public static var menuPresentingViewControllerUserInteractionEnabled: Bool = false /// The strength of the parallax effect on the existing view controller. Does not apply to `menuPresentMode` when set to `ViewSlideOut`. Default is 0. public static var menuParallaxStrength: Int = 0 /// Draws the `menuAnimationBackgroundColor` behind the status bar. Default is true. public static var menuFadeStatusBar = true /// The animation options when a menu is displayed. Ignored when displayed with a gesture. public static var menuAnimationOptions: UIView.AnimationOptions = .curveEaseInOut /// The animation spring damping when a menu is displayed. Ignored when displayed with a gesture. public static var menuAnimationUsingSpringWithDamping: CGFloat = 1 /// The animation initial spring velocity when a menu is displayed. Ignored when displayed with a gesture. public static var menuAnimationInitialSpringVelocity: CGFloat = 1 /// -Warning: Deprecated. Use `menuPushStyle = .subMenu` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .subMenu` instead.") public static var menuAllowSubmenus: Bool { get { return menuPushStyle == .subMenu } set { if newValue { menuPushStyle = .subMenu } } } /// -Warning: Deprecated. Use `menuPushStyle = .popWhenPossible` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .popWhenPossible` instead.") public static var menuAllowPopIfPossible: Bool { get { return menuPushStyle == .popWhenPossible } set { if newValue { menuPushStyle = .popWhenPossible } } } /// -Warning: Deprecated. Use `menuPushStyle = .replace` instead. @available(*, deprecated, renamed: "menuPushStyle", message: "Use `menuPushStyle = .replace` instead.") public static var menuReplaceOnPush: Bool { get { return menuPushStyle == .replace } set { if newValue { menuPushStyle = .replace } } } /// -Warning: Deprecated. Use `menuAnimationTransformScaleFactor` instead. @available(*, deprecated, renamed: "menuAnimationTransformScaleFactor") public static var menuAnimationShrinkStrength: CGFloat { get { return menuAnimationTransformScaleFactor } set { menuAnimationTransformScaleFactor = newValue } } // prevent instantiation fileprivate override init() { } /** The blur effect style of the menu if the menu's root view controller is a UITableViewController or UICollectionViewController. - Note: If you want cells in a UITableViewController menu to show vibrancy, make them a subclass of UITableViewVibrantCell. */ public static var menuBlurEffectStyle: UIBlurEffect.Style? { didSet { if oldValue != menuBlurEffectStyle { updateMenuBlurIfNecessary() } } } /// The left menu. public static var menuLeftNavigationController: UISideMenuNavigationController? { willSet { if menuLeftNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuLeftNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuLeftNavigationController cannot be modified while it's presented.") menuLeftNavigationController = oldValue return } setupNavigationController(menuLeftNavigationController, leftSide: true) } } /// The right menu. public static var menuRightNavigationController: UISideMenuNavigationController? { willSet { if menuRightNavigationController?.presentingViewController == nil { removeMenuBlurForMenu(menuRightNavigationController) } } didSet { guard oldValue?.presentingViewController == nil else { print("SideMenu Warning: menuRightNavigationController cannot be modified while it's presented.") menuRightNavigationController = oldValue return } setupNavigationController(menuRightNavigationController, leftSide: false) } } /// The left menu swipe to dismiss gesture. public static weak var menuLeftSwipeToDismissGesture: UIPanGestureRecognizer? { didSet { oldValue?.view?.removeGestureRecognizer(oldValue!) setupGesture(gesture: menuLeftSwipeToDismissGesture) } } /// The right menu swipe to dismiss gesture. public static weak var menuRightSwipeToDismissGesture: UIPanGestureRecognizer? { didSet { oldValue?.view?.removeGestureRecognizer(oldValue!) setupGesture(gesture: menuRightSwipeToDismissGesture) } } fileprivate class func setupGesture(gesture: UIPanGestureRecognizer?) { guard let gesture = gesture else { return } gesture.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handleHideMenuPan(_:))) } fileprivate class func setupNavigationController(_ forMenu: UISideMenuNavigationController?, leftSide: Bool) { guard let forMenu = forMenu else { return } if menuEnableSwipeGestures { let exitPanGesture = UIPanGestureRecognizer() forMenu.view.addGestureRecognizer(exitPanGesture) if leftSide { menuLeftSwipeToDismissGesture = exitPanGesture } else { menuRightSwipeToDismissGesture = exitPanGesture } } forMenu.transitioningDelegate = SideMenuTransition.singleton forMenu.modalPresentationStyle = .overFullScreen forMenu.leftSide = leftSide updateMenuBlurIfNecessary() } /// Enable or disable gestures that would swipe to dismiss the menu. Default is true. public static var menuEnableSwipeGestures: Bool = true { didSet { menuLeftSwipeToDismissGesture?.view?.removeGestureRecognizer(menuLeftSwipeToDismissGesture!) menuRightSwipeToDismissGesture?.view?.removeGestureRecognizer(menuRightSwipeToDismissGesture!) setupNavigationController(menuLeftNavigationController, leftSide: true) setupNavigationController(menuRightNavigationController, leftSide: false) } } fileprivate class func updateMenuBlurIfNecessary() { let menuBlurBlock = { (forMenu: UISideMenuNavigationController?) in if let forMenu = forMenu { setupMenuBlurForMenu(forMenu) } } menuBlurBlock(menuLeftNavigationController) menuBlurBlock(menuRightNavigationController) } fileprivate class func setupMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { removeMenuBlurForMenu(forMenu) guard let forMenu = forMenu, let menuBlurEffectStyle = menuBlurEffectStyle, let view = forMenu.visibleViewController?.view , !UIAccessibility.isReduceTransparencyEnabled else { return } if forMenu.originalMenuBackgroundColor == nil { forMenu.originalMenuBackgroundColor = view.backgroundColor } let blurEffect = UIBlurEffect(style: menuBlurEffectStyle) let blurView = UIVisualEffectView(effect: blurEffect) view.backgroundColor = UIColor.clear if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = blurView tableViewController.tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect) tableViewController.tableView.reloadData() } else { blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = view.bounds view.insertSubview(blurView, at: 0) } } fileprivate class func removeMenuBlurForMenu(_ forMenu: UISideMenuNavigationController?) { guard let forMenu = forMenu, let originalMenuBackgroundColor = forMenu.originalMenuBackgroundColor, let view = forMenu.visibleViewController?.view else { return } view.backgroundColor = originalMenuBackgroundColor forMenu.originalMenuBackgroundColor = nil if let tableViewController = forMenu.visibleViewController as? UITableViewController { tableViewController.tableView.backgroundView = nil tableViewController.tableView.separatorEffect = nil tableViewController.tableView.reloadData() } else if let blurView = view.subviews[0] as? UIVisualEffectView { blurView.removeFromSuperview() } } /** Adds screen edge gestures to a view to present a menu. - Parameter toView: The view to add gestures to. - Parameter forMenu: The menu (left or right) you want to add a gesture for. If unspecified, gestures will be added for both sides. - Returns: The array of screen edge gestures added to `toView`. */ @discardableResult open class func menuAddScreenEdgePanGesturesToPresent(toView: UIView, forMenu: UIRectEdge? = nil) -> [UIScreenEdgePanGestureRecognizer] { var array = [UIScreenEdgePanGestureRecognizer]() if forMenu != .right { let leftScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() leftScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuLeftScreenEdge(_:))) leftScreenEdgeGestureRecognizer.edges = .left leftScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(leftScreenEdgeGestureRecognizer) array.append(leftScreenEdgeGestureRecognizer) if SideMenuManager.menuLeftNavigationController == nil { print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the left side was called before menuLeftNavigationController has been defined. The gesture will not work without a menu.") } } if forMenu != .left { let rightScreenEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer() rightScreenEdgeGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuRightScreenEdge(_:))) rightScreenEdgeGestureRecognizer.edges = .right rightScreenEdgeGestureRecognizer.cancelsTouchesInView = true toView.addGestureRecognizer(rightScreenEdgeGestureRecognizer) array.append(rightScreenEdgeGestureRecognizer) if SideMenuManager.menuRightNavigationController == nil { print("SideMenu Warning: menuAddScreenEdgePanGesturesToPresent for the right side was called before menuRightNavigationController has been defined. The gesture will not work without a menu.") } } return array } /** Adds a pan edge gesture to a view to present menus. - Parameter toView: The view to add a pan gesture to. - Returns: The pan gesture added to `toView`. */ @discardableResult open class func menuAddPanGestureToPresent(toView: UIView) -> UIPanGestureRecognizer { let panGestureRecognizer = UIPanGestureRecognizer() panGestureRecognizer.addTarget(SideMenuTransition.self, action: #selector(SideMenuTransition.handlePresentMenuPan(_:))) toView.addGestureRecognizer(panGestureRecognizer) if SideMenuManager.menuLeftNavigationController ?? SideMenuManager.menuRightNavigationController == nil { print("SideMenu Warning: menuAddPanGestureToPresent called before menuLeftNavigationController or menuRightNavigationController have been defined. Gestures will not work without a menu.") } return panGestureRecognizer } }
a4728f2c4ed174f30a7ff68730eafa47
45.820051
271
0.70241
false
false
false
false
GitHubCha2016/ZLSwiftFM
refs/heads/master
ZLSwiftFM/Pods/Kingfisher/Sources/Image.swift
mit
1
// // Image.swift // Kingfisher // // Created by Wei Wang on 16/1/6. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? private var animatedImageDataKey: Void? #endif import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: - Image Properties extension Kingfisher where Base: Image { #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CGFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { return objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: - Image Conversion extension Kingfisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale. */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // No need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: - Image Representation extension Kingfisher where Base: Image { // MARK: - PNG func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: - JPEG func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF func gifRepresentation() -> Data? { #if os(macOS) return gifRepresentation(duration: 0.0, repeatCount: 0) #else return animatedImageData #endif } #if os(macOS) func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? { guard let images = images else { return nil } let frameCount = images.count let gifDuration = duration <= 0.0 ? duration / Double(frameCount) : duration / Double(frameCount) let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { return nil } CGImageDestinationSetProperties(destination, imageProperties as CFDictionary) for image in images { CGImageDestinationAddImage(destination, image.kf.cgImage!, frameProperties as CFDictionary) } return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil } #endif } // MARK: - Create images from data extension Kingfisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image? { func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { //Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary) -> Double { let gifDefaultFrameDuration = 0.100 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil), let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else { return nil } gifDuration += frameDuration(from: gifInfo) } images.append(Kingfisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil)) } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration return image #else if preloadAll { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Kingfisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) image?.kf.animatedImageData = data return image } else { let image = Image(data: data) image?.kf.animatedImageData = data image?.kf.imageSource = ImageSource(ref: imageSource) return image } #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = Kingfisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // MARK: - Image Transforming extension Kingfisher where Base: Image { // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. public func image(withRoundRadius radius: CGFloat, fit size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Round corder image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) let path = NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius) path.windingRule = .evenOddWindingRule path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } let path = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).cgPath context.addPath(path) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIViewContentMode) -> Image { switch contentMode { case .scaleAspectFit: let newSize = self.size.kf.constrained(size) return resize(to: newSize) case .scaleAspectFill: let newSize = self.size.kf.filling(size) return resize(to: newSize) default: return resize(to: size) } } #endif // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. public func resize(to size: CGSize) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: size) { #if os(macOS) base.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. public func blurred(withRadius radius: CGFloat) -> Image { #if os(watchOS) return base #else guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = max(radius, 2.0) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. var targetRadius = floor((Double(s * 3.0) * sqrt(2 * Double.pi) / 4.0 + 0.5)) if targetRadius.isEven { targetRadius += 1 } let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) let inDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) inDataPointer.initialize(to: 0) defer { inDataPointer.deinitialize() inDataPointer.deallocate(capacity: rowBytes * Int(h)) } let bitmapInfo = cgImage.bitmapInfo.fixed guard let context = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) var inBuffer = vImage_Buffer(data: inDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) let outDataPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: rowBytes * Int(h)) outDataPointer.initialize(to: 0) defer { outDataPointer.deinitialize() outDataPointer.deallocate(capacity: rowBytes * Int(h)) } var outBuffer = vImage_Buffer(data: outDataPointer, height: vImagePixelCount(h), width: vImagePixelCount(w), rowBytes: rowBytes) for _ in 0 ..< iterations { vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, vImage_Flags(kvImageEdgeExtend)) (inBuffer, outBuffer) = (outBuffer, inBuffer) } guard let outContext = CGContext(data: inDataPointer, width: w, height: h, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: rowBytes, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage #endif } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(cgImage: cgImage, to: rect.size) { #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() NSRectFillUsingOperation(rect, .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl(brightness, contrast, saturation, inputEV)) #endif } } // MARK: - Decode extension Kingfisher where Base: Image { var decoded: Image? { return decoded(scale: scale) } func decoded(scale: CGFloat) -> Image { // prevent animated image (GIF) lose it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = self.cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = imageRef.bitmapInfo.fixed guard let context = CGContext(data: nil, width: imageRef.width, height: imageRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) else { assertionFailure("[Kingfisher] Decoding fails to create a valid context.") return base } let rect = CGRect(x: 0, y: 0, width: imageRef.width, height: imageRef.height) context.draw(imageRef, in: rect) let decompressedImageRef = context.makeImage() return Kingfisher<Image>.image(cgImage: decompressedImageRef!, scale: scale, refImage: base) } } /// Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingfisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } } public struct CGSizeProxy { fileprivate let base: CGSize init(proxy: CGSize) { base = proxy } } extension CGSize: KingfisherCompatible { public typealias CompatibleType = CGSizeProxy public var kf: CGSizeProxy { return CGSizeProxy(proxy: self) } } extension CGSizeProxy { func constrained(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } func filling(_ size: CGSize) -> CGSize { let aspectWidth = round(aspectRatio * size.height) let aspectHeight = round(size.width / aspectRatio) return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height) } private var aspectRatio: CGFloat { return base.height == 0.0 ? 1.0 : base.width / base.height } } extension CGBitmapInfo { var fixed: CGBitmapInfo { var fixed = self let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } return fixed } } extension Kingfisher where Base: Image { func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return base } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension CGContext { static func createARGBContext(from imageRef: CGImage) -> CGContext? { let w = imageRef.width let h = imageRef.height let bytesPerRow = w * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let data = malloc(bytesPerRow * h) defer { free(data) } let bitmapInfo = imageRef.bitmapInfo.fixed // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here. return CGContext(data: data, width: w, height: h, bitsPerComponent: imageRef.bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) } } extension Double { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Deprecated. Only for back compatibility. extension Image { /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.normalized` instead.", renamed: "kf.normalized") public func kf_normalized() -> Image { return kf.normalized } // MARK: - Round Corner /// Create a round corner image based on `self`. /// /// - parameter radius: The round corner radius of creating image. /// - parameter size: The target size of creating image. /// - parameter scale: The image scale of creating image. /// /// - returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.image(withRoundRadius:fit:scale:)` instead.", renamed: "kf.image") public func kf_image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return kf.image(withRoundRadius: radius, fit: size) } // MARK: - Resize /// Resize `self` to an image of new size. /// /// - parameter size: The target size. /// /// - returns: An image with new size. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.resize(to:)` instead.", renamed: "kf.resize") public func kf_resize(to size: CGSize) -> Image { return kf.resize(to: size) } // MARK: - Blur /// Create an image with blur effect based on `self`. /// /// - parameter radius: The blur radius should be used when creating blue. /// /// - returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.blurred(withRadius:)` instead.", renamed: "kf.blurred") public func kf_blurred(withRadius radius: CGFloat) -> Image { return kf.blurred(withRadius: radius) } // MARK: - Overlay /// Create an image from `self` with a color overlay layer. /// /// - parameter color: The color should be use to overlay. /// - parameter fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. /// /// - returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.overlaying(with:fraction:)` instead.", renamed: "kf.overlaying") public func kf_overlaying(with color: Color, fraction: CGFloat) -> Image { return kf.overlaying(with: color, fraction: fraction) } // MARK: - Tint /// Create an image from `self` with a color tint. /// /// - parameter color: The color should be used to tint `self` /// /// - returns: An image with a color tint applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.tinted(with:)` instead.", renamed: "kf.tinted") public func kf_tinted(with color: Color) -> Image { return kf.tinted(with: color) } // MARK: - Color Control /// Create an image from `self` with color control. /// /// - parameter brightness: Brightness changing to image. /// - parameter contrast: Contrast changing to image. /// - parameter saturation: Saturation changing to image. /// - parameter inputEV: InputEV changing to image. /// /// - returns: An image with color control applied. @available(*, deprecated, message: "Extensions directly on Image are deprecated. Use `kf.adjusted` instead.", renamed: "kf.adjusted") public func kf_adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { return kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) } } extension Kingfisher where Base: Image { @available(*, deprecated, message: "`scale` is not used. Use the version without scale instead. (Remove the `scale` argument)") public func image(withRoundRadius radius: CGFloat, fit size: CGSize, scale: CGFloat) -> Image { return image(withRoundRadius: radius, fit: size) } }
c0ebe9764431ac7a662d11c95d17c178
34.994715
192
0.584183
false
false
false
false
sarvex/SwiftRecepies
refs/heads/master
Basics/Displaying Alerts and Action Sheets/Displaying Alerts and Action Sheets/ViewController.swift
isc
1
// // ViewController.swift // Displaying Alerts and Action Sheets // // Created by Vandad Nahavandipoor on 6/27/14. // Copyright (c) 2014 Pixolity Ltd. All rights reserved. // // These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook // If you use these solutions in your apps, you can give attribution to // Vandad Nahavandipoor for his work. Feel free to visit my blog // at http://vandadnp.wordpress.com for daily tips and tricks in Swift // and Objective-C and various other programming languages. // // You can purchase "iOS 8 Swift Programming Cookbook" from // the following URL: // http://shop.oreilly.com/product/0636920034254.do // // If you have any questions, you can contact me directly // at [email protected] // Similarly, if you find an error in these sample codes, simply // report them to O'Reilly at the following URL: // http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254 /* 1 */ //import UIKit // //class ViewController: UIViewController { // // var controller:UIAlertController? // //} /* 2 */ //import UIKit // //class ViewController: UIViewController { // // var controller:UIAlertController? // // override func viewDidLoad() { // super.viewDidLoad() // // controller = UIAlertController(title: "Title", // message: "Message", // preferredStyle: .Alert) // // let action = UIAlertAction(title: "Done", // style: UIAlertActionStyle.Default, // handler: {(paramAction:UIAlertAction!) in // println("The Done button was tapped") // }) // // controller!.addAction(action) // // } // // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // self.presentViewController(controller!, animated: true, completion: nil) // } // //} /* 3 */ import UIKit class ViewController: UIViewController { var controller:UIAlertController? override func viewDidLoad() { super.viewDidLoad() controller = UIAlertController(title: "Please enter your username", message: "This is usually 10 characters long", preferredStyle: .Alert) let action = UIAlertAction(title: "Next", style: UIAlertActionStyle.Default, handler: {[weak self] (paramAction:UIAlertAction!) in if let textFields = self!.controller?.textFields{ let theTextFields = textFields as! [UITextField] let userName = theTextFields[0].text println("Your username is \(userName)") } }) controller!.addAction(action) controller!.addTextFieldWithConfigurationHandler( {(textField: UITextField!) in textField.placeholder = "XXXXXXXXXX" }) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.presentViewController(controller!, animated: true, completion: nil) } } /* 4 */ //import UIKit // //class ViewController: UIViewController { // // var controller:UIAlertController? // // override func viewDidLoad() { // super.viewDidLoad() // // controller = UIAlertController( // title: "Choose how you would like to share this photo", // message: "You cannot bring back a deleted photo", // preferredStyle: .ActionSheet) // // let actionEmail = UIAlertAction(title: "Via email", // style: UIAlertActionStyle.Default, // handler: {(paramAction:UIAlertAction!) in // /* Send the photo via email */ // }) // // let actionImessage = UIAlertAction(title: "Via iMessage", // style: UIAlertActionStyle.Default, // handler: {(paramAction:UIAlertAction!) in // /* Send the photo via iMessage */ // }) // // let actionDelete = UIAlertAction(title: "Delete photo", // style: UIAlertActionStyle.Destructive, // handler: {(paramAction:UIAlertAction!) in // /* Delete the photo here */ // }) // // controller!.addAction(actionEmail) // controller!.addAction(actionImessage) // controller!.addAction(actionDelete) // // } // // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // self.presentViewController(controller!, animated: true, completion: nil) // } // //}
0999082882a8e78e55f5af499c74920c
27.065789
83
0.654243
false
false
false
false
s0mmer/TodaysReactiveMenu
refs/heads/develop
TodaysReactiveMenu/AppDelegate.swift
mit
1
// // AppDelegate.swift // TodaysReactiveMenu // // Created by Steffen Damtoft Sommer on 24/05/15. // Copyright (c) 2015 steffendsommer. All rights reserved. // import UIKit import Fabric import WatchConnectivity import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let menuAPI = TodaysMenuAPI() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Setup Crashlytics Fabric.with([Crashlytics.self]) // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() // Setup initial view window = UIWindow(frame: UIScreen.mainScreen().bounds) if let window = window { window.backgroundColor = UIColor.whiteColor() window.rootViewController = TodaysMenuViewController(viewModel: TodaysMenuViewModel(menuAPI: self.menuAPI)) window.makeKeyAndVisible() } return true } func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" ) let deviceTokenString: String = ( deviceToken.description as NSString ) .stringByTrimmingCharactersInSet( characterSet ) .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String self.menuAPI.submitPushToken(deviceTokenString) .startWithFailed { error in print("Failed to register push token.") } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print(error.localizedDescription) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { // Push received while being in background mode. Fetch the menu so it's loaded when the app gets opened. Menu.fetchTodaysMenuFromCacheOrRemote(self.menuAPI) .start { event in switch event { case .Next(_): completionHandler(UIBackgroundFetchResult.NewData) break default: completionHandler(UIBackgroundFetchResult.NoData) break } } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
4fa8c68841af28b6386ff2086c1883b1
44.63
285
0.685514
false
false
false
false
kdawgwilk/vapor
refs/heads/master
Sources/Vapor/Multipart/Request+Multipart.swift
mit
1
extension Request { /** Multipart encoded request data sent using the `multipart/form-data...` header. Used by web browsers to send files. */ public var multipart: [String: Multipart]? { if let existing = storage["multipart"] as? [String: Multipart]? { return existing } else if let type = headers["Content-Type"] where type.contains("multipart/form-data") { guard case let .data(body) = body else { return nil } guard let boundary = try? Multipart.parseBoundary(contentType: type) else { return nil } let multipart = Multipart.parse(Data(body), boundary: boundary) storage["multipart"] = multipart return multipart } else { return nil } } }
ece50ffc8f53967ad678010357258f05
37.047619
100
0.59199
false
false
false
false
XJAlex/DanTang
refs/heads/master
DanTang/DanTang/Classes/Base/Tools/XJConst.swift
mit
1
// // XJConst.swift // DanTang // // Created by qxj on 2017/3/7. // Copyright © 2017年 QinXJ. All rights reserved. // import UIKit enum YMTopicType: Int { /// 精选 case selection = 4 /// 美食 case food = 14 /// 家居 case household = 16 /// 数码 case digital = 17 /// 美物 case goodThing = 13 /// 杂货 case grocery = 22 } enum YMShareButtonType: Int { /// 微信朋友圈 case weChatTimeline = 0 /// 微信好友 case weChatSession = 1 /// 微博 case weibo = 2 /// QQ 空间 case qZone = 3 /// QQ 好友 case qqFriends = 4 /// 复制链接 case copyLink = 5 } enum YMOtherLoginButtonType: Int { /// 微博 case weiboLogin = 100 /// 微信 case weChatLogin = 101 /// QQ case qqLogin = 102 } /// 服务器地址 let BASE_URL = "http://api.dantangapp.com/" /// 第一次启动 let YMFirstLaunch = "firstLaunch" /// 是否登录 let isLogin = "isLogin" /// code 码 200 操作成功 let RETURN_OK = 200 /// 间距 let kMargin: CGFloat = 10.0 /// 圆角 let kCornerRadius: CGFloat = 5.0 /// 线宽 let klineWidth: CGFloat = 1.0 /// 首页顶部标签指示条的高度 let kIndicatorViewH: CGFloat = 2.0 /// 新特性界面图片数量 let kNewFeatureCount = 4 /// 顶部标题的高度 let kTitlesViewH: CGFloat = 35 /// 顶部标题的y let kTitlesViewY: CGFloat = 64 /// 动画时长 let kAnimationDuration = 0.25 /// 屏幕的宽 let SCREENW = UIScreen.main.bounds.size.width /// 屏幕的高 let SCREENH = UIScreen.main.bounds.size.height /// 分类界面 顶部 item 的高 let kitemH: CGFloat = 75 /// 分类界面 顶部 item 的宽 let kitemW: CGFloat = 150 /// 我的界面头部图像的高度 let kYMMineHeaderImageHeight: CGFloat = 200 // 分享按钮背景高度 let kTopViewH: CGFloat = 230 /// RGBA的颜色设置 func XJColor(_ r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor { return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a) } /// 背景灰色 func XJGlobalColor() -> UIColor { return XJColor(240, g: 240, b: 240, a: 1) } /// 红色 func XJGlobalRedColor() -> UIColor { return XJColor(245, g: 80, b: 83, a: 1.0) } /// iPhone 5 let isIPhone5 = SCREENH == 568 ? true : false /// iPhone 6 let isIPhone6 = SCREENH == 667 ? true : false /// iPhone 6P let isIPhone6P = SCREENH == 736 ? true : false
17254ad83fceb3b150a81b8d6c62d54e
18.072727
79
0.622498
false
false
false
false
yangligeryang/codepath
refs/heads/master
assignments/Canvas/Canvas/CanvasViewController.swift
apache-2.0
1
// // CanvasViewController.swift // Canvas // // Created by Yang Yang on 10/27/16. // Copyright © 2016 Yang Yang. All rights reserved. // import UIKit class CanvasViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var trayView: UIView! @IBOutlet weak var trayArrow: UIImageView! var trayOriginalCenter: CGPoint! var trayTop: CGFloat! var trayOriginalTop: CGFloat! var trayDownOffset: CGFloat! var trayUp: CGPoint! var trayDown: CGPoint! var newlyCreatedFace: UIImageView! var newlyCreatedFaceOriginalCenter: CGPoint! override func viewDidLoad() { super.viewDidLoad() trayDownOffset = 178 trayUp = trayView.center trayDown = CGPoint(x: trayView.center.x ,y: trayView.center.y + trayDownOffset) trayOriginalTop = trayView.frame.origin.y trayTop = trayOriginalTop } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func didPanNewFace(sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) let location = sender.location(in: view) newlyCreatedFace = sender.view as! UIImageView if sender.state == .began { newlyCreatedFaceOriginalCenter = newlyCreatedFace.center UIView.animate(withDuration: 0.2, animations: { self.newlyCreatedFace.transform = CGAffineTransform(scaleX: 2, y: 2) }) } else if sender.state == .changed { newlyCreatedFace.center = CGPoint(x: newlyCreatedFaceOriginalCenter.x + translation.x, y: newlyCreatedFaceOriginalCenter.y + translation.y) } else if sender.state == .ended { if location.y > CGFloat(trayTop) { newlyCreatedFace.center = newlyCreatedFaceOriginalCenter self.newlyCreatedFace.transform = CGAffineTransform(scaleX: 1.6, y: 1.6) } else { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 12, initialSpringVelocity: 24, options: [], animations: { self.newlyCreatedFace.transform = CGAffineTransform(scaleX: 1.6, y: 1.6) }, completion: { (Bool) in }) } } } func didPinchNewFace(sender: UIPinchGestureRecognizer) { let scale = sender.scale let faceView = sender.view as! UIImageView faceView.transform = faceView.transform.scaledBy(x: scale, y: scale) sender.scale = 1 } func didRotateNewFace(sender: UIRotationGestureRecognizer) { let rotation = sender.rotation let faceView = sender.view as! UIImageView faceView.transform = faceView.transform.rotated(by: rotation) sender.rotation = 0 } func didTapNewFace(sender: UITapGestureRecognizer) { let faceView = sender.view as! UIImageView faceView.removeFromSuperview() } @IBAction func didPanTray(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) let velocity = sender.velocity(in: view) if sender.state == .began { trayOriginalCenter = trayView.center } else if sender.state == .changed { var translationY: CGFloat! if trayView.center.y < trayUp.y { translationY = trayUp.y + translation.y / 10 } else { translationY = trayOriginalCenter.y + translation.y } trayView.center = CGPoint(x: trayOriginalCenter.x, y: translationY) } else if sender.state == .ended { if velocity.y > 0 { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 8, options: [], animations: { self.trayView.center = self.trayDown }, completion: { (Bool) in }) UIView.animate(withDuration: 0.4, animations: { self.trayArrow.transform = self.trayArrow.transform.rotated(by: CGFloat(M_PI)) }) } else { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 8, options: [], animations: { self.trayView.center = self.trayUp }, completion: { (Bool) in }) UIView.animate(withDuration: 0.4, animations: { self.trayArrow.transform = CGAffineTransform.identity }) } trayTop = trayView.frame.origin.y } } @IBAction func didPanFace(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) let imageView = sender.view as! UIImageView let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPanNewFace(sender:))) let pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(didPinchNewFace(sender:))) let rotateGestureRecognizer = UIRotationGestureRecognizer(target: self, action: #selector(didRotateNewFace(sender:))) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapNewFace(sender:))) tapGestureRecognizer.numberOfTapsRequired = 2; if sender.state == .began { newlyCreatedFace = UIImageView(image: imageView.image) view.addSubview(newlyCreatedFace) newlyCreatedFace.center = imageView.center newlyCreatedFace.center.y += trayView.frame.origin.y newlyCreatedFaceOriginalCenter = newlyCreatedFace.center newlyCreatedFace.isUserInteractionEnabled = true newlyCreatedFace.addGestureRecognizer(panGestureRecognizer) newlyCreatedFace.addGestureRecognizer(pinchGestureRecognizer) newlyCreatedFace.addGestureRecognizer(rotateGestureRecognizer) newlyCreatedFace.addGestureRecognizer(tapGestureRecognizer) pinchGestureRecognizer.delegate = self UIView.animate(withDuration: 0.2, animations: { self.newlyCreatedFace.transform = self.newlyCreatedFace.transform.scaledBy(x: 2, y: 2) }) } else if sender.state == .changed { newlyCreatedFace.center = CGPoint(x: newlyCreatedFaceOriginalCenter.x + translation.x, y: newlyCreatedFaceOriginalCenter.y + translation.y) } else if sender.state == .ended { UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 12, initialSpringVelocity: 24, options: [], animations: { self.newlyCreatedFace.transform = CGAffineTransform(scaleX: 1.6, y: 1.6) }, completion: { (Bool) in }) } } }
41dab66d66d222d3da369f978278d8e0
37.628272
157
0.598943
false
false
false
false
ParsePlatform/Parse-SDK-iOS-OSX
refs/heads/master
ParseUI/ParseUIDemo/Swift/CustomViewControllers/LogInViewController/CustomLogInViewController.swift
bsd-3-clause
1
/* * Copyright (c) 2015, Parse, LLC. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Parse. * * As with any software that integrates with the Parse platform, your use of * this software is subject to the Parse Terms of Service * [https://www.parse.com/about/terms]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ import UIKit import Parse import ParseUI class CustomLogInViewController: PFLogInViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .blue let label = UILabel() label.textColor = .white label.text = "All Custom!" label.sizeToFit() logInView?.logo = label } }
b0992fd55435eba1c30d3f19ba0f92ee
33.731707
83
0.726124
false
false
false
false
nodes-vapor/ironman
refs/heads/master
App/Controllers/Api/CheckListController.swift
mit
1
import Vapor import HTTP final class CheckListController: ResourceRepresentable { typealias Item = CheckListItem let drop: Droplet init(droplet: Droplet) { drop = droplet } func index(request: Request) throws -> ResponseRepresentable { guard let raceId = request.parameters["w0"]?.int ?? request.parameters["raceId"]?.int else { throw Abort.custom(status: .notFound, message: "Race was not found") } let activeCheckLists = try CheckListItem.query() .filter("is_active", .equals, 1) .filter("race_id", .equals, raceId) .all() // Should be possible to make more flexible var registrations: [Node] = [] var checkIn: [Node] = [] var raceMorning: [Node] = [] try activeCheckLists.forEach({ switch($0.type) { case "registration": try registrations.append($0.makeNode()) break case "check_in": try checkIn.append($0.makeNode()) break case "race_morning": try raceMorning.append($0.makeNode()) break default: throw Abort.custom(status: .internalServerError, message: "Type \($0.type) is not supported") } }) return try JSON(node: [ "registrations": registrations.makeNode(), "checkIns": checkIn.makeNode(), "raceMorning": raceMorning.makeNode() ]) } func show(request: Request, item checklistItem: CheckListItem) throws -> ResponseRepresentable { return try JSON(node: [checklistItem]) } func makeResource() -> Resource<CheckListItem> { return Resource( index: index, show: show ) } }
e3d5da4a08a4a18e2bb46ae008ad299e
29.709677
109
0.536239
false
false
false
false
DasHutch/minecraft-castle-challenge
refs/heads/develop
app/_src/AgeDetailsRequirementsTableViewController.swift
gpl-2.0
1
// // AgeDetailsRequirementsTableViewController.swift // MC Castle Challenge // // Created by Gregory Hutchinson on 8/31/15. // Copyright © 2015 Gregory Hutchinson. All rights reserved. // import UIKit let RequirementCellIdentifier: String = "requirement_cell_identifier" class AgeDetailsRequirementsTableViewController: BaseTableViewController { var selectedCells = [NSIndexPath]() //NOTE: All PLIST Data var plistDict: NSMutableDictionary? var reqDict: NSMutableDictionary? var stage: ChallengeStages? { didSet { configStageData() } } var requirement: ChallengeStageRequirements? { didSet { configTableViewData() } } // MARK: - Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //NOTE: Only get data from plist directly // if it is currently nil here. if reqDict == nil { configStageData() } configTableView() } override func contentSizeDidChange(newUIContentSizeCategoryNewValueKey: String) { self.tableView.reloadData() } // MARK: - Private private func configStageData() { guard let age = stage?.description.lowercaseString else { log.warning("Stage is not set, unable to configure stage data") return } do { reqDict = try CastleChallengeDataManager().dataForAge(age) }catch let error as NSError { log.error("Error: \(error)") } } private func configTableView() { //????: Seems that setting this from the tableView.rowHeight as exists // in storyboard doesn't actually trigger Autolayout / Self Sizing tableView.estimatedRowHeight = 44.0 //tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorInset = UIEdgeInsetsZero } private func configTableViewData() { tableView.reloadData() } } // MARK: - UITableViewDataSource extension AgeDetailsRequirementsTableViewController { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { var sections = 0 if requirement != nil { sections = 1 //TODO: Handle Additional Requirements for Construction // switch requirement! { // case ChallengeStageRequirements.Construction: // sections = 2 // default: break // } } //TODO: Add Section for Additional Construction Reqs return sections } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rows = rowsForCurrentRequirementsType() return rows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: RequirementTableViewCell = (tableView.dequeueReusableCellWithIdentifier(RequirementCellIdentifier, forIndexPath: indexPath) as? RequirementTableViewCell)! //TODO: Refactor to DataManager Class let (req, _) = requirementForIndexPath(indexPath) if req != nil { cell.viewData = RequirementTableViewCell.ViewData(requirement: req!) } return cell } //MARK: Private //TODO: Refactor to DataManager Class private func rowsForCurrentRequirementsType() -> Int { var rows = 0 if requirement != nil { guard let data = reqDict else { log.error("Stage / Data is nil, possibly not set yet") return rows } guard let reqs = data[CastleChallengeKeys.Requirements] as? NSMutableDictionary else { log.error("Requirment data is nil, possibly not set yet") return rows } switch(requirement!) { case ChallengeStageRequirements.Construction: if let constructionReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Construction] as? NSMutableArray { rows = constructionReqs.count } //TODO: Handle Additional Construction Requirements? if let constructionReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.ConstructionAdditional] as? NSMutableArray { rows = constructionReqs.count } case ChallengeStageRequirements.Materials: if let materialsReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Materials] as? NSMutableArray { rows = materialsReqs.count } case ChallengeStageRequirements.Treasure: if let treasureReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Treasure] as? NSMutableArray { rows = treasureReqs.count } } } return rows } private func requirementForIndexPath(indexPath: NSIndexPath) -> (requirement: Requirement?, dictionary: NSMutableDictionary?) { var requirementDictionary = NSMutableDictionary() if requirement != nil { guard let data = reqDict else { log.error("Data is missing") return (nil, nil) } guard let reqs = data[CastleChallengeKeys.Requirements] as? NSMutableDictionary else { log.error("Requirment data is nil, possibly not set yet") return (nil, nil) } switch(requirement!) { case ChallengeStageRequirements.Construction: //????: Do I need mutable? I dont think so. if let constructionReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Construction] as? NSMutableArray { if let req = constructionReqs.atIndex(indexPath.row) as? NSMutableDictionary { requirementDictionary = req } } //TODO: Handle Additional Construction Requirements? if let constructionReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Construction] as? NSMutableArray { if let req = constructionReqs.atIndex(indexPath.row) as? NSMutableDictionary { requirementDictionary = req } } case ChallengeStageRequirements.Materials: //????: Do I need mutable? I dont think so. if let materialsReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Materials] as? NSMutableArray { if let req = materialsReqs.atIndex(indexPath.row) as? NSMutableDictionary { requirementDictionary = req } } case ChallengeStageRequirements.Treasure: //????: Do I need mutable? I dont think so. if let treasureReqs = reqs[CastleChallengeKeys.RequirementsTypeKeys.Treasure] as? NSMutableArray { if let req = treasureReqs.atIndex(indexPath.row) as? NSMutableDictionary { requirementDictionary = req } } } } //TODO: Refactor to DataManager Class let quantity = requirementDictionary[CastleChallengeKeys.StageRequriementItemKeys.Quantity] as? NSNumber ?? 0 let item = requirementDictionary[CastleChallengeKeys.StageRequriementItemKeys.Item] as? String ?? "" let completed = requirementDictionary[CastleChallengeKeys.StageRequriementItemKeys.Completed] as? Bool ?? false return (requirement: Requirement(description: item, quantity: Int(quantity), completed: completed), dictionary: requirementDictionary) } //TODO: Refactor to DataManager Class private func saveRequirementsData() { if plistDict != nil { FileManager.defaultManager.saveChallengeProgressPLIST(plistDict!) }else { log.warning("Attempting to save nil data, aborting.") } } } // MARK: - UITableViewDelegate extension AgeDetailsRequirementsTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if selectedCells.contains(indexPath) { //TODO: Refactor to DataManager Class if plistDict != nil && reqDict != nil && stage != nil && requirement != nil { let (_, dict) = requirementForIndexPath(indexPath) if dict != nil { dict![CastleChallengeKeys.StageRequriementItemKeys.Completed] = false saveRequirementsData() if let index = selectedCells.indexOf(indexPath) { selectedCells.removeAtIndex(index) } } } }else { //TODO: Refactor to DataManager Class if plistDict != nil && reqDict != nil && stage != nil && requirement != nil { let (_, dict) = requirementForIndexPath(indexPath) if dict != nil { dict![CastleChallengeKeys.StageRequriementItemKeys.Completed] = true saveRequirementsData() selectedCells.append(indexPath) } } } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }
f9dc9a9fd8d58a2d5d24573832054215
38.738776
172
0.599733
false
false
false
false
0xfeedface1993/Xs8-Safari-Block-Extension-Mac
refs/heads/master
Sex8BlockExtension/CloudFetchBot/SwiftUI/Log/LogItem.swift
apache-2.0
1
// // LogItem.swift // CloudFetchBot // // Created by god on 2019/8/6. // Copyright © 2019 ascp. All rights reserved. // import SwiftUI final class LogData: ObservableObject { @Published var logs = [LogItem]() @Published var state: ActionState = .hange @Published var isOn: Bool = false { willSet { guard newValue != isOn else { return } if newValue { state = .running coodinator.start() } else { state = .hange DispatchQueue.global().async { coodinator.stop() } } } } } struct LogItem: Identifiable { enum LogType { case log case error } var id: Int var date: Date var type: LogType var message: String static func log(message: String) { let item = LogItem(id: logData.logs.count, date: Date(), type: .log, message: message) if Thread.isMainThread { justLog(item: item) } else { DispatchQueue.main.async { justLog(item: item) } } } static func log(error: String) { let item = LogItem(id: logData.logs.count, date: Date(), type: .error, message: error) if Thread.isMainThread { justLog(item: item) } else { DispatchQueue.main.async { justLog(item: item) } } } private static func justLog(item: LogItem) { if logData.logs.count >= 100 { logData.logs = [item] } logData.logs.insert(item, at: 0) } } let logData = LogData()
eba3aa1b258f7ecd7d61ff40a4c256f3
22.44
94
0.492605
false
false
false
false
LipliStyle/Liplis-iOS
refs/heads/master
Liplis/CtvCellWidgetTopicCheck.swift
mit
1
// // CtvCellWidgetTopicCheck.swift // Liplis // //ウィジェット話題設定画面 要素 チェックボックス // //アップデート履歴 // 2015/05/05 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/05. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class CtvCellWidgetTopicCheck : UITableViewCell { ///============================= ///カスタムセル要素 internal var parView : ViewWidgetTopicSetting! ///============================= ///カスタムセル要素 internal var lblTitle = UILabel(); internal var lblContent = UILabel(); internal var btnCheckBox = UIButton(); ///============================= ///レイアウト情報 internal var viewWidth : CGFloat! = 0 ///============================= ///設定インデックス internal var settingIdx : Int! = -1 ///============================= ///ON/OFF internal var on : Bool! = false //============================================================ // //初期化処理 // //============================================================ /* コンストラクター */ internal override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) //タイトルラベルのセット self.createLblTitle() //チェックボッックス self.createCheckBox() } /* タイトルの初期化 */ private func createLblTitle() { self.lblTitle = UILabel(frame: CGRectMake(20, 5, 300, 15)); self.lblTitle.text = ""; self.lblTitle.font = UIFont.systemFontOfSize(20) self.addSubview(self.lblTitle); } /* 詳細文の初期化 */ private func createLblContent() { self.lblContent = UILabel(frame: CGRectMake(20, 24, 300, 15)); self.lblContent.text = ""; self.lblContent.font = UIFont.systemFontOfSize(10) self.addSubview(self.lblContent); } /* コンストラクター */ private func createCheckBox() { self.btnCheckBox = UIButton() self.btnCheckBox.titleLabel?.font = UIFont.systemFontOfSize(12) self.btnCheckBox.frame = CGRectMake(0,0,32,32) self.btnCheckBox.layer.masksToBounds = true self.btnCheckBox.setTitle("", forState: UIControlState.Normal) self.btnCheckBox.addTarget(self, action: "onClickCheck:", forControlEvents: .TouchDown) self.btnCheckBox.setImage(UIImage(named: ObjR.imgCheckOff), forState: UIControlState.Normal) self.btnCheckBox.layer.cornerRadius = 3.0 self.addSubview(self.btnCheckBox) } /* ビューを設定する */ internal func setView(parView : ViewWidgetTopicSetting) { self.parView = parView } /* 要素の位置を調整する */ internal func setSize(viewWidth : CGFloat) { self.viewWidth = viewWidth let locationY : CGFloat = CGFloat(viewWidth - 50 - 9) self.btnCheckBox.frame = CGRectMake(locationY, 6, 32, 32) } /* 値をセットする */ internal func setVal(settingIdx : Int, val : Int) { self.on = LiplisUtil.int2Bit(val) self.settingIdx = settingIdx if(self.on == true) { let imgOn : UIImage = UIImage(named: ObjR.imgCheckOn)! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) } else { let imgOff : UIImage = UIImage(named: ObjR.imgCheckOff)! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //============================================================ // //イベントハンドラ // //============================================================ /* スイッチ選択 */ internal func onClickCheck(sender: UIButton) { if(self.on == true) { print("チェックボックスOFF") let imgOff : UIImage = UIImage(named: ObjR.imgCheckOff)! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) self.on = false self.parView.selectCheck(settingIdx,val: false) } else { print("チェックボックスON") let imgOn : UIImage = UIImage(named: ObjR.imgCheckOn)! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) self.on = true self.parView.selectCheck(settingIdx,val: true) } } }
882146ae68e0c28688868e3f62b519af
25.781065
100
0.531492
false
false
false
false
tgu/HAP
refs/heads/master
Sources/HAP/Accessories/SmokeSensor.swift
mit
1
extension Accessory { open class SmokeSensor: Accessory { public let smokeSensor = Service.SmokeSensor() public init(info: Service.Info, additionalServices: [Service] = []) { super.init(info: info, type: .sensor, services: [smokeSensor] + additionalServices) } } } public enum SmokeDetected: Int, CharacteristicValueType { case smokeNotDetected = 0 case smokeDetected = 1 } extension Service { open class SmokeSensor: Service { public let smokeDetected = GenericCharacteristic<SmokeDetected>( type: .currentPosition, permissions: [.read, .events]) public init() { super.init(type: .smokeSensor, characteristics: [smokeDetected]) } } }
f4df789aa401c4b4eecc31c9117f543e
28.192308
95
0.642951
false
false
false
false
HighBay/PageMenu
refs/heads/master
Demos/Demo 5/PageMenuDemoSegmentedControl/PageMenuDemoSegmentedControl/RecentsTableViewController.swift
bsd-3-clause
4
// // RecentsTableViewController.swift // PageMenuDemoTabbar // // Created by Niklas Fahl on 1/9/15. // Copyright (c) 2015 Niklas Fahl. All rights reserved. // import UIKit class RecentsTableViewController: UITableViewController { var parentNavigationController : UINavigationController? var namesArray : [String] = ["Kim White", "Kim White", "David Fletcher", "Anna Hunt", "Timothy Jones", "Timothy Jones", "Timothy Jones", "Lauren Richard", "Lauren Richard", "Juan Rodriguez"] var photoNameArray : [String] = ["woman1.jpg", "woman1.jpg", "man8.jpg", "woman3.jpg", "man3.jpg", "man3.jpg", "man3.jpg", "woman5.jpg", "woman5.jpg", "man5.jpg"] var activityTypeArray : NSArray = [0, 1, 1, 0, 2, 1, 2, 0, 0, 2] var dateArray : NSArray = ["4:22 PM", "Wednesday", "Tuesday", "Sunday", "01/02/15", "12/31/14", "12/28/14", "12/24/14", "12/17/14", "12/14/14"] override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UINib(nibName: "RecentsTableViewCell", bundle: nil), forCellReuseIdentifier: "RecentsTableViewCell") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("\(self.title) page: viewWillAppear") } override func viewDidAppear(_ animated: Bool) { self.tableView.showsVerticalScrollIndicator = false super.viewDidAppear(animated) self.tableView.showsVerticalScrollIndicator = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell : RecentsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RecentsTableViewCell") as! RecentsTableViewCell // Configure the cell... cell.nameLabel.text = namesArray[indexPath.row] cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row]) cell.dateLabel.text = dateArray[indexPath.row] as! NSString as String cell.nameLabel.textColor = UIColor(red: 85.0/255.0, green: 85.0/255.0, blue: 85.0/255.0, alpha: 1.0) if activityTypeArray[indexPath.row] as! Int == 0 { cell.activityImageView.image = UIImage(named: "phone_send") } else if activityTypeArray[indexPath.row] as! Int == 1 { cell.activityImageView.image = UIImage(named: "phone_receive") } else { cell.activityImageView.image = UIImage(named: "phone_down") cell.nameLabel.textColor = UIColor.red } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 94.0 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let newVC : UIViewController = UIViewController() newVC.view.backgroundColor = UIColor.white newVC.title = "Favorites" parentNavigationController!.pushViewController(newVC, animated: true) } }
7cd0a6c354df9f7369509e85f3caca36
39.802198
194
0.654457
false
false
false
false
jsembdner/Ninety-Nine-Swift-Solutions
refs/heads/master
solutions_jsembdner/NinetyNineSwiftSolutions/NinetyNineSwiftSolutions/p04_jsembdner.swift
mit
1
extension List { public var length: Int { var currentItem = self var counter = 1 while let nextItem = currentItem.nextItem { counter += 1 currentItem = nextItem } return counter } }
4dde612ffb06212e00de3a51c5d0b796
13.642857
45
0.658537
false
false
false
false
sosaucily/yelpclient
refs/heads/master
yelpclient/FiltersTableViewController.swift
mit
1
// // FiltersTableViewController.swift // yelpclient // // Created by Jesse Smith on 9/20/14. // Copyright (c) 2014 Jesse Smith. All rights reserved. // import UIKit @objc protocol FilterTableDelegate { func returnSearchParams(searchParams: SearchResults) } class SearchResults: NSObject { var sortMetric: Int = 0 var thai: Bool = true var mexican: Bool = true var chinese: Bool = true var italian: Bool = true } class FiltersTableController: UITableViewController, DropdownFilterCellDelegate, SwitchFilterCellDelegate { let sectionHeaders = ["Sort by", "Categories"] let categories = ["thai","mexican", "chinese", "italian"] var searchParams: SearchResults = SearchResults() var delegate: FilterTableDelegate? var searchButton: UIBarButtonItem = UIBarButtonItem() var expanded: Bool = false override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 200 self.tableView.rowHeight = UITableViewAutomaticDimension var vcs = self.navigationController?.viewControllers self.delegate = vcs?[0] as? FilterTableDelegate self.searchButton = UIBarButtonItem(title: "Search", style: UIBarButtonItemStyle.Bordered, target: self, action: "doSearch") self.navigationItem.rightBarButtonItem = self.searchButton; } func doSearch() { self.delegate?.returnSearchParams(self.searchParams) self.navigationController?.popViewControllerAnimated(true) } // override func viewDidDisappear(animated: Bool) {} override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 1 } else { if (!self.expanded) { return 3 } else { return 4 } } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let table = self.tableView if (indexPath.section == 0){ let cell = table.dequeueReusableCellWithIdentifier("dropdownFilterCell", forIndexPath: indexPath) as DropdownFilterCell cell.delegate = self return cell } else if (indexPath.row == 2 && !self.expanded) { let cell = table.dequeueReusableCellWithIdentifier("seeAllCell", forIndexPath: indexPath) as SeeAllCell return cell } else { let cell = table.dequeueReusableCellWithIdentifier("switchFilterCell", forIndexPath: indexPath) as SwitchFilterCell cell.filterName.text = categories[indexPath.row] cell.filterSwitch.addTarget(cell, action: "triggerSwitch", forControlEvents: UIControlEvents.ValueChanged) cell.delegate = self return cell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if (!self.expanded) { if (indexPath.section == 1 && indexPath.row == 2) { self.expanded = true self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Automatic) } } } func sortValue(message: String) { var id = 0 switch message { case "best match": id = 1 case "distance": id = 2 case "highest rated": id = 3 default: id = 0 } self.searchParams.sortMetric = id } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "\(sectionHeaders[section])" } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 75; } func setSwitch(message: String) { println(message) switch message { case "thai": searchParams.thai = !searchParams.thai case "mexican": searchParams.mexican = !searchParams.mexican case "chinese": searchParams.chinese = !searchParams.chinese case "italian": searchParams.italian = !searchParams.italian default: break } } }
e9c5217876d042708c9316ed9d6d1f9b
31.244604
132
0.623606
false
false
false
false
qvik/HelsinkiOS-IBD-Demo
refs/heads/master
HelsinkiOS-Demo/Views/ExampleInspectables.swift
mit
1
// // ExampleInspectables.swift // HelsinkiOS-Demo // // Created by Jerry Jalava on 30/09/15. // Copyright © 2015 Qvik. All rights reserved. // import UIKit enum ExampleEnum { case Value1 case Value2 } @IBDesignable class ExampleInspectables: UIView { @IBInspectable var stringInput:String = "A String" @IBInspectable var nsStringInput:NSString = "NSString" @IBInspectable var integerInput:Int! @IBInspectable var cgFloatInput:CGFloat! @IBInspectable var floatingPointInput:Double! @IBInspectable var booleanInput:Bool = true @IBInspectable var colorPicker:UIColor! @IBInspectable var pointInput:CGPoint! @IBInspectable var areaInput:CGRect = CGRect(x: 0, y: 0, width: 100, height: 100) @IBInspectable var sizeInput:CGSize! // This variable isn't in camelCase @IBInspectable var badlynamedvariable:String! @IBInspectable var borderColor:UIColor = UIColor.appPink() { didSet { layer.borderColor = borderColor.CGColor } } @IBInspectable var borderWidth: CGFloat = 1 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var cornerRadius:CGFloat = 2 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var circleColor: UIColor = UIColor(red: (171.0/255.0), green: (250.0/255), blue: (81.0/255.0), alpha: 1.0) @IBInspectable var circleRadius:CGFloat = 150 // items that don't display in IB @IBInspectable var enumInput:ExampleEnum = .Value1 @IBInspectable var layoutConstraint:NSLayoutConstraint! @IBInspectable var listValues:[String]! @IBInspectable var edgeInsets:UIEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) @IBInspectable var cgVectorInput:CGVector! @IBInspectable var cgTransform:CGAffineTransform! = CGAffineTransformIdentity @IBInspectable var nsDate:NSDate! // MARK: Lifecycle required override init(frame: CGRect) { super.init(frame: frame) self.setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupView() } override func prepareForInterfaceBuilder() { self.setupView() } func setupView() { layer.borderColor = borderColor.CGColor layer.borderWidth = borderWidth layer.cornerRadius = cornerRadius } override func drawRect(rect: CGRect) { // self.addCirle(self.circleRadius, capRadius: 20, color: self.circleColor) } // MARK: Private methods func addCirle(arcRadius: CGFloat, capRadius: CGFloat, color: UIColor) { let X = CGRectGetMidX(self.bounds) let Y = CGRectGetMidY(self.bounds) // Bottom Oval let pathBottom = UIBezierPath(ovalInRect: CGRectMake((X - (arcRadius/2)), (Y - (arcRadius/2)), arcRadius, arcRadius)).CGPath self.addOval(20.0, path: pathBottom, strokeStart: 0, strokeEnd: 0.5, strokeColor: color, fillColor: UIColor.clearColor(), shadowRadius: 0, shadowOpacity: 0, shadowOffsset: CGSizeZero) // Middle Cap let pathMiddle = UIBezierPath(ovalInRect: CGRectMake((X - (capRadius/2)) - (arcRadius/2), (Y - (capRadius/2)), capRadius, capRadius)).CGPath self.addOval(0.0, path: pathMiddle, strokeStart: 0, strokeEnd: 1.0, strokeColor: color, fillColor: color, shadowRadius: 5.0, shadowOpacity: 0.5, shadowOffsset: CGSizeZero) // Top Oval let pathTop = UIBezierPath(ovalInRect: CGRectMake((X - (arcRadius/2)), (Y - (arcRadius/2)), arcRadius, arcRadius)).CGPath self.addOval(20.0, path: pathTop, strokeStart: 0.5, strokeEnd: 1.0, strokeColor: color, fillColor: UIColor.clearColor(), shadowRadius: 0, shadowOpacity: 0, shadowOffsset: CGSizeZero) } func addOval(lineWidth: CGFloat, path: CGPathRef, strokeStart: CGFloat, strokeEnd: CGFloat, strokeColor: UIColor, fillColor: UIColor, shadowRadius: CGFloat, shadowOpacity: Float, shadowOffsset: CGSize) { let arc = CAShapeLayer() arc.lineWidth = lineWidth arc.path = path arc.strokeStart = strokeStart arc.strokeEnd = strokeEnd arc.strokeColor = strokeColor.CGColor arc.fillColor = fillColor.CGColor arc.shadowColor = UIColor.blackColor().CGColor arc.shadowRadius = shadowRadius arc.shadowOpacity = shadowOpacity arc.shadowOffset = shadowOffsset layer.addSublayer(arc) } }
12d66ec54fd5f54cb1c1e1ec01081b31
36.908333
207
0.667399
false
false
false
false
honghaoz/UW-Quest-iOS
refs/heads/master
UW Quest/ThirdParty/ZHDynamicCollectionView.swift
apache-2.0
1
// // ZHDynamicCollectionView.swift // // Created by Honghao on 1/1/15. // Copyright (c) 2015 Honghao. All rights reserved. // import UIKit class ZHDynamicCollectionView: UICollectionView { // A dictionary of offscreen cells that are used within the sizeForItemAtIndexPath method to handle the size calculations. These are never drawn onscreen. The dictionary is in the format: // { NSString *reuseIdentifier : UICollectionViewCell *offscreenCell, ... } private var offscreenCells = Dictionary<String, UICollectionViewCell>() private var registeredCellNibs = Dictionary<String, UINib>() private var registeredCellClasses = Dictionary<String, UICollectionViewCell.Type>() override func registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) { super.registerClass(cellClass, forCellWithReuseIdentifier: identifier) registeredCellClasses[identifier] = cellClass as! UICollectionViewCell.Type! } override func registerNib(nib: UINib?, forCellWithReuseIdentifier identifier: String) { super.registerNib(nib, forCellWithReuseIdentifier: identifier) registeredCellNibs[identifier] = nib } /** Returns a reusable collection cell object located by its identifier. This collection cell is not showing on screen, it's useful for calculating dynamic cell size :param: identifier A string identifying the cell object to be reused. This parameter must not be nil. :returns: UICollectionViewCell? */ func dequeueReusableOffScreenCellWithReuseIdentifier(identifier: String) -> UICollectionViewCell? { var cell: UICollectionViewCell? = offscreenCells[identifier] if cell == nil { if registeredCellNibs.indexForKey(identifier) != nil { let cellNib: UINib = registeredCellNibs[identifier]! as UINib cell = cellNib.instantiateWithOwner(nil, options: nil)[0] as? UICollectionViewCell } else if registeredCellClasses.indexForKey(identifier) != nil { let cellClass = registeredCellClasses[identifier] as UICollectionViewCell.Type! cell = cellClass() } else { assertionFailure("\(identifier) is not registered in \(self)") } offscreenCells[identifier] = cell } return cell } }
8b2137d0139b5b9210e4cebf8f867660
46.56
191
0.705214
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS Tests/Mocks/MockCollection.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // 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/. // @testable import Wire final class MockCollection: NSObject, ZMCollection { static let onlyImagesCategory = CategoryMatch(including: .image, excluding: .none) static let onlyVideosCategory = CategoryMatch(including: .video, excluding: .none) static let onlyFilesCategory = CategoryMatch(including: .file, excluding: .video) static let onlyLinksCategory = CategoryMatch(including: .linkPreview, excluding: .none) let messages: [CategoryMatch: [ZMConversationMessage]] init(messages: [CategoryMatch: [ZMConversationMessage]]) { self.messages = messages } convenience init(fileMessages: [ZMConversationMessage]) { self.init(messages: [ MockCollection.onlyFilesCategory: fileMessages ]) } convenience init(linkMessages: [ZMConversationMessage]) { self.init(messages: [ MockCollection.onlyLinksCategory: linkMessages ]) } static var empty: MockCollection { return MockCollection(messages: [:]) } func tearDown() { } func assets(for category: WireDataModel.CategoryMatch) -> [ZMConversationMessage] { return messages[category] ?? [] } let fetchingDone = true }
e23a58c378769413a9c2533eb786d1cf
32.649123
91
0.705422
false
false
false
false
sjtu-meow/iOS
refs/heads/master
Meow/NotificationTableViewController.swift
apache-2.0
1
// // NotificationTableViewController.swift // Meow // // Created by 唐楚哲 on 2017/7/18. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit class NotificationTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() tableView.register(R.nib.momentNotificationTableViewCell) tableView.register(R.nib.questionNotificationTableViewCell) tableView.register(R.nib.answerNotificationTableViewCell) tableView.register(R.nib.messageNotificationTableViewCell) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10; } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
6d52f6e9c70830e4bd8a870278f6c56b
30.613636
136
0.668943
false
false
false
false
lydonchandra/DominantColor
refs/heads/master
DominantColor/Shared/DominantColors.swift
mit
1
// // DominantColors.swift // DominantColor // // Created by Indragie on 12/20/14. // Copyright (c) 2014 Indragie Karunaratne. All rights reserved. // #if os(OSX) import Foundation #elseif os(iOS) import UIKit #endif // MARK: Bitmaps private struct RGBAPixel { let r: UInt8 let g: UInt8 let b: UInt8 let a: UInt8 } extension RGBAPixel: Hashable { private var hashValue: Int { return (((Int(r) << 8) | Int(g)) << 8) | Int(b) } } private func ==(lhs: RGBAPixel, rhs: RGBAPixel) -> Bool { return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b } private func createRGBAContext(width: Int, height: Int) -> CGContext { return CGBitmapContextCreate( nil, width, height, 8, // bits per component width * 4, // bytes per row CGColorSpaceCreateDeviceRGB(), CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue).rawValue )! } // Enumerates over all of the pixels in an RGBA bitmap context // in the order that they are stored in memory, for faster access. // // From: https://www.mikeash.com/pyblog/friday-qa-2012-08-31-obtaining-and-interpreting-image-data.html private func enumerateRGBAContext(context: CGContext, handler: (Int, Int, RGBAPixel) -> Void) { let (width, height) = (CGBitmapContextGetWidth(context), CGBitmapContextGetHeight(context)) let data = unsafeBitCast(CGBitmapContextGetData(context), UnsafeMutablePointer<RGBAPixel>.self) for y in 0..<height { for x in 0..<width { handler(x, y, data[Int(x + y * width)]) } } } private func enumerateRGBAContextDon(context:CGContext, handler: (Int, Int, RGBAPixel) -> Void) { let (width, height) = (CGBitmapContextGetWidth(context), CGBitmapContextGetHeight(context)) let data = unsafeBitCast(CGBitmapContextGetData(context), UnsafeMutablePointer<RGBAPixel>.self) for y in 0..<height { for x in 0..<width { let currentPixelIdx = Int(x + (y * width)) handler(x, y, data[currentPixelIdx]) } } } // MARK: Conversions public func RGBVectorToCGColor(rgbVector: INVector3) -> CGColor { return CGColorCreate(CGColorSpaceCreateDeviceRGB(), [CGFloat(rgbVector.x), CGFloat(rgbVector.y), CGFloat(rgbVector.z), 1.0])! } private func RGBVectorToCGColorDon(rgbVector: INVector3) -> CGColor { return CGColorCreate( CGColorSpaceCreateDeviceRGB(), [CGFloat(rgbVector.x), CGFloat(rgbVector.y), CGFloat(rgbVector.z), 1.0])! } private extension RGBAPixel { func toRGBVector() -> INVector3 { return INVector3( x: Float(r) / Float(UInt8.max), y: Float(g) / Float(UInt8.max), z: Float(b) / Float(UInt8.max) ) } } // MARK: Clustering extension INVector3 : ClusteredType {} // MARK: Main public enum GroupingAccuracy { case Low // CIE 76 - Euclidian distance case Medium // CIE 94 - Perceptual non-uniformity corrections case High // CIE 2000 - Additional corrections for neutral colors, lightness, chroma, and hue } struct DefaultParameterValues { static var maxSampledPixels: Int = 10000 static var accuracy: GroupingAccuracy = .Medium static var seed: UInt32 = 3571 static var memoizeConversions: Bool = false } struct DefaultParameterValuesDon { static var maxSampledPixels: Int = 1000 static var accuracy: GroupingAccuracy = .Medium static var seed: UInt32 = 3571 static var memoizeConversions: Bool = false } /** Computes the dominant colors in an image - parameter image: The image - parameter maxSampledPixels: Maximum number of pixels to sample in the image. If the total number of pixels in the image exceeds this value, it will be downsampled to meet the constraint. - parameter accuracy: Level of accuracy to use when grouping similar colors. Higher accuracy will come with a performance tradeoff. - parameter seed: Seed to use when choosing the initial points for grouping of similar colors. The same seed is guaranteed to return the same colors every time. - parameter memoizeConversions: Whether to memoize conversions from RGB to the LAB color space (used for grouping similar colors). Memoization will only yield better performance for large values of `maxSampledPixels` in images that are primarily comprised of flat colors. If this information about the image is not known beforehand, it is best to not memoize. - returns: A list of dominant colors in the image sorted from most dominant to least dominant. */ public func dominantColorsInImage( image: CGImage, maxSampledPixels: Int = DefaultParameterValues.maxSampledPixels, //1000 accuracy: GroupingAccuracy = DefaultParameterValues.accuracy, //Medium seed: UInt32 = DefaultParameterValues.seed, //3571 memoizeConversions: Bool = DefaultParameterValues.memoizeConversions ) -> [CGColor] { let (width, height) = (CGImageGetWidth(image), CGImageGetHeight(image)) NSLog("image width, height = %d,%d", width, height) let (scaledWidth, scaledHeight) = scaledDimensionsForPixelLimit(maxSampledPixels, width: width, height: height) NSLog("image scaled width, height = %d, %d",scaledWidth, scaledHeight) // Downsample the image if necessary, so that the total number of // pixels sampled does not exceed the specified maximum. let context = createRGBAContext(scaledWidth, height: scaledHeight) CGContextDrawImage(context, CGRect(x: 0, y: 0, width: Int(scaledWidth), height: Int(scaledHeight)), image) // Get the RGB colors from the bitmap context, ignoring any pixels // that have alpha transparency. // Also convert the colors to the LAB color space var labValues = [INVector3]() labValues.reserveCapacity(Int(scaledWidth * scaledHeight)) let RGBToLAB: RGBAPixel -> INVector3 = { let f: RGBAPixel -> INVector3 = { IN_RGBToLAB($0.toRGBVector()) } return memoizeConversions ? memoize(f) : f }() enumerateRGBAContext(context) { (_, _, pixel) in //if pixel.a == UInt8.max { labValues.append(RGBToLAB(pixel)) //} } // Cluster the colors using the k-means algorithm let k = selectKForElements(labValues) var clusters = kmeans(labValues, k: k, seed: seed, distance: distanceForAccuracy(accuracy)) // Sort the clusters by size in descending order so that the // most dominant colors come first. clusters.sortInPlace { $0.size > $1.size } return clusters.map { RGBVectorToCGColor(IN_LABToRGB($0.centroid)) } } public func dominantColorsInImageDon ( image: CGImage, maxSampledPixels: Int = DefaultParameterValues.maxSampledPixels, accuracy: GroupingAccuracy = DefaultParameterValues.accuracy, seed: UInt32 = DefaultParameterValues.seed, memoizeConversions: Bool = DefaultParameterValues.memoizeConversions ) -> [CGColor] { let (width, height) = (CGImageGetWidth(image), CGImageGetHeight(image)); let (scaledWidth, scaledHeight) = scaledDimensionsForPixelLimit(maxSampledPixels, width: width, height: height) //downsample image if necessary, so total number of pixels sampled does not exceed //specified maximum let context = createRGBAContext(scaledWidth, height: scaledHeight) CGContextDrawImage( context ,CGRect( x: 0, y: 0, width: Int(scaledWidth), height: Int(scaledHeight)) , image) //get RGB colors from bitmap context,ignoring any pixels that have alpha transparency //also convert the colors to LAB color space var labValues = [INVector3]() labValues.reserveCapacity( Int(scaledWidth * scaledHeight) ) let RGBToLAB: RGBAPixel -> INVector3 = { let f: RGBAPixel -> INVector3 = { IN_RGBToLAB( $0.toRGBVector()) } return memoizeConversions ? memoize(f) : f }() enumerateRGBAContext(context) { (_, _, pixel) -> Void in if pixel.a == UInt8.max { labValues.append(RGBToLAB(pixel)) } } //cluster colors using k-means algorithm let k = selectKForElements(labValues) var clusters = kmeans(labValues, k: k, seed: seed, distance: distanceForAccuracy(accuracy)) //sort clusters by size in descending order so that most dominant colors come first clusters.sortInPlace { $0.size < $1.size } return clusters.map { RGBVectorToCGColor(IN_LABToRGB($0.centroid)) } } private func distanceForAccuracy(accuracy: GroupingAccuracy) -> (INVector3, INVector3) -> Float { switch accuracy { case .Low: return CIE76SquaredColorDifference case .Medium: return CIE94SquaredColorDifference() case .High: return CIE2000SquaredColorDifference() } } // Computes the proportionally scaled dimensions such that the // total number of pixels does not exceed the specified limit. private func scaledDimensionsForPixelLimit(limit: Int, width: Int, height: Int) -> (Int, Int) { if (width * height > limit) { let ratio = Float(width) / Float(height) let maxWidth = sqrtf(ratio * Float(limit)) return (Int(maxWidth), Int(Float(limit) / maxWidth)) } return (width, height) } private func selectKForElements<T>(elements: [T]) -> Int { // Seems like a magic number... return 16 }
e014abc8f3e336ee3808affab71d339c
36.679389
129
0.653566
false
false
false
false
ianyh/Highball
refs/heads/master
Highball/Account.swift
mit
1
// // Account.swift // Highball // // Created by Ian Ynda-Hummel on 8/29/16. // Copyright © 2016 ianynda. All rights reserved. // import RealmSwift public protocol Account { var name: String! { get } var token: String! { get } var tokenSecret: String! { get } var blogs: [UserBlog] { get } } public extension Account { public var primaryBlog: UserBlog { return blogs.filter { $0.isPrimary }.first! } } public func == (lhs: Account, rhs: Account) -> Bool { return lhs.name == rhs.name } public class AccountObject: Object { public dynamic var name: String! public dynamic var token: String! public dynamic var tokenSecret: String! public let blogObjects = List<UserBlogObject>() public var blogs: [UserBlog] { return Array(blogObjects) } public override static func primaryKey() -> String { return "name" } public override static func ignoredProperties() -> [String] { return ["blogs"] } } extension AccountObject: Account {}
e3c3f716cfa2254b709d6f56412d42cf
19.489362
62
0.694704
false
false
false
false
dropbox/SwiftyDropbox
refs/heads/master
Source/SwiftyDropbox/Platform/SwiftyDropbox_macOS/OAuthDesktop.swift
mit
1
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// #if os(macOS) import Foundation import AppKit import WebKit extension DropboxClientsManager { /// Starts a "token" flow. /// /// This method should no longer be used. /// Long-lived access tokens are deprecated. See https://dropbox.tech/developers/migrating-app-permissions-and-access-tokens. /// Please use `authorizeFromControllerV2` instead. /// - Parameters: /// - sharedApplication: The shared NSApplication instance in your app. /// - controller: An NSViewController to present the auth flow from. Reference is weakly held. /// - openURL: Handler to open a URL. @available(*, deprecated, message: "This method was used for long-lived access tokens, which are now deprecated. Please use `authorizeFromControllerV2` instead.") public static func authorizeFromController(sharedApplication: NSApplication, controller: NSViewController?, openURL: @escaping ((URL) -> Void)) { precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` before calling this method") let sharedDesktopApplication = DesktopSharedApplication(sharedApplication: sharedApplication, controller: controller, openURL: openURL) DesktopSharedApplication.sharedDesktopApplication = sharedDesktopApplication DropboxOAuthManager.sharedOAuthManager.authorizeFromSharedApplication(sharedDesktopApplication) } /// Starts the OAuth 2 Authorization Code Flow with PKCE. /// /// PKCE allows "authorization code" flow without "client_secret" /// It enables "native application", which is ensafe to hardcode client_secret in code, to use "authorization code". /// PKCE is more secure than "token" flow. If authorization code is compromised during /// transmission, it can't be used to exchange for access token without random generated /// code_verifier, which is stored inside this SDK. /// /// - Parameters: /// - sharedApplication: The shared NSApplication instance in your app. /// - controller: An NSViewController to present the auth flow from. Reference is weakly held. /// - loadingStatusDelegate: An optional delegate to handle loading experience during auth flow. /// e.g. Show a loading spinner and block user interaction while loading/waiting. /// - openURL: Handler to open a URL. /// - scopeRequest: Contains requested scopes to obtain. /// - NOTE: /// If auth completes successfully, A short-lived Access Token and a long-lived Refresh Token will be granted. /// API calls with expired Access Token will fail with AuthError. An expired Access Token must be refreshed /// in order to continue to access Dropbox APIs. /// /// API clients set up by `DropboxClientsManager` will get token refresh logic for free. /// If you need to set up `DropboxClient`/`DropboxTeamClient` without `DropboxClientsManager`, /// you will have to set up the clients with an appropriate `AccessTokenProvider`. public static func authorizeFromControllerV2(sharedApplication: NSApplication, controller: NSViewController?, loadingStatusDelegate: LoadingStatusDelegate?, openURL: @escaping ((URL) -> Void), scopeRequest: ScopeRequest? ) { precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` before calling this method") let sharedDesktopApplication = DesktopSharedApplication(sharedApplication: sharedApplication, controller: controller, openURL: openURL) sharedDesktopApplication.loadingStatusDelegate = loadingStatusDelegate DesktopSharedApplication.sharedDesktopApplication = sharedDesktopApplication DropboxOAuthManager.sharedOAuthManager.authorizeFromSharedApplication( sharedDesktopApplication, usePKCE: true, scopeRequest: scopeRequest ) } public static func setupWithAppKeyDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManager(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithAppKeyMultiUserDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUser(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } public static func setupWithTeamAppKeyDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManagerTeam(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithTeamAppKeyMultiUserDesktop(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUserTeam(appKey, oAuthManager: DropboxOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } } public class DesktopSharedApplication: SharedApplication { public static var sharedDesktopApplication: DesktopSharedApplication? let sharedApplication: NSApplication weak var controller: NSViewController? let openURL: ((URL) -> Void) weak var loadingStatusDelegate: LoadingStatusDelegate? /// Reference to controller is weakly held. public init(sharedApplication: NSApplication, controller: NSViewController?, openURL: @escaping ((URL) -> Void)) { self.sharedApplication = sharedApplication self.controller = controller self.openURL = openURL if let controller = controller { self.controller = controller } else { self.controller = sharedApplication.keyWindow?.contentViewController } } public func presentErrorMessage(_ message: String, title: String) { let error = NSError(domain: "", code: 123, userInfo: [NSLocalizedDescriptionKey:message]) if let controller = self.controller { controller.presentError(error) } } public func presentErrorMessageWithHandlers(_ message: String, title: String, buttonHandlers: Dictionary<String, () -> Void>) { presentErrorMessage(message, title: title) } // no platform-specific auth methods for OS X public func presentPlatformSpecificAuth(_ authURL: URL) -> Bool { return false } public func presentAuthChannel(_ authURL: URL, tryIntercept: @escaping ((URL) -> Bool), cancelHandler: @escaping (() -> Void)) { self.presentExternalApp(authURL) } public func presentExternalApp(_ url: URL) { self.openURL(url) } public func canPresentExternalApp(_ url: URL) -> Bool { return true } public func presentLoading() { loadingStatusDelegate?.showLoading() } public func dismissLoading() { loadingStatusDelegate?.dismissLoading() } } #endif
fcc339f50d360b7f422f6e2e1ba1b1c6
48.993289
189
0.696335
false
false
false
false
PomTTcat/SourceCodeGuideRead_JEFF
refs/heads/master
ObjectMapperGuideRead_Jeff/ObjectGuide/ObjectGuide/ObjectMapper/ImmutableMappableDemo.swift
mit
2
// // ImmutableMappableDemo.swift // ObjectGuide // // Created by PomCat on 2019/7/3. // import Foundation // ImmutableMappable 这些属性是只读的,因为赋值只发生在init之中。 class immutModel: ImmutableMappable { let id: Int let name: String? // 为什么可能throws?因为里面的用可能有throws没有处理。 required init(map: Map) throws { // 这里是最大的不同。 普通mappable是走操作符"<-" ,ImmutableMappable是直接赋值。 // 此处的属性都是常量,所以只能用直接复制,不能用操作符。 // 官方推荐方法 id = try map.value("id") name = try? map.value("name") // 错误示范 // id <- map["id"] // 为什么这种就报错,self.id 还没有被初始化。因为常量是不能被引用的(inout)!只能直接赋值。 //Constant 'self.id' passed by reference before being initialized // 另类赋值方法 // var s:Int = 0 // s <- map["id"] // id = s } func mapping(map: Map) { id >>> map["id"] name >>> map["name"] } } func ImmutableMappableDemo() { let dic = ["id": 15, "name": "李雷", ] as [String : Any] // dict -> model let mm = try! immutModel(JSON: dic) // model -> dict let dic2 = mm.toJSON() print("meimeiModel\n \(String(describing: mm)) -- \(dic2)") }
b065c566fff10f64a1d2c21e9adbbe99
20.77193
83
0.519742
false
false
false
false
KarlWarfel/nutshell-ios
refs/heads/roll-back
Nutshell/Utilities and Extensions/NutUtils.swift
bsd-2-clause
1
/* * Copyright (c) 2015, Tidepool Project * * This program is free software; you can redistribute it and/or modify it under * the terms of the associated License, which is identical to the BSD 2-Clause * License as published by the Open Source Initiative at opensource.org. * * 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 License for more details. * * You should have received a copy of the License along with this program; if * not, you can obtain one from Tidepool Project at tidepool.org. */ import UIKit import CoreData import Photos import Darwin class NutUtils { class func onIPad() -> Bool { return UIDevice.currentDevice().userInterfaceIdiom == .Pad } class func dispatchBoolToVoidAfterSecs(secs: Float, result: Bool, boolToVoid: (Bool) -> (Void)) { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(secs * Float(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()){ boolToVoid(result) } } class func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } class func compressImage(image: UIImage) -> UIImage { var actualHeight : CGFloat = image.size.height var actualWidth : CGFloat = image.size.width let maxHeight : CGFloat = 600.0 let maxWidth : CGFloat = 800.0 var imgRatio : CGFloat = actualWidth/actualHeight let maxRatio : CGFloat = maxWidth/maxHeight let compressionQuality : CGFloat = 0.5 //50 percent compression if ((actualHeight > maxHeight) || (actualWidth > maxWidth)){ if(imgRatio < maxRatio){ //adjust height according to maxWidth imgRatio = maxWidth / actualWidth; actualHeight = imgRatio * actualHeight; actualWidth = maxWidth; } else{ actualHeight = maxHeight; actualWidth = maxWidth; } } let rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight) UIGraphicsBeginImageContext(rect.size) image.drawInRect(rect) let img : UIImage = UIGraphicsGetImageFromCurrentImageContext()! let imageData = UIImageJPEGRepresentation(img, compressionQuality) UIGraphicsEndImageContext() NSLog("Compressed length: \(imageData!.length)") return UIImage(data: imageData!)! } class func photosDirectoryPath() -> String? { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] var photoDirPath: String? = path + "/photos/" + NutDataController.controller().currentUserId! + "/" let fm = NSFileManager.defaultManager() var dirExists = false do { _ = try fm.contentsOfDirectoryAtPath(photoDirPath!) //NSLog("Photos dir: \(dirContents)") dirExists = true } catch let error as NSError { NSLog("Need to create dir at \(photoDirPath), error: \(error)") } if !dirExists { do { try fm.createDirectoryAtPath(photoDirPath!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { NSLog("Failed to create dir at \(photoDirPath), error: \(error)") photoDirPath = nil } } return photoDirPath } class func urlForNewPhoto() -> String { let baseFilename = "file_" + NSUUID().UUIDString + ".jpg" return baseFilename } class func filePathForPhoto(photoUrl: String) -> String? { if let dirPath = NutUtils.photosDirectoryPath() { return dirPath + photoUrl } return nil } class func deleteLocalPhoto(url: String) { if url.hasPrefix("file_") { if let filePath = filePathForPhoto(url) { let fm = NSFileManager.defaultManager() do { try fm.removeItemAtPath(filePath) NSLog("Deleted photo: \(url)") } catch let error as NSError { NSLog("Failed to delete photo at \(filePath), error: \(error)") } } } } class func photoInfo(url: String) -> String { var result = "url: " + url if url.hasPrefix("file_") { if let filePath = filePathForPhoto(url) { let fm = NSFileManager.defaultManager() do { let fileAttributes = try fm.attributesOfItemAtPath(filePath) result += "size: " + String(fileAttributes[NSFileSize]) result += "created: " + String(fileAttributes[NSFileCreationDate]) } catch let error as NSError { NSLog("Failed to get attributes for file \(filePath), error: \(error)") } } } return result } class func loadImage(url: String, imageView: UIImageView) { if let image = UIImage(named: url) { imageView.image = image imageView.hidden = false } else if url.hasPrefix("file_") { if let filePath = filePathForPhoto(url) { let image = UIImage(contentsOfFile: filePath) if let image = image { imageView.hidden = false imageView.image = image } else { NSLog("Failed to load photo from local file: \(url)!") } } } else { if let nsurl = NSURL(string:url) { let fetchResult = PHAsset.fetchAssetsWithALAssetURLs([nsurl], options: nil) if let asset = fetchResult.firstObject as? PHAsset { // TODO: move this to file system! Would need current event to update it as well! var targetSize = imageView.frame.size // bump up resolution... targetSize.height *= 2.0 targetSize.width *= 2.0 let options = PHImageRequestOptions() PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: PHImageContentMode.AspectFit, options: options) { (result, info) in if let result = result { imageView.hidden = false imageView.image = result } } } } } } class func dateFromJSON(json: String?) -> NSDate? { if let json = json { var result = jsonDateFormatter.dateFromString(json) if result == nil { result = jsonAltDateFormatter.dateFromString(json) } return result } return nil } class func dateToJSON(date: NSDate) -> String { return jsonDateFormatter.stringFromDate(date) } class func decimalFromJSON(json: String?) -> NSDecimalNumber? { if let json = json { return NSDecimalNumber(string: json) } return nil } /** Date formatter for JSON date strings */ class var jsonDateFormatter : NSDateFormatter { struct Static { static let instance: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormatter.timeZone = NSTimeZone(name: "GMT") return dateFormatter }() } return Static.instance } class var jsonAltDateFormatter : NSDateFormatter { struct Static { static let instance: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" dateFormatter.timeZone = NSTimeZone(name: "GMT") return dateFormatter }() } return Static.instance } /** Date formatter for date strings in the UI */ private class var dateFormatter : NSDateFormatter { struct Static { static let instance: NSDateFormatter = { let df = NSDateFormatter() df.dateFormat = Styles.uniformDateFormat return df }() } return Static.instance } // NOTE: these date routines are not localized, and do not take into account user preferences for date display. /// Call setFormatterTimezone to set time zone before calling standardUIDayString or standardUIDateString class func setFormatterTimezone(timezoneOffsetSecs: Int) { let df = NutUtils.dateFormatter df.timeZone = NSTimeZone(forSecondsFromGMT:timezoneOffsetSecs) } /// Returns delta time different due to a different daylight savings time setting for a date different from the current time, assuming the location-based time zone is the same as the current default. class func dayLightSavingsAdjust(dateInPast: NSDate) -> Int { let thisTimeZone = NSTimeZone.localTimeZone() let dstOffsetForThisDate = thisTimeZone.daylightSavingTimeOffsetForDate(NSDate()) let dstOffsetForPickerDate = thisTimeZone.daylightSavingTimeOffsetForDate(dateInPast) let dstAdjust = dstOffsetForPickerDate - dstOffsetForThisDate return Int(dstAdjust) } /// Returns strings like "Mar 17, 2016", "Today", "Yesterday" /// Note: call setFormatterTimezone before this! class func standardUIDayString(date: NSDate) -> String { let df = NutUtils.dateFormatter df.dateFormat = "MMM d, yyyy" var dayString = df.stringFromDate(date) // If this year, remove year. df.dateFormat = ", yyyy" let thisYearString = df.stringFromDate(NSDate()) dayString = dayString.stringByReplacingOccurrencesOfString(thisYearString, withString: "") // Replace with today, yesterday if appropriate: only check if it's in the last 48 hours // TODO: look at using NSCalendar.startOfDayForDate and then time intervals to determine today, yesterday, Saturday, etc., back a week. if (date.timeIntervalSinceNow > -48 * 60 * 60) { if NSCalendar.currentCalendar().isDateInToday(date) { dayString = "Today" } else if NSCalendar.currentCalendar().isDateInYesterday(date) { dayString = "Yesterday" } } return dayString } /// Returns strings like "Yesterday at 9:17 am" /// Note: call setFormatterTimezone before this! class func standardUIDateString(date: NSDate) -> String { let df = NutUtils.dateFormatter let dayString = NutUtils.standardUIDayString(date) // Figure the hour/minute part... df.dateFormat = "h:mm a" var hourString = df.stringFromDate(date) // Replace uppercase PM and AM with lowercase versions hourString = hourString.stringByReplacingOccurrencesOfString("PM", withString: "pm", options: NSStringCompareOptions.LiteralSearch, range: nil) hourString = hourString.stringByReplacingOccurrencesOfString("AM", withString: "am", options: NSStringCompareOptions.LiteralSearch, range: nil) //kbw add delta hours var hoursAgo = Float(trunc(Float(date.timeIntervalSinceNow/(60.0*60.0))*10.0)/10.0) if (hoursAgo < -24.0) { //hoursAgo = hoursAgo/24.0 // hoursAgo = Double(Int(hoursAgo*10)/10.0) // replsced with built in function //hourString += " \(Float(trunc(Float(hoursAgo/24.0 )*10.0)/10.0)) days ago " } else { //hourString += " \(Float(trunc(Float(hoursAgo)*10.0)/10.0)) hours ago " } return dayString + " at " + hourString + " \t" + NSDate().timeAgoInWords(date) // } //kbw to add text to a cell - for extra information class func addOnText() -> String{ // use cases // new food - fast or digesting state? // new bgl - avg 7, 30 day, avg tod 7, 30 std dev 7, 30 // existing nut event - food insulin exercise BGL before and after, (slope delta BGL per hour // existing nut event - bgl iob? timesincenow return "test" } //kbw add function to add on text for bgl measurements class func addOnTextBGL(date: NSDate) -> String { let beforeBGLpoint = self.beforeSMBG(date); let afterBGLpoint = self.afterSMBG(date.dateByAddingTimeInterval(1.0*60.0*60.0)); let afterafterBGLpoint = self.afterSMBG(date.dateByAddingTimeInterval(2.5*60*60.0)); let averageBGLpoint = self.averageSMBGTOD(date, startDate: date.dateByAddingTimeInterval(-7.0*24*60*60.0), endDate: date) var directionString = "\u{2198}"; if(beforeBGLpoint < afterBGLpoint) {directionString = "\u{2197}";} let addOnTextString = "\n\(directionString) " + (NSString(format: "%3d to \t%3d,%3d \t%3.2fAvg\n",Int(beforeBGLpoint),Int(afterBGLpoint), Int(afterafterBGLpoint),averageBGLpoint) as String) /* + (NSString(format: "\n %3.1f/%3.1f wk/mo avg at ToD ", NutUtils.averageSMBGTOD(date.dateByAddingTimeInterval(+0.0*60.0*60.0), startDate: date.dateByAddingTimeInterval(-7.0*24.0*60.0*60.0), endDate: date.dateByAddingTimeInterval(1.0*24.0*60.0*60.0)), NutUtils.averageSMBGTOD(date.dateByAddingTimeInterval(+2.0*60.0*60.0), startDate: date.dateByAddingTimeInterval(-30.0*24.0*60.0*60.0), endDate: date)) as String) */ //future: add in delta and del / hour as well as flaging if it is moveing in the right direction and too much or too little insulin / correction. //future: advanced display averae and STDev for the past 7, 30 days as well as abg and stddev TOD for the past 7,30 days return addOnTextString } //kbw todo refactor to just find a bgl at the closest of an interval? //kbw find the SMBG before the time class func beforeSMBG(date: NSDate) ->Double { //find smbg before date, let earlyStartTime = date.dateByAddingTimeInterval(-12.0*60.0*60.0); //loadStartTime() let lateEndTime = date.dateByAddingTimeInterval(-0.0);//0.1*60.0*60.0); //kbw stream lines before and after functions // var convertedValue = CGFloat(85); // convertedValue = closestSMBG(date, startDate: earlyStartTime , endDate: lateEndTime); //return value and time? return Double(closestSMBG(date, startDate: earlyStartTime , endDate: lateEndTime)) } //kbw find the SMBG after the time class func afterSMBG(date: NSDate) ->Double { //return value and time? //find smbg before date, let earlyStartTime = date.dateByAddingTimeInterval(0.1*60.0*60.0); //loadStartTime() let lateEndTime = date.dateByAddingTimeInterval(12.0*60.0*60.0); //kbw streamlines before and after functions // var convertedValue = CGFloat(85); // convertedValue = closestSMBG(date, startDate: earlyStartTime , endDate: lateEndTime); //return value and time? return Double(closestSMBG(date, startDate: earlyStartTime , endDate: lateEndTime)) } //build function to retunr the closed bGL to a date between two dates class func closestSMBG(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ var convertedValue = CGFloat(999.9); var deltaTime = 99999999.0 do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) NSLog("\(convertedValue) \(eventTime) ") //dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } //return value and time? return convertedValue } //build function to retunr the average BGL to a date between two dates class func averageSMBG(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ return averageSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: 24.0) /* var convertedValue = CGFloat(85); var deltaTime = 99999999.0 var count = 0; var totalSMBG = CGFloat(0.0); do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) NSLog("\(convertedValue) \(eventTime) ") count = count+1; totalSMBG = totalSMBG+convertedValue //dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } //return value and time? return totalSMBG/CGFloat(count) //convertedValue */ } //build function to retunr the average BGL to a date between two dates //kbw refactor to use this method, add value to expand the window - error check window class func averageSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ return averageSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: 2.0) /* / var convertedValue = CGFloat(0); var deltaTime = 99999999.0; var timeWindow = 2.0; var count = 0; var totalSMBG = CGFloat(0.0); var minSMBG = CGFloat(-999.0); var maxSMBG = CGFloat(0.0); var sdtDev = CGFloat(0.0); do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) //NSLog("\(convertedValue) \(eventTime) ") var differenceTimeDays=centerDate.timeIntervalSinceDate(smbgEvent.time!)/(24.0*60.0*60.0) var differenceTimeHours = differenceTimeDays-Double(Int(differenceTimeDays+0.5)) if (abs(differenceTimeHours)<(timeWindow/24.0)){//only could measurement within 2 hours of centerdate NSLog("CvE\(centerDate) \(smbgEvent.time) \(differenceTimeHours)") count = count+1; totalSMBG = totalSMBG+convertedValue if (convertedValue>maxSMBG) {maxSMBG=convertedValue} if (convertedValue<minSMBG) {minSMBG=convertedValue} //dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } //return value and time? return totalSMBG/CGFloat(count) //convertedValue */ } //build function to retunr the average BGL to a date between two dates //kbw refactor to use this method, add value to expand the window - error check window class func averageSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate, timeWindow: Double)->CGFloat{ var convertedValue = CGFloat(0); var deltaTime = 99999999.0; // var timeWindow = 2.0; var count = 0; var totalSMBG = CGFloat(0.0); var minSMBG = CGFloat(-999.0); var maxSMBG = CGFloat(0.0); var sdtDev = CGFloat(0.0); do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) //NSLog("\(convertedValue) \(eventTime) ") var differenceTimeDays=centerDate.timeIntervalSinceDate(smbgEvent.time!)/(24.0*60.0*60.0) var differenceTimeHours = differenceTimeDays-Double(Int(differenceTimeDays+0.5)) if (abs(differenceTimeHours)<(timeWindow/24.0)){//only could measurement within 2 hours of centerdate NSLog("CvE\(centerDate) \(smbgEvent.time) \(differenceTimeHours)") count = count+1; totalSMBG = totalSMBG+convertedValue if (convertedValue>maxSMBG) {maxSMBG=convertedValue} if (convertedValue<minSMBG) {minSMBG=convertedValue} //dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } //return value and time? return totalSMBG/CGFloat(count) //convertedValue } class func varianceSMBG(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ return varianceSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: 24.0) } class func varianceSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ return varianceSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: 2.0) /* var variance = CGFloat(0.0) var count = CGFloat(0.0) var sum = CGFloat(0.0) var convertedValue = CGFloat(0); var deltaTime = 99999999.0; var timeWindow = 2.0; var average = self.averageSMBGTOD(centerDate, startDate: startDate, endDate: endDate) do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) //NSLog("\(convertedValue) \(eventTime) ") var differenceTimeDays=centerDate.timeIntervalSinceDate(smbgEvent.time!)/(24.0*60.0*60.0) var differenceTimeHours = differenceTimeDays-Double(Int(differenceTimeDays+0.5)) if (abs(differenceTimeHours)<(timeWindow/24.0)){//only could measurement within 2 hours of centerdate NSLog("CvE\(centerDate) \(smbgEvent.time) \(differenceTimeHours)") count = count+1; sum += (convertedValue-average)*(convertedValue-average) } } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } return sum/count */ } class func varianceSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate, timeWindow: Double)->CGFloat{ var variance = CGFloat(0.0) var count = CGFloat(0.0) var sum = CGFloat(0.0) var convertedValue = CGFloat(0); var deltaTime = 99999999.0; // var timeWindow = 2.0; var average = self.averageSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: timeWindow) do { let events = try DatabaseUtils.getTidepoolEvents(startDate, thruTime: endDate, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (abs(eventTime.timeIntervalSinceDate(centerDate))<deltaTime){ deltaTime=abs(eventTime.timeIntervalSinceDate(centerDate)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) //NSLog("\(convertedValue) \(eventTime) ") var differenceTimeDays=centerDate.timeIntervalSinceDate(smbgEvent.time!)/(24.0*60.0*60.0) var differenceTimeHours = differenceTimeDays-Double(Int(differenceTimeDays+0.5)) if (abs(differenceTimeHours)<(timeWindow/24.0)){//only could measurement within 2 hours of centerdate NSLog("CvE\(centerDate) \(smbgEvent.time) \(differenceTimeHours)") count = count+1; sum += (convertedValue-average)*(convertedValue-average) } } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } return sum/count } class func standardDeviationSMBG(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ var stdDev = CGFloat(0.0) var variance = self.varianceSMBG(centerDate, startDate: startDate, endDate: endDate) return (CGFloat(Darwin.sqrt(Double(variance)))) } class func standardDeviationSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate)->CGFloat{ var stdDev = CGFloat(0.0) var variance = self.varianceSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: 2.0) return (CGFloat(Darwin.sqrt(Double(variance)))) } class func standardDeviationSMBGTOD(centerDate: NSDate ,startDate: NSDate, endDate: NSDate, timeWindow: Double)->CGFloat{ var stdDev = CGFloat(0.0) var variance = self.varianceSMBGTOD(centerDate, startDate: startDate, endDate: endDate, timeWindow: timeWindow) return (CGFloat(Darwin.sqrt(Double(variance)))) } //kbw add fasing hour method that return a well forwatted string class func fastingHoursText(date: NSDate) -> String{ let fastingHoursTime = NutUtils.fastingHours(date) var fastingIcon = "🚫" if (fastingHoursTime>0){ if fastingHoursTime > 10.0 { fastingIcon = "\u{1F374} " //fork and knife } if fastingHoursTime > 24.0 { fastingIcon = "\u{1F37D} " //fork and knife and plate } return NSString(format: "%@Fasting hours: %3.1f",fastingIcon,fastingHoursTime) as String } else{ return NSString(format: "↗️Digesting for %3.1f hrs",fastingHoursTime+4.0) as String } }//fastingHoursText //kbw add function to return hours fasting class func fastingHours(date: NSDate) -> Double{ //dataArray = [] let maxFast = -7.0*24.0*60.0*60.0 // let endTime = date //.dateByAddingTimeInterval(timeIntervalForView) // let timeExtensionForDataFetch = NSTimeInterval(kMealTriangleTopWidth/viewPixelsPerSec) let earlyStartTime = date.dateByAddingTimeInterval(maxFast) let lateEndTime = date.dateByAddingTimeInterval(-1.0) //endTime.dateByAddingTimeInterval(timeExtensionForDataFetch) var fastingTime = maxFast do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values if (mealEvent.title!.lowercaseString.rangeOfString("🧀") != nil) { let deltaTime = eventTime.timeIntervalSinceDate(date) if (deltaTime > fastingTime) {fastingTime=deltaTime} } NSLog("\(mealEvent.title) \(fastingTime)") } } } catch let error as NSError { NSLog("Error: \(error)") } //NSLog("loaded \(dataArray.count) meal events") return -1.0*(fastingTime+(4.0*60.0*60.0))/(60.0*60.0) } //kbw add function to return hours - refactor and combine with fasting hours class func iobHours(date: NSDate) -> Double{ //dataArray = [] let maxIoB = -1.0*24.0*60.0*60.0 // let endTime = date //.dateByAddingTimeInterval(timeIntervalForView) // let timeExtensionForDataFetch = NSTimeInterval(kMealTriangleTopWidth/viewPixelsPerSec) let earlyStartTime = date.dateByAddingTimeInterval(maxIoB) let lateEndTime = date.dateByAddingTimeInterval(+0.0*60.0*60.0) //endTime.dateByAddingTimeInterval(timeExtensionForDataFetch) var iobTime = maxIoB do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values if (mealEvent.title!.lowercaseString.rangeOfString("💉novalog") != nil) { let deltaTime = eventTime.timeIntervalSinceDate(date) if (deltaTime > iobTime) {iobTime=deltaTime} } NSLog("\(mealEvent.title) \(iobTime)") } } } catch let error as NSError { NSLog("Error: \(error)") } //NSLog("loaded \(dataArray.count) meal events") return -1.0*((iobTime)/(60.0*60.0))//+(4.0*60.0*60.0))/(60.0*60.0) } //kbw a class func iobText(date: NSDate) -> String{ let iobTime = NutUtils.iobHours(date) var iobIcon = "👌" if (iobTime<2.5){ if iobTime > 1.5 { iobIcon = "❗️💉" // } else { iobIcon = "‼️💉" //syrynge } return NSString(format: "%@ IoB for %3.1f hrs",iobIcon,iobTime) as String } else{ return NSString(format: "%@ Insulin %3.1f hrs ago",iobIcon,iobTime) as String } }//iobText //kbw add function to return hours - refactor and combine with fasting hours class func bglHours(date: NSDate) -> Double{ //dataArray = [] let maxBGL = -1.0*24.0*60.0*60.0 // let endTime = date //.dateByAddingTimeInterval(timeIntervalForView) // let timeExtensionForDataFetch = NSTimeInterval(kMealTriangleTopWidth/viewPixelsPerSec) let earlyStartTime = date.dateByAddingTimeInterval(maxBGL) let lateEndTime = date.dateByAddingTimeInterval(+0.0*60.0*60.0) //endTime.dateByAddingTimeInterval(timeExtensionForDataFetch) var bglTime = maxBGL do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values if (mealEvent.title!.lowercaseString.rangeOfString("bgl") != nil) { let deltaTime = eventTime.timeIntervalSinceDate(date) if (deltaTime > bglTime) {bglTime=deltaTime} } NSLog("\(mealEvent.title) \(bglTime)") } } } catch let error as NSError { NSLog("Error: \(error)") } //NSLog("loaded \(dataArray.count) meal events") return -1.0*((bglTime)/(60.0*60.0))//+(4.0*60.0*60.0))/(60.0*60.0) } //kbw a class func bglText(date: NSDate) -> String{ let bglTime = NutUtils.bglHours(date) var bglIcon = "👌" if (bglTime > 1.5){ if bglTime > 2.0 { bglIcon = "‼️" // } else { bglIcon = "⏰" // } return NSString(format: "%@ been %3.1f hrs \n time to check BGL",bglIcon,bglTime) as String } else{ return NSString(format: "%@ BGL checked %3.1f hrs ago",bglIcon,bglTime) as String } }//bglText //kbw add function to return hours - refactor and combine with fasting hours class func tdd24String(date: NSDate) -> String{ //dataArray = [] var tddString = " " var tddCount = 0 // let endTime = date //.dateByAddingTimeInterval(timeIntervalForView) // let timeExtensionForDataFetch = NSTimeInterval(kMealTriangleTopWidth/viewPixelsPerSec) let earlyStartTime = date.dateByAddingTimeInterval(-1.0*24*60*60) let lateEndTime = date.dateByAddingTimeInterval(+0.0*60.0*60.0) //endTime.dateByAddingTimeInterval(timeExtensionForDataFetch) //var iobTime = maxIoB tddString="" do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values if (mealEvent.title!.lowercaseString.rangeOfString("💉novalog") != nil) { tddCount++ tddString = tddString + mealEvent.notes! + "\n" } } } } catch let error as NSError { NSLog("Error: \(error)") } //NSLog("loaded \(dataArray.count) meal events") return tddString + "-\(tddCount) shots in the last 24 hours" } class func weekTDDString(date: NSDate) -> String{ //dataArray = [] var weekString = " " var weekCount = 0 // let endTime = date //.dateByAddingTimeInterval(timeIntervalForView) // let timeExtensionForDataFetch = NSTimeInterval(kMealTriangleTopWidth/viewPixelsPerSec) let earlyStartTime = date.dateByAddingTimeInterval(-7.0*24*60*60) let lateEndTime = date.dateByAddingTimeInterval(+0.0*60.0*60.0) //endTime.dateByAddingTimeInterval(timeExtensionForDataFetch) //var iobTime = maxIoB weekString="" do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values if (mealEvent.title!.lowercaseString.rangeOfString("💉tdd") != nil) { weekCount++ weekString = weekString + (NSString(format:"aBGL %3.1f\t", self.averageSMBG(mealEvent.time!, startDate: mealEvent.time!.dateByAddingTimeInterval(-1.0*24*60*60.0), endDate: mealEvent.time!)) as String) as String + mealEvent.notes! + "\n" } } } } catch let error as NSError { NSLog("Error: \(error)") } //NSLog("loaded \(dataArray.count) meal events") return weekString + "-\(weekCount) days with TDD " }// end weekTDD class func avgSMBGToDbyHour (date :NSDate) -> String{ //kbw averge 7 and 30 day var convertedValue = CGFloat(0); var deltaTime = 99999999.0; // var timeWindow = 2.0; var count = 0; var totalSMBG = CGFloat(0.0); var minSMBG = CGFloat(-999.0); var maxSMBG = CGFloat(0.0); var sdtDev = CGFloat(0.0); var countArray: [Int] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var totalSMBGArray: [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var minSMBGArray : [CGFloat] = [-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,]; var maxSMBGArray : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var sdtDevArray : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var count1Star = 0 var count2Star = 0 var count3Star = 0 var countArray30: [Int] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var totalSMBGArray30: [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var minSMBGArray30 : [CGFloat] = [-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,]; var maxSMBGArray30 : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var sdtDevArray30 : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var count1Star30 = 0 var count2Star30 = 0 var count3Star30 = 0 var countArray7: [Int] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var totalSMBGArray7: [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var minSMBGArray7 : [CGFloat] = [-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,-999.0,]; var maxSMBGArray7 : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var sdtDevArray7 : [CGFloat] = [0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0 ,0,0,0,0,0]; var count1Star7 = 0 var count2Star7 = 0 var count3Star7 = 0 var resultsString = "" let targetBGL = 83.0 let presentHour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate()) do { let events = try DatabaseUtils.getTidepoolEvents(date.dateByAddingTimeInterval(-90.0*24.0*60.0*60), thruTime: date, objectTypes: ["smbg"])//[typeString()]) for event in events { if let event = event as? CommonData { if let eventTime = event.time { if (true) //(abs(eventTime.timeIntervalSinceDate(date))<deltaTime) { deltaTime=abs(eventTime.timeIntervalSinceDate(date)) if let smbgEvent = event as? SelfMonitoringGlucose { //NSLog("Adding smbg event: \(event)") if let value = smbgEvent.value { let kGlucoseConversionToMgDl = CGFloat(18.0) convertedValue = round(CGFloat(value) * kGlucoseConversionToMgDl) count = count+1; totalSMBG = totalSMBG+convertedValue if (convertedValue>maxSMBG) {maxSMBG=convertedValue} if (convertedValue<minSMBG) {minSMBG=convertedValue} // calc integer value of the hour let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: eventTime) // use that for an array based version of the above statements countArray[hour]=countArray[hour]+1 totalSMBGArray[hour] = totalSMBGArray[hour]+convertedValue if(eventTime.timeIntervalSinceNow > -30.0*24.0*60*60.0 ) { countArray30[hour]=countArray30[hour]+1 totalSMBGArray30[hour] = totalSMBGArray30[hour]+convertedValue if(eventTime.timeIntervalSinceNow > -7.0*24.0*60*60.0 ) { countArray7[hour]=countArray7[hour]+1 totalSMBGArray7[hour] = totalSMBGArray7[hour]+convertedValue }//7 day }//30 day //NSLog("\(convertedValue) \(eventTime) ") var differenceTimeDays=date.timeIntervalSinceDate(smbgEvent.time!)/(24.0*60.0*60.0) var differenceTimeHours = differenceTimeDays-Double(Int(differenceTimeDays+0.5)) if (abs(differenceTimeHours)<(1.0/24.0)){//only could measurement within 2 hours of centerdate // NSLog("CvE\(centerDate) \(smbgEvent.time) \(differenceTimeHours)") // count = count+1; // totalSMBG = totalSMBG+convertedValue // if (convertedValue>maxSMBG) {maxSMBG=convertedValue} // if (convertedValue<minSMBG) {minSMBG=convertedValue} //dataArray.append(CbgGraphDataType(value: convertedValue, timeOffset: timeOffset)) } } else { NSLog("ignoring smbg event with nil value") } } } } } } } catch let error as NSError { NSLog("Error: \(error)") } for (var i=0;i<24;i++){ resultsString = resultsString + (NSString(format:"\n%dhr:",i) as String) if presentHour == i { resultsString = resultsString + "*" } if countArray7[i]==0 { resultsString = resultsString + (NSString(format:"\t%d \t\t",countArray7[i]) as String) } else { var tempCount = NSString(format: "%d",countArray7[i]) if countArray7[i] < 3 {tempCount = (tempCount as String) + "*"} resultsString = resultsString + (NSString(format:"\t%@ \t%3.1f",tempCount,Double(totalSMBGArray7[i])/Double(countArray7[i])) as String) var tempBGLDelta = abs((Double(totalSMBGArray7[i])/Double(countArray7[i]))-targetBGL) if (tempBGLDelta<20) { resultsString = resultsString + "" if (tempBGLDelta<12) { resultsString = resultsString + "*" count1Star7 = count1Star7+1 if (tempBGLDelta<6) { resultsString = resultsString + "*" count2Star7 = count2Star7+1 if (tempBGLDelta<3.5) { resultsString = resultsString + "*" count3Star7 = count3Star7+1 } else{ // not in tightest group if ((Double(totalSMBGArray7[i])/Double(countArray7[i]))-targetBGL)<0 { resultsString = resultsString + ".." } } } else{// not in 2nd tightest group if ((Double(totalSMBGArray7[i])/Double(countArray7[i]))-targetBGL)<0 { resultsString = resultsString + "...." } } } else{// not in 3nd tightest group if ((Double(totalSMBGArray7[i])/Double(countArray7[i]))-targetBGL)<0 { resultsString = resultsString + "......" } } } } if countArray30[i]==0 { resultsString = resultsString + (NSString(format:"\t%d\t\t",countArray30[i]) as String) } else { resultsString = resultsString + (NSString(format:"\t|\t%3.1f",Double(totalSMBGArray30[i])/Double(countArray30[i])) as String) var tempBGLDelta = abs((Double(totalSMBGArray30[i])/Double(countArray30[i]))-targetBGL) if (tempBGLDelta<20) { resultsString = resultsString + "" if (tempBGLDelta<12) { resultsString = resultsString + "*" count1Star30 += 1 if (tempBGLDelta<6) { resultsString = resultsString + "*" count2Star30 += 1 if (tempBGLDelta<3.5) { resultsString = resultsString + "*" count3Star30 += 1 } } } } } resultsString = resultsString + (NSString(format:"\t|\t%3.1f",Double(totalSMBGArray[i])/Double(countArray[i])) as String) var tempBGLDelta = abs((Double(totalSMBGArray[i])/Double(countArray[i]))-targetBGL) if (tempBGLDelta<20) { resultsString = resultsString + "'" if (tempBGLDelta<12) { resultsString = resultsString + "'" count1Star += 1 if (tempBGLDelta<6) { resultsString = resultsString + "'" count2Star = count2Star+1 if (tempBGLDelta<3.5) { resultsString = resultsString + "'" count3Star = count3Star+1 } } } } } resultsString = resultsString + "\n" + (NSString(format: "*** \t\t%d \t\t\t%d \t\t\t%d", count3Star7,count3Star30,count3Star) as String) resultsString = resultsString + "\n" + (NSString(format: "** \t\t\t%d \t\t\t%d \t\t\t%d", count2Star7,count2Star30,count2Star) as String) resultsString = resultsString + "\n" + (NSString(format: "* \t\t\t%d \t\t\t%d \t\t\t%d", count1Star7,count1Star30,count1Star) as String) return resultsString //"\n30d: \(count) \(Double(totalSMBG)/Double(count))"+resultsString // \nmidnight \n1am \n2am \n3am \n4am \n5am \n6am \n7am \n8am \n9am \n10am \n11am \nNoon \n1pm \n2pm \n3pm \n4pm \n5pm \n6pm \n7pm \n8pm \n9pm \n10pm \n11pm " } class func generateCSV() -> String{ let csvString = nutEventCSVString return csvString() } class func nutEventCSVString() -> String{ var nutString = "" let date = NSDate() let maxFast = -356.0*24.0*60.0*60.0 let earlyStartTime = date.dateByAddingTimeInterval(maxFast) let lateEndTime = date.dateByAddingTimeInterval(-1.0) // do { let events = try DatabaseUtils.getMealEvents(earlyStartTime, toTime: lateEndTime) for mealEvent in events { if let eventTime = mealEvent.time { //kbw filter out bgl values //NSLog(" \(mealEvent.title!) \(mealEvent.notes!)") nutString = (NSString(format: "nut event scan: %@,%@,",mealEvent.time!,mealEvent.title!,mealEvent.notes!) as String) as String NSLog("\(nutString)") } } } catch let error as NSError { NSLog("Error: \(error)") } return nutString } class func nutEventIsDue(nutEvent: NutEvent) -> Bool { var addOnText = "" var addOnTextExpire = "" var timeSinceNow=nutEvent.itemArray[nutEvent.itemArray.count-1].time.timeIntervalSinceNow var timeActive = 0.0 var timeExpire = -365.0*24.0*60*60 for item in nutEvent.itemArray { //KBW is there an activity tag? if item.notes.rangeOfString("#A(") != nil { var minInTextArr = item.notes.characters.split("(") var minInText = String(minInTextArr[1]) var minInTextArr2 = minInText.characters.split(")") var minInTextNum = String(minInTextArr2[0]) //[item.notes.rangeOfString("#A(")!] //let tempString = minInTextArr NSLog("**Active tag found in %@ with note \(item.notes) ",item.title) NSLog(" number string ")//\(String(minInTextNum))") ///addOnText="****Active****" //parse out time timeActive = -4.0 * 60.0 * 60.0 //minInTextNum = "10" timeActive = -60.0*Double(minInTextNum)! addOnText="****Active****" var addOnTextArr = item.notes.characters.split("\"") if (addOnTextArr.count > 1) { addOnText = String(addOnTextArr[1]) } else { //addOnText = String("****Active****") } //and copy add on text //titleLabel.textColor = UIColor.redColor() }//End activity tag if item.notes.rangeOfString("#D(") != nil { var minInTextArr = item.notes.characters.split("(") var minInText = String(minInTextArr[1]) var minInTextArr2 = minInText.characters.split(")") var minInTextNum = String(minInTextArr2[0]) //[item.notes.rangeOfString("#A(")!] //let tempString = minInTextArr NSLog("***DUE tag found in %@ with note \(item.notes) ",item.title) NSLog(" number string ")//\(String(minInTextNum))") ///addOnText="****Active****" //parse out time timeExpire = -24.0 * 60.0 * 60.0 timeExpire = -60.0*Double(minInTextNum)! addOnText="****Active****" var addOnTextArr = item.notes.characters.split("\"") if (addOnTextArr.count > 1) { addOnTextExpire = String(addOnTextArr[1]) } else { //addOnText = String("****Active****") } //and copy add on text //titleLabel.textColor = UIColor.redColor() }//End Due tag if item.notes.lowercaseString.rangeOfString("#daily") != nil { timeExpire = -23.5*60.0*60 addOnTextExpire = "" } if item.notes.lowercaseString.rangeOfString("#weekly") != nil { timeExpire = -6.75*24.0*60.0*60 addOnTextExpire = "" } //KBW Find the most recent time if timeSinceNow < item.time.timeIntervalSinceNow { timeSinceNow = item.time.timeIntervalSinceNow NSLog("**** found better time****") } }// loop through nut array NSLog(" Is the event DUE \(timeSinceNow) \(timeExpire)") return (timeSinceNow < (timeExpire)) } //end of nutEventIsDue }
d39a0ac1d4d30bda9705c1a2f09d54aa
43.819772
220
0.514201
false
false
false
false
AlexChekanov/Gestalt
refs/heads/dev
05-filtering-operators/starter/RxSwiftPlayground/Pods/RxSwift/RxSwift/Observables/Generate.swift
apache-2.0
102
// // Generate.swift // RxSwift // // Created by Krunoslav Zaher on 9/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension Observable { /** Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to run the loop send out observer messages. - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) - parameter initialState: Initial state. - parameter condition: Condition to terminate generation (upon returning `false`). - parameter iterate: Iteration step function. - parameter scheduler: Scheduler on which to run the generator loop. - returns: The generated sequence. */ public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> { return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) } } final fileprivate class GenerateSink<S, O: ObserverType> : Sink<O> { typealias Parent = Generate<S, O.E> private let _parent: Parent private var _state: S init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _state = parent._initialState super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.scheduleRecursive(true) { (isFirst, recurse) -> Void in do { if !isFirst { self._state = try self._parent._iterate(self._state) } if try self._parent._condition(self._state) { let result = try self._parent._resultSelector(self._state) self.forwardOn(.next(result)) recurse(false) } else { self.forwardOn(.completed) self.dispose() } } catch let error { self.forwardOn(.error(error)) self.dispose() } } } } final fileprivate class Generate<S, E> : Producer<E> { fileprivate let _initialState: S fileprivate let _condition: (S) throws -> Bool fileprivate let _iterate: (S) throws -> S fileprivate let _resultSelector: (S) throws -> E fileprivate let _scheduler: ImmediateSchedulerType init(initialState: S, condition: @escaping (S) throws -> Bool, iterate: @escaping (S) throws -> S, resultSelector: @escaping (S) throws -> E, scheduler: ImmediateSchedulerType) { _initialState = initialState _condition = condition _iterate = iterate _resultSelector = resultSelector _scheduler = scheduler super.init() } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
63b2da87a541d4b56929f4e0302159ca
37.275862
213
0.611712
false
false
false
false
EvsenevDev/SmartReceiptsiOS
refs/heads/master
SmartReceipts/Modules/Payment Methods/PaymentMethodsView.swift
agpl-3.0
2
// // PaymentMethodsView.swift // SmartReceipts // // Created by Bogdan Evsenev on 14/07/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import UIKit import Viperit import RxSwift //MARK: - Public Interface Protocol protocol PaymentMethodsViewInterface { } //MARK: PaymentMethodsView Class final class PaymentMethodsView: FetchedTableViewController { @IBOutlet private weak var addItem: UIBarButtonItem! private let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() title = LocalizedString("payment_methods") addItem.rx.tap .subscribe(onNext: { [unowned self] in _ = self.showEditPaymentMethod().bind(to: self.presenter.paymentMethodAction) }).disposed(by: bag) } override func configureCell(cell: UITableViewCell, item: Any) { let method = item as! PaymentMethod cell.textLabel?.text = method.method } override func createFetchedModelAdapter() -> FetchedModelAdapter? { return presenter.fetchedModelAdapter() } override func delete(object: Any!, at indexPath: IndexPath) { presenter.deleteSubject.onNext(object as! PaymentMethod) } override func tappedObject(_ tapped: Any, indexPath: IndexPath) { let method = tapped as! PaymentMethod showEditPaymentMethod(method) .bind(to: presenter.paymentMethodAction) .disposed(by: bag) } func showEditPaymentMethod(_ method: PaymentMethod? = nil) -> Observable<PaymentMethodAction> { return Observable<PaymentMethodAction>.create({ [unowned self] observer -> Disposable in let isEdit = method != nil let title = isEdit ? LocalizedString("payment_method_edit") : LocalizedString("payment_method_add") let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.placeholder = LocalizedString("payment_method") textField.text = method?.method } let saveTitle = isEdit ? LocalizedString("update") : LocalizedString("add") alert.addAction(UIAlertAction(title: saveTitle, style: .default, handler: { [unowned self] _ in let pm = method ?? PaymentMethod() let method = alert.textFields!.first!.text if self.validate(method: method) { pm.method = method observer.onNext((pm: pm, update: isEdit)) } })) alert.addAction(UIAlertAction(title: LocalizedString("DIALOG_CANCEL"), style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) return Disposables.create() }) } private func validate(method: String?) -> Bool { if method == nil || method!.isEmpty { presenter.presentAlert(title: LocalizedString("generic_error_alert_title"), message: LocalizedString("edit_payment_method_controller_save_error_message")) return false } return true } } //MARK: - Public interface extension PaymentMethodsView: PaymentMethodsViewInterface { } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension PaymentMethodsView { var presenter: PaymentMethodsPresenter { return _presenter as! PaymentMethodsPresenter } var displayData: PaymentMethodsDisplayData { return _displayData as! PaymentMethodsDisplayData } }
a6d04e056a2426605a134ad427f777e5
34.095238
114
0.628494
false
false
false
false
AlphaJian/LarsonApp
refs/heads/master
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderStaticView.swift
apache-2.0
1
// // WorkOrderStaticView.swift // LarsonApp // // Created by Perry Z Chen on 11/10/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class WorkOrderStaticView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! private var strTitle = "" private var strContent = "" func initUI(parameter: (String, String), labelWidth: CGFloat) { self.contentLabel.preferredMaxLayoutWidth = labelWidth - 30 self.strTitle = parameter.0 self.strContent = "\(parameter.1)\(parameter.1)\(parameter.1)\(parameter.1)" self.titleLabel.text = self.strTitle self.contentLabel.text = self.strContent // self.titleLabel.text = parameter.0 // self.contentLabel.text = "\(parameter.1)\(parameter.1)\(parameter.1)\(parameter.1)" // self.contentLabel.layoutIfNeeded() // self.layoutIfNeeded() } }
d75e9cb4837b81eb61d74f8e170f45cc
25.977273
93
0.64027
false
false
false
false
SwiftKitz/Appz
refs/heads/master
Appz/AppzTests/AppsTests/BehanceTests.swift
mit
1
// // BehanceTests.swift // Appz // // Created by Mariam AlJamea on 6/17/17. // Copyright © 2017 kitz. All rights reserved. // import XCTest @testable import Appz class BehanceTests: XCTestCase { let appCaller = ApplicationCallerMock() func testConfiguration() { let behance = Applications.Behance() XCTAssertEqual(behance.scheme, "behance:") XCTAssertEqual(behance.fallbackURL, "https://www.behance.net/") } func testOpen() { let action = Applications.Behance.Action.open XCTAssertEqual(action.paths.app.pathComponents, ["app"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } func testUserProfile() { let profile = "StudioAIO" let action = Applications.Behance.Action.userProfile(profile) XCTAssertEqual(action.paths.app.pathComponents, ["profile", profile]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web.pathComponents, [profile]) XCTAssertEqual(action.paths.web.queryParameters, [:]) } }
097db8954e5255f58d9410e4b95218f5
27.095238
77
0.64322
false
true
false
false
RCacheaux/BitbucketKit
refs/heads/master
Sources/iOS/Private/Remote/Details/Parsers/Implementations/ObjectMapperRepoParser.swift
apache-2.0
1
// Copyright © 2016 Atlassian Pty Ltd. All rights reserved. import Foundation import ObjectMapper extension Repo: Mappable { public init?(_ map: Map) { self.name = "" self.description = "" self.owner = User(username: "", displayName: "", avatarURL: NSURL()) } public mutating func mapping(map: Map) { name <- map["name"] description <- map ["description"] owner <- map["owner"] } } public class ObjectMapperRepoParser: RepoParser { func repoFromData(data: NSData, onComplete: (outcome: Outcome<Repo>)->Void) { dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { guard let JSONString = String(data: data, encoding: NSUTF8StringEncoding) else { onComplete(outcome: Outcome<Repo>.error(BitbucketKit.Error.genericError)) return } guard let repo = Mapper<Repo>().map(JSONString) else { onComplete(outcome: Outcome<Repo>.error(BitbucketKit.Error.genericError)) return } onComplete(outcome: Outcome<Repo>.success(repo)) } } }
938685e1873fc33fd407f3cd235e37cd
29.705882
86
0.665709
false
false
false
false
JGiola/swift
refs/heads/main
test/SILGen/opaque_result_type_private.swift
apache-2.0
9
// RUN: %target-swift-emit-silgen -primary-file %s -disable-availability-checking | %FileCheck %s // RUN: %target-swift-emit-sil -primary-file %s -O -disable-availability-checking // CHECK-LABEL: sil [ossa] @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { // CHECK: [[BOX:%.*]] = alloc_stack $PrivateClass // CHECK: [[FN:%.*]] = function_ref @$s26opaque_result_type_private19returnPrivateOpaqueQryF : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <PrivateClass> // CHECK: apply [[FN]]([[BOX]]) : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <PrivateClass> // CHECK: [[RESULT:%.*]] = load [take] [[BOX]] : $*PrivateClass // CHECK: destroy_value [[RESULT]] : $PrivateClass // CHECK: dealloc_stack [[BOX]] : $*PrivateClass _ = returnPrivateOpaque() // CHECK: [[BOX:%.*]] = alloc_stack $LocalClass // CHECK: [[FN:%.*]] = function_ref @$s26opaque_result_type_private17returnLocalOpaqueQryF : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <LocalClass> // CHECK: apply [[FN]]([[BOX]]) : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <LocalClass> // CHECK: [[RESULT:%.*]] = load [take] [[BOX]] : $*LocalClass // CHECK: destroy_value [[RESULT]] : $LocalClass // CHECK: dealloc_stack [[BOX]] : $*LocalClass _ = returnLocalOpaque() fileprivate class PrivateClass {} // CHECK-LABEL: sil hidden [ossa] @$s26opaque_result_type_private19returnPrivateOpaqueQryF : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <@_opaqueReturnTypeOf("$s26opaque_result_type_private19returnPrivateOpaqueQryF", 0) __> func returnPrivateOpaque() -> some Any { return PrivateClass() } // CHECK-LABEL: sil hidden [ossa] @$s26opaque_result_type_private17returnLocalOpaqueQryF : $@convention(thin) @substituted <τ_0_0> () -> @out τ_0_0 for <@_opaqueReturnTypeOf("$s26opaque_result_type_private17returnLocalOpaqueQryF", 0) __> func returnLocalOpaque() -> some Any { class LocalClass {} return LocalClass() }
9132507d38d08100a518c48606c06bcb
58.088235
241
0.681434
false
false
false
false
fluidpixel/SquashTracker
refs/heads/master
SquashTracker/SwiftCharts/Axis/ChartAxisValuesGenerator.swift
gpl-2.0
1
// // ChartAxisValuesGenerator.swift // swift_charts // // Created by ischuetz on 12/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public typealias ChartAxisValueGenerator = (CGFloat) -> ChartAxisValue // Dynamic axis values generation public struct ChartAxisValuesGenerator { public static func generateXAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: CGFloat, maxSegmentCount: CGFloat, multiple: CGFloat = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.x}) } public static func generateYAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: CGFloat, maxSegmentCount: CGFloat, multiple: CGFloat = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { return self.generateAxisValuesWithChartPoints(chartPoints, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge, axisPicker: {$0.y}) } private static func generateAxisValuesWithChartPoints(chartPoints: [ChartPoint], minSegmentCount: CGFloat, maxSegmentCount: CGFloat, multiple: CGFloat = 10, axisValueGenerator: ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool, axisPicker: (ChartPoint) -> ChartAxisValue) -> [ChartAxisValue] { let sortedChartPoints = chartPoints.sort {(obj1, obj2) in return axisPicker(obj1).scalar < axisPicker(obj2).scalar } if let first = sortedChartPoints.first, last = sortedChartPoints.last { return self.generateAxisValuesWithChartPoints(axisPicker(first).scalar, last: axisPicker(last).scalar, minSegmentCount: minSegmentCount, maxSegmentCount: maxSegmentCount, multiple: multiple, axisValueGenerator: axisValueGenerator, addPaddingSegmentIfEdge: addPaddingSegmentIfEdge) } else { print("Trying to generate Y axis without datapoints, returning empty array") return [] } } private static func generateAxisValuesWithChartPoints(first: CGFloat, last: CGFloat, minSegmentCount: CGFloat, maxSegmentCount: CGFloat, multiple: CGFloat, axisValueGenerator:ChartAxisValueGenerator, addPaddingSegmentIfEdge: Bool) -> [ChartAxisValue] { if last < first { fatalError("Invalid range generating axis values") } else if last == first { return [] } var firstValue = first - (first % multiple) var lastValue = last + (abs(multiple - last) % multiple) var segmentSize = multiple if firstValue == first && addPaddingSegmentIfEdge { firstValue = firstValue - segmentSize } if lastValue == last && addPaddingSegmentIfEdge { lastValue = lastValue + segmentSize } let distance = lastValue - firstValue var currentMultiple = multiple var segmentCount = distance / currentMultiple while segmentCount > maxSegmentCount { currentMultiple *= 2 segmentCount = distance / currentMultiple } segmentCount = ceil(segmentCount) while segmentCount < minSegmentCount { segmentCount++ } segmentSize = currentMultiple let offset = firstValue return (0...Int(segmentCount)).map {segment in let scalar = offset + (CGFloat(segment) * segmentSize) return axisValueGenerator(scalar) } } }
b353d6555c789ad9f1f1ec84cac6aab6
49.102564
302
0.702661
false
false
false
false
github/codeql
refs/heads/main
swift/ql/test/query-tests/Security/CWE-311/testAlamofire.swift
mit
1
// --- Foundation stubs --- class NSObject { } struct URL { } struct URLRequest { } class URLResponse: NSObject { } class HTTPURLResponse : URLResponse { } // --- Alamofire stubs --- protocol URLConvertible { } extension String: URLConvertible { } struct HTTPMethod { static let get = HTTPMethod(rawValue: "GET") static let post = HTTPMethod(rawValue: "POST") init(rawValue: String) {} } struct HTTPHeaders { init(_ dictionary: [String: String]) {} mutating func add(name: String, value: String) {} mutating func update(name: String, value: String) {} } extension HTTPHeaders: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, String)...) {} } typealias Parameters = [String: Any] protocol ParameterEncoding { } struct URLEncoding: ParameterEncoding { static var `default`: URLEncoding { URLEncoding() } } protocol ParameterEncoder { } class URLEncodedFormParameterEncoder: ParameterEncoder { static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() } } protocol RequestInterceptor { } class Request { } class DataRequest: Request { } final class DataStreamRequest: Request { } class DownloadRequest: Request { struct Options: OptionSet { let rawValue: Int init(rawValue: Int) { self.rawValue = rawValue } } typealias Destination = (_ temporaryURL: URL, _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options) } class Session { static let `default` = Session() typealias RequestModifier = (inout URLRequest) throws -> Void func request( _ convertible: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil, requestModifier: RequestModifier? = nil) -> DataRequest { return DataRequest() } func request<Parameters: Encodable>( _ convertible: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil, requestModifier: RequestModifier? = nil) -> DataRequest { return DataRequest() } func streamRequest( _ convertible: URLConvertible, method: HTTPMethod = .get, headers: HTTPHeaders? = nil, automaticallyCancelOnStreamError: Bool = false, interceptor: RequestInterceptor? = nil, requestModifier: RequestModifier? = nil) -> DataStreamRequest { return DataStreamRequest() } func download( _ convertible: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, interceptor: RequestInterceptor? = nil, requestModifier: RequestModifier? = nil, to destination: DownloadRequest.Destination? = nil) -> DownloadRequest { return DownloadRequest() } // (there are many more variants of `request`, `streamRequest` and `download`) } let AF = Session.default // --- tests --- struct MyEncodable: Encodable { let value: String } func test1(username: String, password: String, email: String, harmless: String) { // sensitive data in URL AF.request("http://example.com/login?p=" + password) // BAD AF.request("http://example.com/login?h=" + harmless) // GOOD (not sensitive) AF.streamRequest("http://example.com/login?p=" + password) // BAD AF.streamRequest("http://example.com/login?h=" + harmless) // GOOD (not sensitive) AF.download("http://example.com/" + email + ".html") // BAD AF.download("http://example.com/" + harmless + ".html") // GOOD (not sensitive) // sensitive data in parameters let params1 = ["value": email] let params2 = ["value": harmless] AF.request("http://example.com/", parameters: params1) // BAD [NOT DETECTED] AF.request("http://example.com/", parameters: params2) // GOOD (not sensitive) AF.request("http://example.com/", parameters: params1, encoding: URLEncoding.default) // BAD [NOT DETECTED] AF.request("http://example.com/", parameters: params2, encoding: URLEncoding.default) // GOOD (not sensitive) AF.request("http://example.com/", parameters: params1, encoder: URLEncodedFormParameterEncoder.default) // BAD [NOT DETECTED] AF.request("http://example.com/", parameters: params2, encoder: URLEncodedFormParameterEncoder.default) // GOOD (not sensitive) AF.download("http://example.com/", parameters: params1) // BAD [NOT DETECTED] AF.download("http://example.com/", parameters: params2) // GOOD (not sensitive) let params3 = ["values": ["...", email, "..."]] let params4 = ["values": ["...", harmless, "..."]] AF.request("http://example.com/", method:.post, parameters: params3) // BAD [NOT DETECTED] AF.request("http://example.com/", method:.post, parameters: params4) // GOOD (not sensitive) let params5 = MyEncodable(value: email) let params6 = MyEncodable(value: harmless) AF.request("http://example.com/", parameters: params5) // BAD [NOT DETECTED] AF.request("http://example.com/", parameters: params6) // GOOD (not sensitive) // request headers // - in real usage a password here would normally be base64 encoded for transmission // - the risk is greatly reduced (but not eliminated) if HTTPS is used let headers1: HTTPHeaders = ["Authorization": username + ":" + password] let headers2: HTTPHeaders = ["Value": harmless] AF.request("http://example.com/", headers: headers1) // BAD [NOT DETECTED] AF.request("http://example.com/", headers: headers2) // GOOD (not sensitive) AF.streamRequest("http://example.com/", headers: headers1) // BAD [NOT DETECTED] AF.streamRequest("http://example.com/", headers: headers2) // GOOD (not sensitive) let headers3 = HTTPHeaders(["Authorization": username + ":" + password]) let headers4 = HTTPHeaders(["Value": harmless]) AF.request("http://example.com/", headers: headers3) // BAD [NOT DETECTED] AF.request("http://example.com/", headers: headers4) // GOOD (not sensitive) AF.download("http://example.com/", headers: headers1) // BAD [NOT DETECTED] AF.download("http://example.com/", headers: headers2) // GOOD (not sensitive) var headers5 = HTTPHeaders([:]) var headers6 = HTTPHeaders([:]) headers5.add(name: "Authorization", value: username + ":" + password) headers6.add(name: "Data", value: harmless) AF.request("http://example.com/", headers: headers5) // BAD [NOT DETECTED] AF.request("http://example.com/", headers: headers6) // GOOD (not sensitive) var headers7 = HTTPHeaders([:]) var headers8 = HTTPHeaders([:]) headers7.update(name: "Authorization", value: username + ":" + password) headers8.update(name: "Data", value: harmless) AF.request("http://example.com/", headers: headers7) // BAD [NOT DETECTED] AF.request("http://example.com/", headers: headers8) // GOOD (not sensitive) }
f283c57515f2134465607ab5d0c6397c
30.362385
128
0.709375
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGImagePickerControllerDemo/MGImagePickerControllerDemo/MGPhotosBrowseController.swift
mit
1
// // MGPhotosBrowseController.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/8. // Copyright © 2019 MG. All rights reserved. // import UIKit import Photos class MGPhotosBrowseController: UIViewController { struct MGPhotoBrowseViewModelAssociate { static let MG_photoBrowViewEndDeceleratingAssociate = UnsafeRawPointer(bitPattern: "mg_photoBrowViewEndDeceleratingAssociate".hashValue) } private let kMGPhotosBrowseCellID = "kMGPhotosBrowseCellID" let mg_deselectedImage = UIImage(named: "MGDeselected") let mg_selectedImage = UIImage(named: "MGSelected") let mg_photoBackImage = UIImage(named: "MGPhotoBack") // MARK: public /// 当前图片的位置指数 var current : Int = 0 /// 是否是缩略图 var isSelectOriginalPhoto: Bool = false lazy var MGScreenScale: CGFloat = { if (UIScreen.main.bounds.width > 700) { return 1.5; } return 2.0 }() /// 存储图片所有资源对象 var allAssets = [PHAsset]() /// 所有选择的的图片资源 var allPhotoAssets = [PHAsset]() /// 浏览控制器将要消失的回调 var mg_browseWilldisappearHandle : (() -> Void)? var isHiddenBar: Bool = false // MARK: private /// 展示图片的collectionView lazy fileprivate var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = self.view.frame.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 let collection : UICollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height), collectionViewLayout: layout) collection.delegate = self collection.dataSource = self collection.isPagingEnabled = true collection.showsHorizontalScrollIndicator = false if #available(iOS 10, *) { collection.prefetchDataSource = self } collection.register(MGPhotosBrowseCell.self, forCellWithReuseIdentifier: kMGPhotosBrowseCellID) return collection }() /// 顶部的bar lazy fileprivate var topBar: UIView = { let topBar : UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: DeviceTools.isIphoneX ? 88:64)) // topBar.barStyle = .black topBar.backgroundColor = UIColor.black.withAlphaComponent(0.5) // topBar.setBackgroundImage(UIColor.black.withAlphaComponent(0.6).mg_image, for: UIBarMetrics.default) return topBar }() /// 返回 lazy fileprivate var backItem: UIButton = { //位置 let backItem = UIButton(frame: CGRect(x: 5, y: self.topBar.bounds.height - 44, width: 44, height: 44)) // backItem.center = CGPoint(x: backItem.center.x, y: (self.topBar.bounds.height - 44) / 2) //属性 backItem.setImage(mg_photoBackImage, for: .normal) backItem.setTitleColor(.white, for: .normal) backItem.titleLabel?.font = .systemFont(ofSize: 30) backItem.titleLabel?.textAlignment = .center //响应 backItem.action(at: .touchUpInside, handle: { [weak self](sender) in self?.navigationController?.popViewController(animated: true) }) return backItem }() /// 选择 lazy fileprivate var selectedItem : UIButton = { let button : UIButton = UIButton(frame: CGRect(x: self.topBar.bounds.width - 44 - 10, y: self.topBar.bounds.height - 44, width: 44, height: 44)) // button.center = CGPoint(x: button.center.x, y: (self.topBar.bounds.height - 44) / 2) button.imageEdgeInsets = UIEdgeInsets(top: 12, left: 10, bottom: 8, right: 10) button.setImage(mg_deselectedImage, for: .normal) button.action(at: .touchUpInside, handle: {[weak self] (sender) in self!.select() }) return button }() /// 底部的tabBar lazy fileprivate var bottomBar : UITabBar = { let safeBottomHeight: CGFloat = DeviceTools.isIphoneX ? 60:44 let bottomBar :UITabBar = UITabBar(frame: CGRect(x: 0, y: self.view.bounds.height - safeBottomHeight, width: self.view.bounds.width, height: safeBottomHeight)) bottomBar.barStyle = .black bottomBar.backgroundImage = UIColor.black.withAlphaComponent(0.6).mg_image return bottomBar }() /// 发送按钮 lazy fileprivate var sendButton : UIButton = { let button : UIButton = UIButton(frame: CGRect(x: self.bottomBar.bounds.width - 50 - 5, y: 0, width: 50, height: 40)) button.center = CGPoint(x: button.center.x, y: self.bottomBar.bounds.height / 2) button.setTitle("发送", for: .normal) button.setTitleColor(0x2dd58a.mg_color, for: .normal) button.setTitleColor(0x2DD58A.mg_color.withAlphaComponent(0.25), for: .disabled) button.titleLabel?.font = .systemFont(ofSize: 15) button.titleLabel?.textAlignment = .center button.action(at: .touchUpInside, handle: { [weak self](sender) in if let strongSelf = self { //获得筛选的数组 let assets = MGPhotoHandleManager.filter(assetsIn: strongSelf.allAssets, status: MGPhotosCacheManager.sharedInstance.assetIsSelectedSignal) //进行回调 MGPhotosBridgeManager.sharedInstance.start(renderFor: assets) self?.dismiss(animated: true, completion: nil) } }) return button }() /// 显示数目的标签 lazy fileprivate var numberLabel : UILabel = { let label : UILabel = UILabel(frame: CGRect(x: self.sendButton.frame.origin.x - 20, y: 0, width: 20, height: 20)) label.center = CGPoint(x: label.center.x, y: self.sendButton.center.y) label.textAlignment = .center label.font = .boldSystemFont(ofSize: 14) label.text = "8" // label.backgroundColor = .colorValue(with: 0x2dd58a) label.backgroundColor = 0x2dd58a.mg_color label.textColor = .white label.layer.cornerRadius = label.bounds.size.height / 2 label.clipsToBounds = true label.isHidden = true return label }() /// 高清图的响应Control lazy fileprivate var hightQuarityControl : UIControl = { let control : UIControl = UIControl(frame: CGRect(x: 0, y: 0, width: 150, height: self.bottomBar.bounds.height)) //响应 control.action(at: .touchUpInside, handle: { [weak self](sender) in if let strongSelf = self { strongSelf.mg_hightQualityStatusChanged() } }) return control }() /// 选中圆圈 lazy fileprivate var signImageView : UIImageView = { let imageView : UIImageView = UIImageView(frame: CGRect(x: 10, y: 0, width: 15, height: 15)) imageView.center = CGPoint(x: imageView.center.x, y: self.hightQuarityControl.bounds.height / 2) imageView.layer.cornerRadius = imageView.bounds.height / 2 imageView.layer.borderColor = UIColor.white.cgColor imageView.layer.borderWidth = 1.0 return imageView }() /// 原图: lazy fileprivate var sizeSignLabel : UILabel = { var width = NSAttributedString(string: "原图", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 13)]).boundingRect(with: CGSize(width: 100, height: 30), options: .usesLineFragmentOrigin, context: nil).width + 10 let label : UILabel = UILabel(frame: CGRect(x:self.signImageView.frame.maxX + 5 , y: 0, width: width, height: 25)) label.center = CGPoint(x: label.center.x, y: self.hightQuarityControl.bounds.height / 2) label.font = .systemFont(ofSize: 13) label.textColor = .darkGray label.text = "原图:" return label }() /// 等待 lazy fileprivate var indicator : UIActivityIndicatorView = { let indicator : UIActivityIndicatorView = UIActivityIndicatorView(style: .white) indicator.frame = CGRect(x: self.sizeSignLabel.frame.maxX + 5, y: 0, width: 15, height: 15) indicator.center = CGPoint(x: indicator.center.x, y: self.hightQuarityControl.bounds.height / 2) indicator.hidesWhenStopped = true return indicator }() /// 照片大小 lazy fileprivate var sizeLabel : UILabel = { let label = UILabel(frame: CGRect(x: self.sizeSignLabel.frame.maxX + 5, y: 0, width: self.hightQuarityControl.bounds.width - self.sizeSignLabel.bounds.width, height: 25)) label.center = CGPoint(x: label.center.x, y: self.hightQuarityControl.bounds.height / 2) label.font = .systemFont(ofSize: 13) label.textColor = .darkGray label.text = "" return label }() override func viewDidLoad() { super.viewDidLoad() if #available(iOS 11,*) { self.collectionView.contentInsetAdjustmentBehavior = .never }else { automaticallyAdjustsScrollViewInsets = false } view.addSubview(collectionView) view.addSubview(topBar) view.addSubview(bottomBar) topBar.addSubview(backItem) topBar.addSubview(selectedItem) bottomBar.addSubview(hightQuarityControl) bottomBar.addSubview(sendButton) bottomBar.addSubview(numberLabel) hightQuarityControl.addSubview(signImageView) hightQuarityControl.addSubview(sizeSignLabel) hightQuarityControl.addSubview(indicator) hightQuarityControl.addSubview(sizeLabel) //滚动到当前 collectionView.scrollToItem(at: IndexPath(item: self.current, section: 0), at: .centeredHorizontally, animated: false) mg_checkSendStatusChanged() self.isSelectOriginalPhoto = MGPhotosCacheManager.sharedInstance.isHightQuarity if isSelectOriginalPhoto { self.mg_hightQualityStatusChanged() } mg_update(sizeForHightQuarity: mg_checkHightQuarityStatus()) sendViewBarShouldChangedSignal() } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = false if mg_browseWilldisappearHandle != nil { mg_browseWilldisappearHandle!() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) //标记 scrollViewDidEndDecelerating(collectionView) } override var prefersStatusBarHidden: Bool { return true } deinit { print("\(self.self)deinit") } } extension MGPhotosBrowseController : UICollectionViewDataSource { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let collectionView = scrollView as! UICollectionView let currentIndex = Int(collectionView.contentOffset.x / collectionView.bounds.width) //获得当前记录的位置 let index = current // 判断是否为第一次进入 let shouldIgnoreCurrentIndex = objc_getAssociatedObject(self, MGPhotoBrowseViewModelAssociate.MG_photoBrowViewEndDeceleratingAssociate!) // 如果不是第一次进入并且索引没有变化,不操作 if shouldIgnoreCurrentIndex != nil && index == currentIndex { return } current = currentIndex //修改 objc_setAssociatedObject(self, MGPhotoBrowseViewModelAssociate.MG_photoBrowViewEndDeceleratingAssociate!, false, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) // //获得indexPath // let indexPath = IndexPath(item: currentIndex, section: 0) // // //请求高清图片 // image(at: indexPath, in: scrollView as! UICollectionView, isThum: false) { [weak self](image, asset) in // if let strongSelf = self { // //获得当前cell // let cell = strongSelf.collectionView.cellForItem(at: indexPath) // // UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: { // if cell != nil { // (cell as! MGPhotosBrowseCell).mg_imageView.image = image // } // // }, completion: nil) // } // } //执行判定 let cacheManager = MGPhotosCacheManager.sharedInstance self.selectedItem.setImage((cacheManager.assetIsSelectedSignal[mg_index(indexFromAllPhotosToAll: currentIndex)] ? mg_selectedImage : mg_deselectedImage)!, for: .normal) self.mg_check(hightQuarityChangedAt: currentIndex) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return allPhotoAssets.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : MGPhotosBrowseCell = collectionView.dequeueReusableCell(withReuseIdentifier: kMGPhotosBrowseCellID, for: indexPath) as! MGPhotosBrowseCell self.image(at: indexPath, in: collectionView, isThum: false) {(image, asset) in DispatchQueue.main.async { cell.mg_imageView.image = image } } // if (self.isSelectOriginalPhoto) { // self.mg_check(hightQuarityChangedAt: indexPath.item) // } cell.mg_photoBrowerSimpleTapHandle = { [unowned self] (cell) in self.sendViewBarShouldChangedSignal() } return cell } } // MARK: - 操作处理 extension MGPhotosBrowseController { /// 获得当前的位置的图片对象 /// /// - Parameters: /// - indexPath: 所在位置 /// - collection: collectionView /// - isThum: 是否为缩略图,如果为false,则按照图片原始比例获得 /// - completion: 完成 func image(at indexPath:IndexPath,in collection:UICollectionView,isThum:Bool,completion:@escaping ((UIImage,PHAsset) -> Void)) { //默认图片大小 var pixelWidth:CGFloat = self.view.frame.size.width * self.MGScreenScale DispatchQueue.global().async { //获得当前资源 let asset = self.allPhotoAssets[indexPath.item] //图片比 let scale = CGFloat(asset.pixelHeight) * 1.0 / CGFloat(asset.pixelWidth) // 超宽图片 if (scale > 1.8) { pixelWidth = pixelWidth * scale; } // 超高图片 if (scale < 0.2) { pixelWidth = pixelWidth * 0.5; } // 如果不是缩略图 // if !isThum { // let height = (collection.bounds.width - 10) * scale // // size = CGSize(width: height / scale, height: height) // } let pixelHeight = pixelWidth / scale; let imageSize = CGSize(width:pixelWidth,height:pixelHeight); MGPhotoHandleManager.asset(representionIn: asset, size: imageSize) { (image, asset) in completion(image,asset) } } } /// 检测当前发送按钮状态 func mg_checkSendStatusChanged() { let count = MGPhotosCacheManager.sharedInstance.numberOfSelectedPhoto let enable = count >= 1 self.sendButton.isEnabled = enable let hidden = count == 0 numberLabel.isHidden = hidden if !hidden { numberLabel.text = "\(count)" numberLabel.transform = CGAffineTransform(scaleX: 0.1,y: 0.1) UIView.animate(withDuration: 0.3, animations: { self.numberLabel.transform = .identity }) } } /// 点击选择按钮,触发ritl_browseSelectedBtnRefreshHandle /// /// - Parameter scrollView: collectionView func select() { let cacheManager = MGPhotosCacheManager.sharedInstance //获得当前偏移量 let currentIndex = mg_index(indexFromAllPhotosToAll: Int(self.collectionView.contentOffset.x / collectionView.bounds.width)) //修改标志位 let temp = cacheManager.assetIsSelectedSignal[currentIndex] ? -1 : 1 cacheManager.numberOfSelectedPhoto += temp //判断是否达到上限 guard cacheManager.numberOfSelectedPhoto <= cacheManager.maxNumeberOfSelectedPhoto else { //退回 cacheManager.numberOfSelectedPhoto -= 1 //弹出警告 present(alertControllerShow: UInt(cacheManager.maxNumeberOfSelectedPhoto)) return } //修改状态 cacheManager.mg_change(selecteStatusIn: currentIndex) //检测 mg_checkSendStatusChanged() //执行 self.selectedItem.setImage((cacheManager.assetIsSelectedSignal[currentIndex] ? mg_selectedImage : mg_deselectedImage)!, for: .normal) } /// 弹出alert控制器 /// /// - Parameter count: 限制的数目 func present(alertControllerShow count:UInt) { let alertController = UIAlertController(title: ("你最多可以选择\(count)张照片"), message: nil, preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: "知道了", style: UIAlertAction.Style.cancel, handler: { (action) in })) present(alertController, animated: true, completion: nil) } /// 检测当前是否为高清状态,并执行响应的block /// /// - Parameter index: 当前展示图片的索引 fileprivate func mg_check(hightQuarityChangedAt index:Int) { let cacheManager = MGPhotosCacheManager.sharedInstance guard cacheManager.isHightQuarity else { return } let currentAsset = self.allPhotoAssets[index] self.indicator.startAnimating() self.sizeLabel.isHidden = true DispatchQueue.global().async { //获取高清数据 MGPhotoHandleManager.asset(hightQuarityFor: currentAsset, Size: CGSize(width: currentAsset.pixelWidth, height: currentAsset.pixelHeight)) { (imageSize) in DispatchQueue.main.async { self.indicator.stopAnimating() self.sizeLabel.isHidden = false self.sizeLabel.text = imageSize } } } } /// 检测浏览是否为高清状态 func mg_checkHightQuarityStatus() -> Bool{ return (MGPhotosCacheManager.sharedInstance.isHightQuarity) } /// 更新高清显示的状态 /// /// - Parameter isHight: 是否为高清状态 func mg_update(sizeForHightQuarity isHight:Bool) { let signColor = isHight ? 0x2dd58a.mg_color : UIColor.darkGray let textColor = isHight ? UIColor.white : UIColor.darkGray // 设置UI signImageView.backgroundColor = signColor sizeSignLabel.textColor = textColor sizeLabel.textColor = textColor if !isHight { indicator.stopAnimating() sizeLabel.text = "" } } /// 高清状态发生变化 /// /// - Parameter scrollView: func mg_hightQualityStatusChanged() { let isHightQuality = MGPhotosCacheManager.sharedInstance.isHightQuarity // 变换标志位 MGPhotosCacheManager.sharedInstance.isHightQuarity = !isHightQuality let isHight = mg_checkHightQuarityStatus() self.isSelectOriginalPhoto = isHight self.mg_update(sizeForHightQuarity: isHight) //进入高清图进行计算 if !isHightQuality { mg_check(hightQuarityChangedAt: Int(collectionView.contentOffset.x / collectionView.bounds.width)) } } /// 从所有的图片资源转换为所有资源的位置 /// /// - Parameter index: 在所有图片资源的位置 /// - Returns: 资源对象在所有资源中的位置 fileprivate func mg_index(indexFromAllPhotosToAll index:Int) -> Int { let currentAsset = allPhotoAssets[index] return allAssets.index(of: currentAsset)! } /// bar对象的隐藏 func sendViewBarShouldChangedSignal() { self.isHiddenBar = !self.isHiddenBar self.topBar.isHidden = self.isHiddenBar self.bottomBar.isHidden = self.isHiddenBar } } extension MGPhotosBrowseController : UICollectionViewDelegateFlowLayout { func collectonViewModel(didEndDisplayCellForItemAt index: IndexPath) { //执行判定 let cacheManager = MGPhotosCacheManager.sharedInstance self.selectedItem.setImage((cacheManager.assetIsSelectedSignal[index.item] ? mg_selectedImage : mg_deselectedImage)!, for: .normal) } } @available(iOS 10, *) extension MGPhotosBrowseController : UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { } func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) { } }
b106ac9c0a9316efe44a8a22951ea76b
31.77492
237
0.643775
false
false
false
false
rajagp/iOS-UIAutomationExample
refs/heads/master
LSUITestExample-UIAutomation/LSUITestExample-UIAutomation/ViewController.swift
mit
1
// // ViewController.swift // LSUITestExample-UIAutomation // // Created by Priya Rajagopal on 6/10/15. // Copyright (c) 2015 lunaria. All rights reserved. // import UIKit // KVO const let LOGIN_SUCCESS:String = "LoginSuccess" class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate { // MARK - instance var declarations let NUMSECTIONS = 1 let NUMROWSPERSECTION = 2 let ROW_HEIGHT:CGFloat = 55.0 let ROWINDEX_LOGIN = 0 let ROWINDEX_PASSWORD = 1 let TAG_LOGIN = 10 let TAG_PASSWORD = 20 @IBOutlet weak var loginTableView: UITableView! @IBOutlet var loginButton: UIButton! weak var loginTextField: UITextField! weak var passTextField: UITextField! var accountManager: LSAccountDataManager { get{ return LSAccountDataManager.sharedInstance() } } dynamic var LoginSuccess:Bool = true dynamic var LogoutSuccess:Bool = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.loginTableView.rowHeight = ROW_HEIGHT } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK -- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return NUMROWSPERSECTION } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row == ROWINDEX_LOGIN { let cell :UITableViewCell = tableView.dequeueReusableCellWithIdentifier("LoginCell")! as! UITableViewCell self.loginTextField = cell.contentView.viewWithTag(TAG_LOGIN) as! UITextField self.loginTextField.becomeFirstResponder() self.loginTextField.delegate = self return cell } else { let cell :UITableViewCell = tableView.dequeueReusableCellWithIdentifier("PasswordCell")! as! UITableViewCell self.passTextField = cell.contentView.viewWithTag(TAG_PASSWORD) as! UITextField self.passTextField.delegate = self return cell } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return NUMSECTIONS } // MARK - UITableViewDelegate // MARK - UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { if self.loginTextField.text!.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 && self.passTextField.text!.lengthOfBytesUsingEncoding( NSUTF8StringEncoding) > 0 { self.loginButton.enabled = true } if (textField == self.loginTextField) { self.passTextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return true } // MARK - IBAction @IBAction func onLoginTapped(sender: UIButton) { let user = self.loginTextField.text! let pass = self.passTextField.text! self.LoginSuccess = self.accountManager.isValidUser(user, withPassword: pass) } }
f9f7257ad96fbcd03874645c5dc194ba
30.254237
188
0.666486
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/TXTReader/BookDetail/Models/QSReaderParse.swift
mit
1
// // QSReaderParse.swift // zhuishushenqi // // Created by yung on 2018/2/6. // Copyright © 2018年 QS. All rights reserved. // import UIKit class QSReaderParse: NSObject { //从本地目录中获取书籍内容并解析 public class func fetchBook(path:String,completion:((BookDetail?)->Void)?){ // unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); let encode = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)) let url = URL(fileURLWithPath: path) if let content = try? String(contentsOf: url, encoding: String.Encoding(rawValue: encode)) { let book = self.chapterInfo(text: content, path: path) completion?(book) } else if let content = try? String(contentsOf: url, encoding: .utf8) { let book = self.chapterInfo(text: content, path: path) completion?(book) } else if let content = try? String(contentsOf: url, encoding: .unicode) { let book = self.chapterInfo(text: content, path: path) completion?(book) } } class func content(shelf:ZSShelfModel) ->String { let path = NSHomeDirectory().appending(shelf.bookUrl) let gbk = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)) let gb2312 = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_2312_80.rawValue)) let utf8 = String.Encoding.utf8 let unicode = String.Encoding.unicode let encodeArray = [String.Encoding(rawValue: gbk), String.Encoding(rawValue: gb2312), utf8, unicode] let url = URL(fileURLWithPath: path) let data = try! Data(contentsOf: url) let encoding = NSString.fileEncoding(path) guard let result = String.stringFromDataDetectingEncoding(data: data, suggestedEncodings:encodeArray) else { return "" } return result.0 } // failed to get chardet, use NSString.fileEncoding class func encode(path:String) ->UnsafeMutablePointer<CChar>? { var buf:UnsafeMutablePointer<CChar>? let file = fopen(path, "r") if file == nil { print("打开文件失败!") return nil } let len = fread(buf, CChar.bitWidth, 2048, file) fclose(file) let ud = uchardet_new() if uchardet_handle_data(ud, buf, len) != 0 { print("分析编码失败!") return nil } uchardet_data_end(ud) let encode = uchardet_get_charset(ud) print("文本的编码方式是:\(String(cString: encode!))") uchardet_delete(ud) return UnsafeMutablePointer(mutating: encode) } class func parse(shelf:ZSShelfModel)-> ZSAikanParserModel? { if shelf.bookType == .online { return nil } //章节名过滤,只有特定的名称才能识别,不过可以更改正则,做更多的的适配 let parten = "第[0-9一二三四五六七八九十百千]*[章回节].*" let txt = content(shelf: shelf) let reg = try? NSRegularExpression(pattern: parten, options: .caseInsensitive) if let match = reg?.matches(in: txt, options: .reportCompletion, range: NSMakeRange(0, txt.nsString.length)) { let book = ZSAikanParserModel() book.bookName = shelf.bookName book.bookAuthor = shelf.author book.bookUrl = shelf.bookUrl book.bookType = shelf.bookType var lastRange:NSRange? var chapters:[ZSBookChapter] = [] for index in 0..<match.count { var range = match[index == 0 ? index:index - 1].range let chapter = ZSBookChapter() chapter.bookUrl = shelf.bookUrl if match.count == 1 { if index == 0 { chapter.chapterName = txt.nsString.substring(with: range) chapter.bookType = shelf.bookType chapter.chapterContent = self.trim(str: txt.nsString.substring(with: NSMakeRange(range.location, txt.nsString.length - range.location))) chapter.chapterIndex = index chapters.append(chapter) } } else { if index != 0 && index != match.count { range = match[index].range chapter.chapterName = txt.nsString.substring(with:lastRange!) chapter.bookType = shelf.bookType chapter.chapterContent = self.trim(str: txt.nsString.substring(with: NSMakeRange(lastRange!.location, range.location - lastRange!.location))) chapter.chapterIndex = index - 1 chapters.append(chapter) } else if index == match.count { chapter.chapterName = txt.nsString.substring(with: lastRange!) chapter.bookType = shelf.bookType chapter.chapterContent = self.trim(str: txt.nsString.substring(with: NSMakeRange(lastRange!.location, txt.nsString.length - lastRange!.location))) chapter.chapterIndex = index - 1 chapters.append(chapter) } } lastRange = range } if chapters.count == 0 { let chapter = ZSBookChapter() chapter.bookUrl = shelf.bookUrl chapter.chapterName = "" chapter.chapterContent = txt chapter.chapterIndex = 0 chapters.append(chapter) } book.chaptersModel = chapters return book } return nil } @discardableResult public class func chapterInfo(text:String,path:String) ->BookDetail?{ //章节名过滤,只有特定的名称才能识别,不过可以更改正则,做更多的的适配 let parten = "第[0-9一二三四五六七八九十百千]*[章回].*" let content = text as NSString let reg = try? NSRegularExpression(pattern: parten, options: .caseInsensitive) if let match = reg?.matches(in: text, options: .reportCompletion, range: NSMakeRange(0, content.length)) { let book = BookDetail() if match.count > 0 { book.title = (path as NSString).lastPathComponent var lastRange:NSRange? var chapters:[QSChapter] = [] for index in 0..<match.count { var range = match[index == 0 ? index:index - 1].range let chapter = QSChapter() if match.count == 1 { if index == 0 { chapter.title = content.substring(with: range) chapter.content = self.trim(str: (text as NSString).substring(with: NSMakeRange(range.location, content.length))) chapter.curChapter = index chapter.getPages() chapters.append(chapter) } } else { if index != 0 && index != match.count { range = match[index].range chapter.title = content.substring(with:lastRange!) chapter.content = self.trim(str: content.substring(with: NSMakeRange(lastRange!.location, range.location - lastRange!.location))) chapter.curChapter = index - 1 chapter.getPages() chapters.append(chapter) } else if index == match.count { chapter.title = content.substring(with: lastRange!) chapter.content = self.trim(str: content.substring(with: NSMakeRange(lastRange!.location, content.length - lastRange!.location))) chapter.curChapter = index - 1 chapter.getPages() chapters.append(chapter) } } lastRange = range } book.book.localChapters = chapters return book } else { book.title = (path as NSString).lastPathComponent var chapters:[QSChapter] = [] let chapter = QSChapter() chapter.title = "" chapter.content = text chapter.getPages() chapters.append(chapter) book.book.localChapters = chapters return book } } return nil } //去掉章节开头跟结尾的多余的空格,防止产生空白页 public class func trim(str:String)->String{ var spaceStr:String = str spaceStr = spaceStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return spaceStr } //耗时操作,只在显示章节时才去计算,计算完成将会缓存,在改变约束,或者换源时重置 public class func pageWithAttributes(attrubutes:[NSAttributedString.Key:Any]?,constrainedToFrame frame:CGRect,string:String)->[NSRange]{ // 记录 let date = NSDate() var rangeArray:[NSRange] = [] // 拼接字符串 let attrString = NSMutableAttributedString(string: string, attributes: attrubutes) let frameSetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString) let path = CGPath(rect: frame, transform: nil) var range = CFRangeMake(0, 0) var rangeOffset:NSInteger = 0 repeat{ let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(rangeOffset, 0), path, nil) range = CTFrameGetVisibleStringRange(frame) rangeArray.append(NSMakeRange(rangeOffset, range.length)) rangeOffset += range.length }while(range.location + range.length < attrString.length) let millionSecond = NSDate().timeIntervalSince(date as Date) QSLog("耗时:\(millionSecond)") return rangeArray } }
5c53040e7d10f91cd6f1c16b599b61b1
42.939655
170
0.556111
false
false
false
false
ddgold/Cathedral
refs/heads/master
Cathedral/Settings.swift
apache-2.0
1
// // Settings.swift // Cathedral // // Created by Doug Goldstein on 2/24/19. // Copyright © 2019 Doug Goldstein. All rights reserved. // import Foundation /// A games settings object struct Settings { /// Initilizes a settings object, but there is no need to have an instance. init() { self.lightPlayerType = Settings.lightPlayerType self.darkPlayerType = Settings.darkPlayerType self.delayedCathedral = Settings.delayedCathedral self.autoBuild = Settings.autoBuild } //MARK: - Light Player Type /// The light player type. /// - Note: System level setting. static var lightPlayerType: Player.Type { get { if let playerType = UserDefaults.standard.string(forKey: "lightPlayerType") { return PlayerType(playerType) } else { return RandomComputer.self } } set { UserDefaults.standard.set(newValue.id, forKey: "lightPlayerType") } } /// The light player type. /// - Note: Game level setting. let lightPlayerType: Player.Type //MARK: - Dark Player Type /// The dark player type. /// - Note: System level setting. static var darkPlayerType: Player.Type { get { if let playerType = UserDefaults.standard.string(forKey: "darkPlayerType") { return PlayerType(playerType) } else { return LocalHuman.self } } set { UserDefaults.standard.set(newValue.id, forKey: "darkPlayerType") } } /// The dark player type. /// - Note: Game level setting. let darkPlayerType: Player.Type //MARK: - Delayed Cathedral /// Whether or not the cathedral placement should be delayed until after the first dark piece has been placed. /// - Note: System level setting. static var delayedCathedral: Bool { get { return UserDefaults.standard.bool(forKey: "delayedCathedral") } set { UserDefaults.standard.set(newValue, forKey: "delayedCathedral") } } /// Whether or not the cathedral placement should be delayed until after the first dark piece has been placed. /// - Note: Game level setting. let delayedCathedral: Bool //MARK: - Auto Build /// Whether or not to auto-build once one player can no longer build, and there are enough tiles to build all remaining pieces. /// - Note: System level setting. static var autoBuild: Bool { get { return UserDefaults.standard.bool(forKey: "autoBuild") } set { UserDefaults.standard.set(newValue, forKey: "autoBuild") } } /// Whether or not to auto-build once one player can no longer build, and there are enough tiles to build all remaining pieces. /// - Note: Game level setting. let autoBuild: Bool }
49ea39d38ee66eb9fa0e8d9fe77c692a
26.866071
131
0.579622
false
false
false
false
ajsnow/Shear
refs/heads/master
Shear/Tensor.swift
mit
1
// Copyright 2016 The Shear Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. import Foundation public struct Tensor<Element>: TensorProtocol { // MARK: - Underlying Storage /// The functions called for a given index. One should be defined in terms of the other. fileprivate let cartesianFn: ([Int]) -> Element fileprivate let linearFn: (Int) -> Element // These functions perform range checking themselves. // // The reason we maintain two functions is that some Tensors will be most naturally defined one way or the other so we need both inits. // However, if we only supported, for example, cartesian functions natively, then linear access of, say, iota would result in linear -> cartesian -> linear index translation. // MARK: - Stored Properties public let shape: [Int] public let unified: Bool /// The stride needed to index into storage. fileprivate let stride: [Int] /// The total number of elements. fileprivate let count: Int } public extension Tensor { // MARK: - Internal Init // Internal Init handles otherwise repeatitive tasks. init(shape: [Int], cartesian: (([Int]) -> Element)?, linear: ((Int) -> Element)?, unified: Bool) { guard let shape = checkAndReduce(shape) else { fatalError("A Tensor cannot contain zero or negative length dimensions") } self.shape = shape self.stride = calculateStride(shape) self.count = shape.reduce(1, *) self.unified = unified switch (cartesian, linear) { case let (.some(cartesian), .some(linear)): self.cartesianFn = cartesian self.linearFn = linear case let (.some(cartesian), .none): self.cartesianFn = cartesian self.linearFn = transformFn(cartesian, stride: stride) case let (.none, .some(linear)): self.cartesianFn = transformFn(linear, stride: stride) self.linearFn = linear case (.none, .none): fatalError("At least one method of index translation must be defined") } } // MARK: - Conformance Init /// Construct a Tensor with a `shape` of elements, each initialized to `repeatedValue`. public init(shape: [Int], repeatedValue: Element) { self.init(shape: shape, cartesian: { _ in repeatedValue }, linear: { _ in repeatedValue }, unified: true) } /// Convert the native Array of `values` into a Tensor of `shape`. public init(shape: [Int], values: [Element]) { self.init(shape: shape, cartesian: nil, linear: { i in values[i] }, unified: true) } /// Construct a Tensor with the elements of `tensor` of `shape`. public init(shape: [Int], tensor: Tensor<Element>) { guard shape.reduce(1, *) == tensor.count else { fatalError("Reshaped Tensors must contain the same number of elements") } // It's a little redundant to compute the shape twice, but that's not a high cost. self.init(shape: shape, cartesian: nil, linear: tensor.linearFn, unified: tensor.unified) // The cartesian function changes unless the shape == tensor.shape, so we recompute it from the linear function that does not change. } /// Construct a Tensor a slice with `view` into `tensor`. init(view: [TensorIndex], tensor: Tensor<Element>) { guard let (shape, compactView) = makeSliceIndexingShapeAndView(tensor.shape, view: view) else { fatalError("Invalid bounds for an TensorSlice") } let cartesian = { (indices: [Int]) -> Element in var g = indices.makeIterator() let underlyingIndices = zip(compactView, view).map { (c, v) -> Int in if let d = c { return d } return convertIndex(g.next()!, view: v) } return tensor.cartesianFn(underlyingIndices) } self.init(shape: shape, cartesian: cartesian, linear: nil, unified: false) } /// Type-convert any TensorProtocol adopter into a Tensor. public init<A: TensorProtocol>(_ tensor: A) where A.Element == Element { // Likely doubles up on bounds checking. self.init(shape: tensor.shape, cartesian: { indices in tensor[indices] }, linear: { index in tensor[linear: index] }, unified: tensor.unified) } /// Constructs a Tensor with the given `shape` where the values are a function of their `cartesian` indices. public init(shape: [Int], cartesian: @escaping ([Int]) -> Element) { self.init(shape: shape, cartesian: cartesian, linear: nil, unified: false) // We have to be conservative with unified's condition here since we could get closures dragging lots of Tensors in with them. } /// Constructs a Tensor with the given `shape` where the values are a function of their `linear` index. public init(shape: [Int], linear: @escaping (Int) -> Element) { self.init(shape: shape, cartesian: nil, linear: linear, unified: false) // We have to be conservative with unified's condition here since we could get closures dragging lots of Tensors in with them. } } // MARK: - Linear Indexing extension Tensor { public var allElements: AnyRandomAccessCollection<Element> { return AnyRandomAccessCollection(AllElementsCollection(array: self)) } public subscript(linear linearIndex: Int) -> Element { guard checkBounds(linearIndex, forCount: count) else { fatalError("TensorProtocol index out of range") } return linearFn(linearIndex) } } // MARK: - Linear Slicing extension Tensor { public subscript(linear indices: Range<Int>) -> Tensor<Element> { guard checkBounds(indices.lowerBound, forCount: count) && checkBounds(indices.upperBound, forCount: count) else { fatalError("TensorProtocol index out of range") } return Tensor(shape: [indices.count], linear: { self[linear: $0] }) } } // MARK: - Scalar Indexing extension Tensor { public subscript(indices: [Int]) -> Element { guard checkBounds(indices, forShape: shape) else { fatalError("TensorProtocol index out of range") } return cartesianFn(indices) } public subscript(indices: Int...) -> Element { guard checkBounds(indices, forShape: shape) else { fatalError("TensorProtocol index out of range") } return cartesianFn(indices) } } // MARK: - Slice Indexing extension Tensor { public subscript(indices: [TensorIndex]) -> Tensor<Element> { return Tensor(view: indices, tensor: self) } public subscript(indices: TensorIndex...) -> Tensor<Element> { return Tensor(view: indices, tensor: self) } } private func transformFn<A>(_ cartesianFn: @escaping ([Int]) -> A, stride: [Int]) -> (Int) -> A { return { index in cartesianFn(convertIndices(linear: index, stride: stride)) } } private func transformFn<A>(_ linearFn: @escaping (Int) -> A, stride: [Int]) -> ([Int]) -> A { return { indices in linearFn(convertIndices(cartesian: indices, stride: stride)) } } private func makeSliceIndexingShapeAndView(_ baseShape: [Int], view: [TensorIndex]) -> (shape: [Int], compactedView: [Int?])? { // Assumes view is within bounds. func calculateBound(_ baseCount: Int, view: TensorIndex) -> Int { switch view { case .all: return baseCount case .singleValue: return 1 case .list(let list): return list.count case .range(let low, let high): return high - low } } func calculateUncompactedShape(_ baseShape: [Int], view: [TensorIndex]) -> [Int] { return zip(baseShape, view).map(calculateBound) } func calculateCompactedBound(_ baseCount: Int, view: TensorIndex) -> Int? { guard baseCount == 1 else { return nil } switch view { case .all: return 0 // Cannot be reached, as there cannot be singular dimensions in the base array's shape either. case .singleValue(let sv): return sv case .list(let list): return list.first! // If the list is empty we have a problem we should have detected earlier. case .range(let low, _): return low } } func calculateCompactedView(_ uncompactedShape: [Int], view: [TensorIndex]) -> [Int?] { return zip(uncompactedShape, view).map(calculateCompactedBound) } // Check for correct number of indices guard baseShape.count == view.count else { return nil } guard !zip(baseShape, view).map({$1.isInbounds($0)}).contains(false) else { return nil } let uncompactedShape = calculateUncompactedShape(baseShape, view: view) guard !uncompactedShape.contains(where: {$0 < 1}) else { return nil } let compactedView = calculateCompactedView(uncompactedShape, view: view) return (uncompactedShape.filter {$0 != 1}, compactedView) } private func convertIndex(_ index: Int, view: TensorIndex) -> Int { switch view { case .all: return index case .singleValue: fatalError("This cannot happen") case .list(let list): return list[index] case .range(let low, _): return low + index } }
e8ebe33195a63652b041dbfe0b8a62e0
39.571429
231
0.644046
false
false
false
false
mownier/Umalahokan
refs/heads/master
Umalahokan/Source/UI/Recent Chat/RecentChatViewController.swift
mit
1
// // RecentChatViewController.swift // Umalahokan // // Created by Mounir Ybanez on 30/01/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class RecentChatViewController: UIViewController { let messageWriterTransitioning = MessageWriterTransitioning() let chatTransitioning = ChatTransitioning() weak var hamburger: DrawerContainerHamburger? var recentChatView: RecentChatView! var chats = genereRecentChatRandomDisplayItems() var item: RecentChatViewItem? override func loadView() { var rect = CGRect.zero rect.size = UIScreen.main.bounds.size recentChatView = RecentChatView(frame: rect) recentChatView.configure(item) recentChatView.delegate = self recentChatView.topBar.delegate = self recentChatView.tableView.dataSource = self recentChatView.tableView.delegate = self recentChatView.tableView.rowHeight = 80 recentChatView.tableView.separatorStyle = .none RecentChatCell.register(in: recentChatView.tableView) view = recentChatView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) recentChatView.tableView.reloadData() } override var prefersStatusBarHidden: Bool { return true } } extension RecentChatViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return chats.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = RecentChatCell.dequeue(from: tableView) let item = chats[indexPath.row] as? RecentChatCellItem cell.configure(item) return cell } } extension RecentChatViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! RecentChatCell cell.avatarImageView.image = nil cell.avatarImageView.backgroundColor = UIColor.white let frame = cell.convert(cell.avatarImageView.frame, to: nil) chatTransitioning.avatarFrame = frame let chat = ChatViewController() chat.item = chats[indexPath.row] as? ChatViewItem chat.transitioningDelegate = chatTransitioning chat.modalPresentationStyle = .custom present(chat, animated: true, completion: nil) // A work around when cell selectionStyle set to .none. // The delay of showing the chat view controller is // being resolved by this line. // See related problem here: goo.gl/VlN0JQ CFRunLoopWakeUp(CFRunLoopGetCurrent()) } } extension RecentChatViewController: RecentChatTopBarDelegate { func didTapRight() { } func didTapLeft() { hamburger?.showMenu() } } extension RecentChatViewController: RecentChatViewDelegate { func didTapComposer() { let vc = MessageWriterViewController() messageWriterTransitioning.composerButtonFrame = recentChatView.composerButton.frame vc.transitioningDelegate = messageWriterTransitioning vc.modalPresentationStyle = .custom present(vc, animated: true, completion: nil) } } extension RecentChatViewController: DrawerContainerContentProtocol { var drawerContentViewController: UIViewController { return self } var drawerContentId: String { return "Recent Chat" } }
769e2de46df1d9a1312dc6095a28ab7d
30.206897
100
0.687569
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
brave/src/data/Device.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 CoreData import Foundation import Shared class Device: NSManagedObject, Syncable { // Check if this can be nested inside the method private static var sharedCurrentDevice: Device? // Assign on parent model via CD @NSManaged var isSynced: Bool @NSManaged var created: Date? @NSManaged var isCurrentDevice: Bool @NSManaged var deviceDisplayId: String? @NSManaged var syncDisplayUUID: String? @NSManaged var name: String? // Device is subtype of prefs 🤢 var recordType: SyncRecordType = .prefs // Just a facade around the displayId, for easier access and better CD storage var deviceId: [Int]? { get { return SyncHelpers.syncUUID(fromString: deviceDisplayId) } set(value) { deviceDisplayId = SyncHelpers.syncDisplay(fromUUID: value) } } class func deviceSettings(profile: Profile) -> [SyncDeviceSetting]? { // Building settings off of device objects let deviceSettings: [SyncDeviceSetting]? = (Device.get(predicate: nil, context: DataController.shared.workerContext) as? [Device])?.map { // Even if no 'real' title, still want it to show up in list return SyncDeviceSetting(profile: profile, device: $0) } return deviceSettings } // This should be abstractable func asDictionary(deviceId: [Int]?, action: Int?) -> [String: Any] { return SyncDevice(record: self, deviceId: deviceId, action: action).dictionaryRepresentation() } static func add(rootObject root: SyncRecord?, save: Bool, sendToSync: Bool, context: NSManagedObjectContext) -> Syncable? { // No guard, let bleed through to allow 'empty' devices (e.g. local) let root = root as? SyncDevice let device = Device(entity: Device.entity(context: context), insertInto: context) device.created = root?.syncNativeTimestamp ?? Date() device.syncUUID = root?.objectId ?? SyncCrypto.shared.uniqueSerialBytes(count: 16) device.update(syncRecord: root) if save { DataController.saveContext(context: context) } return device } class func add(save: Bool = false, context: NSManagedObjectContext) -> Device? { return add(rootObject: nil, save: save, sendToSync: false, context: context) as? Device } func update(syncRecord record: SyncRecord?) { guard let root = record as? SyncDevice else { return } self.name = root.name self.deviceId = root.deviceId // No save currently } static func currentDevice() -> Device? { if sharedCurrentDevice == nil { let context = DataController.shared.workerContext // Create device let predicate = NSPredicate(format: "isCurrentDevice = YES") // Should only ever be one current device! var localDevice: Device? = get(predicate: predicate, context: context)?.first if localDevice == nil { // Create localDevice = add(context: context) localDevice?.isCurrentDevice = true DataController.saveContext(context: context) } sharedCurrentDevice = localDevice } return sharedCurrentDevice } class func deleteAll(completionOnMain: ()->()) { let context = DataController.shared.workerContext context.perform { let fetchRequest = NSFetchRequest<NSFetchRequestResult>() fetchRequest.entity = Device.entity(context: context) fetchRequest.includesPropertyValues = false do { let results = try context.fetch(fetchRequest) for result in results { context.delete(result as! NSManagedObject) } } catch { let fetchError = error as NSError print(fetchError) } // Destroy handle to local device instance, otherwise it is locally retained and will throw console errors sharedCurrentDevice = nil DataController.saveContext(context: context) } } }
14cdfa8ed5e520207c6014076746153b
36.139344
198
0.617524
false
false
false
false
twtstudio/WePeiYang-iOS
refs/heads/master
WePeiYang/PartyService/Controller/TwentyCourseDetailViewController.swift
mit
1
// // TwentyCourseDetailViewController.swift // WePeiYang // // Created by Allen X on 8/16/16. // Copyright © 2016 Qin Yubo. All rights reserved. // import UIKit import pop class TwentyCourseDetailViewController: UITableViewController { var detailList: [Courses.Study20.Detail?] = [] //var quizTakingBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() //Eliminate the empty cells tableView.tableFooterView = UIView() self.navigationController!.jz_navigationBarBackgroundAlpha = 0; //FIXME: Autolayout and Scrolling is bad. let bgView = UIView(frame: CGRect(x: 0, y: -(self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height), width: self.view.frame.size.width, height: self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) //let bgView = UIView(color: partyRed) bgView.backgroundColor = partyRed let quizTakingBtn = UIBarButtonItem(title: "开始答题", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(TwentyCourseDetailViewController.startQuiz)) self.navigationItem.setRightBarButtonItem(quizTakingBtn, animated: true) //navigationItem.titleView?.addSubview(bgView) tableView.addSubview(bgView) /*bgView.snp_makeConstraints { make in make.left.equalTo(0) make.top.equalTo(-(self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) make.right.equalTo((navigationController?.view)!.snp_right) make.height.equalTo(self.navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height) }*/ // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillDisappear(animated: Bool) { super.viewWillAppear(animated) for foo in navigationController!.view.subviews { if foo.isKindOfClass(CourseDetailReadingView) { foo.removeFromSuperview() } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //log.word("hi\(detailList.count)") // #warning Incomplete implementation, return the number of rows return detailList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = CourseDetailTableViewCell(detail: detailList[indexPath.row]!) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let readingView = CourseDetailReadingView(detail: detailList[indexPath.row]!) self.navigationController?.view.addSubview(readingView) //animate(to: readingView) readingView.frame = CGRect(x: 0, y: self.view.frame.height, width: 0, height: self.view.frame.height/4) UIView.beginAnimations("readingViewPopUp", context: nil) UIView.setAnimationDuration(0.6) readingView.frame = self.view.frame UIView.commitAnimations() //UIView.beginAnimations("", context: UnsafeMutablePointer<Void>) /*UIView.animateWithDuration(0.5, animations: { readingView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.bounds.height) }) { (_: Bool) in self.navigationController?.view.addSubview(readingView) readingView.snp_makeConstraints { make in make.top.equalTo(self.view) make.left.equalTo(self.view) make.bottom.equalTo(self.view) make.right.equalTo(self.view) } }*/ tableView.deselectRowAtIndexPath(indexPath, animated: true) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension TwentyCourseDetailViewController { convenience init(details: [Courses.Study20.Detail?]) { self.init() self.detailList = details } } extension TwentyCourseDetailViewController { func animate(to Who: UIView) { let anim = POPSpringAnimation(propertyNamed: kPOPViewBounds) anim.fromValue = NSValue(CGRect: CGRect(x: self.view.frame.width/2, y: self.view.frame.height, width: 0, height: self.view.frame.height/4)) anim.toValue = NSValue(CGRect: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)) anim.springBounciness = 20 anim.delegate = self Who.pop_addAnimation(anim, forKey: "readingViewPopup") } func startQuiz() { let courseID = (self.detailList[0]?.courseID)! Courses.Study20.getQuiz(of: courseID) { let quizTakingVC = QuizTakingViewController(courseID: courseID) self.navigationController?.showViewController(quizTakingVC, sender: nil) } } }
25e154c924ce85e4e98c40be5e2eb4ce
36.360976
339
0.6604
false
false
false
false
ashfurrow/XCGLogger
refs/heads/master
XCGLogger/Library/XCGLogger/XCGLogger.swift
mit
2
// // XCGLogger.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright (c) 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // import Foundation private extension NSThread { class func dateFormatter(format: String, locale: NSLocale? = nil) -> NSDateFormatter? { let localeToUse = locale ?? NSLocale.currentLocale() if let threadDictionary = NSThread.currentThread().threadDictionary { var dataFormatterCache: [String:NSDateFormatter]? = threadDictionary.objectForKey(XCGLogger.constants.nsdataFormatterCacheIdentifier) as? [String:NSDateFormatter] if dataFormatterCache == nil { dataFormatterCache = [String:NSDateFormatter]() } let formatterKey = format + "_" + localeToUse.localeIdentifier if let formatter = dataFormatterCache?[formatterKey] { return formatter } var formatter = NSDateFormatter() formatter.locale = localeToUse formatter.dateFormat = format dataFormatterCache?[formatterKey] = formatter threadDictionary[XCGLogger.constants.nsdataFormatterCacheIdentifier] = dataFormatterCache return formatter } return nil } } // MARK: - XCGLogDetails // - Data structure to hold all info about a log message, passed to log destination classes public struct XCGLogDetails { public var logLevel: XCGLogger.LogLevel public var date: NSDate public var logMessage: String public var functionName: String public var fileName: String public var lineNumber: Int public init(logLevel: XCGLogger.LogLevel, date: NSDate, logMessage: String, functionName: String, fileName: String, lineNumber: Int) { self.logLevel = logLevel self.date = date self.logMessage = logMessage self.functionName = functionName self.fileName = fileName self.lineNumber = lineNumber } } // MARK: - XCGLogDestinationProtocol // - Protocol for output classes to conform to public protocol XCGLogDestinationProtocol: DebugPrintable { var owner: XCGLogger {get set} var identifier: String {get set} var outputLogLevel: XCGLogger.LogLevel {get set} func processLogDetails(logDetails: XCGLogDetails) func processInternalLogDetails(logDetails: XCGLogDetails) // Same as processLogDetails but should omit function/file/line info func isEnabledForLogLevel(logLevel: XCGLogger.LogLevel) -> Bool } // MARK: - XCGConsoleLogDestination // - A standard log destination that outputs log details to the console public class XCGConsoleLogDestination : XCGLogDestinationProtocol, DebugPrintable { public var owner: XCGLogger public var identifier: String public var outputLogLevel: XCGLogger.LogLevel = .Debug public var showFileName: Bool = true public var showLineNumber: Bool = true public var showLogLevel: Bool = true public var dateFormatter: NSDateFormatter? { return NSThread.dateFormatter("yyyy-MM-dd HH:mm:ss.SSS") } public init(owner: XCGLogger, identifier: String = "") { self.owner = owner self.identifier = identifier } public func processLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } if showFileName { extendedDetails += "[" + logDetails.fileName.lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] " } else if showLineNumber { extendedDetails += "[" + String(logDetails.lineNumber) + "] " } var formattedDate: String = logDetails.date.description if let unwrappedDataFormatter = dateFormatter { formattedDate = unwrappedDataFormatter.stringFromDate(logDetails.date) } var fullLogMessage: String = "\(formattedDate) \(extendedDetails)\(logDetails.functionName): \(logDetails.logMessage)\n" dispatch_async(XCGLogger.logQueue) { print(fullLogMessage) } } public func processInternalLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } var formattedDate: String = logDetails.date.description if let unwrappedDataFormatter = dateFormatter { formattedDate = unwrappedDataFormatter.stringFromDate(logDetails.date) } var fullLogMessage: String = "\(formattedDate) \(extendedDetails): \(logDetails.logMessage)\n" dispatch_async(XCGLogger.logQueue) { print(fullLogMessage) } } // MARK: - Misc methods public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } // MARK: - DebugPrintable public var debugDescription: String { get { return "XCGConsoleLogDestination: \(identifier) - LogLevel: \(outputLogLevel.description()) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber)" } } } // MARK: - XCGFileLogDestination // - A standard log destination that outputs log details to a file public class XCGFileLogDestination : XCGLogDestinationProtocol, DebugPrintable { public var owner: XCGLogger public var identifier: String public var outputLogLevel: XCGLogger.LogLevel = .Debug public var showFileName: Bool = true public var showLineNumber: Bool = true public var showLogLevel: Bool = true public var dateFormatter: NSDateFormatter? { return NSThread.dateFormatter("yyyy-MM-dd HH:mm:ss.SSS") } private var writeToFileURL : NSURL? = nil { didSet { openFile() } } private var logFileHandle: NSFileHandle? = nil public init(owner: XCGLogger, writeToFile: AnyObject, identifier: String = "") { self.owner = owner self.identifier = identifier if writeToFile is NSString { writeToFileURL = NSURL.fileURLWithPath(writeToFile as String) } else if writeToFile is NSURL { writeToFileURL = writeToFile as? NSURL } else { writeToFileURL = nil } openFile() } deinit { // close file stream if open closeFile() } // MARK: - Logging methods public func processLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } if showFileName { extendedDetails += "[" + logDetails.fileName.lastPathComponent + (showLineNumber ? ":" + String(logDetails.lineNumber) : "") + "] " } else if showLineNumber { extendedDetails += "[" + String(logDetails.lineNumber) + "] " } var formattedDate: String = logDetails.date.description if let unwrappedDataFormatter = dateFormatter { formattedDate = unwrappedDataFormatter.stringFromDate(logDetails.date) } var fullLogMessage: String = "\(formattedDate) \(extendedDetails)\(logDetails.functionName): \(logDetails.logMessage)\n" if let encodedData = fullLogMessage.dataUsingEncoding(NSUTF8StringEncoding) { logFileHandle?.writeData(encodedData) } } public func processInternalLogDetails(logDetails: XCGLogDetails) { var extendedDetails: String = "" if showLogLevel { extendedDetails += "[" + logDetails.logLevel.description() + "] " } var formattedDate: String = logDetails.date.description if let unwrappedDataFormatter = dateFormatter { formattedDate = unwrappedDataFormatter.stringFromDate(logDetails.date) } var fullLogMessage: String = "\(formattedDate) \(extendedDetails): \(logDetails.logMessage)\n" if let encodedData = fullLogMessage.dataUsingEncoding(NSUTF8StringEncoding) { logFileHandle?.writeData(encodedData) } } // MARK: - Misc methods public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } private func openFile() { if logFileHandle != nil { closeFile() } if let unwrappedWriteToFileURL = writeToFileURL { if let path = unwrappedWriteToFileURL.path { NSFileManager.defaultManager().createFileAtPath(path, contents: nil, attributes: nil) var fileError : NSError? = nil logFileHandle = NSFileHandle(forWritingToURL: unwrappedWriteToFileURL, error: &fileError) if logFileHandle == nil { owner._logln("Attempt to open log file for writing failed: \(fileError?.localizedDescription)", logLevel: .Error) } else { owner.logAppDetails(selectedLogDestination: self) let logDetails = XCGLogDetails(logLevel: .Info, date: NSDate(), logMessage: "XCGLogger writing to log to: \(unwrappedWriteToFileURL)", functionName: "", fileName: "", lineNumber: 0) owner._logln(logDetails.logMessage, logLevel: logDetails.logLevel) processInternalLogDetails(logDetails) } } } } private func closeFile() { logFileHandle?.closeFile() logFileHandle = nil } // MARK: - DebugPrintable public var debugDescription: String { get { return "XCGFileLogDestination: \(identifier) - LogLevel: \(outputLogLevel.description()) showLogLevel: \(showLogLevel) showFileName: \(showFileName) showLineNumber: \(showLineNumber)" } } } // MARK: - XCGLogger // - The main logging class public class XCGLogger : DebugPrintable { // MARK: - Constants public struct constants { public static let defaultInstanceIdentifier = "com.cerebralgardens.xcglogger.defaultInstance" public static let baseConsoleLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.console" public static let baseFileLogDestinationIdentifier = "com.cerebralgardens.xcglogger.logdestination.file" public static let nsdataFormatterCacheIdentifier = "com.cerebralgardens.xcglogger.nsdataFormatterCache" public static let logQueueIdentifier = "com.cerebralgardens.xcglogger.queue" public static let versionString = "1.7" } // MARK: - Enums public enum LogLevel: Int, Comparable { case Verbose case Debug case Info case Error case Severe case None public func description() -> String { switch self { case .Verbose: return "Verbose" case .Debug: return "Debug" case .Info: return "Info" case .Error: return "Error" case .Severe: return "Severe" case .None: return "None" } } } // MARK: - Properties (Options) public var identifier: String = "" public var outputLogLevel: LogLevel = .Debug { didSet { for index in 0 ..< logDestinations.count { logDestinations[index].outputLogLevel = outputLogLevel } } } // MARK: - Properties public class var logQueue : dispatch_queue_t { struct Statics { static var logQueue = dispatch_queue_create(XCGLogger.constants.logQueueIdentifier, nil) } return Statics.logQueue } public var dateFormatter: NSDateFormatter? { return NSThread.dateFormatter("yyyy-MM-dd HH:mm:ss.SSS") } public var logDestinations: Array<XCGLogDestinationProtocol> = [] public init() { // Setup a standard console log destination addLogDestination(XCGConsoleLogDestination(owner: self, identifier: XCGLogger.constants.baseConsoleLogDestinationIdentifier)) } // MARK: - Default instance public class func defaultInstance() -> XCGLogger { struct statics { static let instance: XCGLogger = XCGLogger() } statics.instance.identifier = XCGLogger.constants.defaultInstanceIdentifier return statics.instance } public class func sharedInstance() -> XCGLogger { self.defaultInstance()._logln("sharedInstance() has been renamed to defaultInstance() to better reflect that it is not a true singleton. Please update your code, sharedInstance() will be removed in a future version.", logLevel: .Info) return self.defaultInstance() } // MARK: - Setup methods public class func setup(logLevel: LogLevel = .Debug, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, writeToFile: AnyObject? = nil) { defaultInstance().setup(logLevel: logLevel, showLogLevel: showLogLevel, showFileNames: showFileNames, showLineNumbers: showLineNumbers, writeToFile: writeToFile) } public func setup(logLevel: LogLevel = .Debug, showLogLevel: Bool = true, showFileNames: Bool = true, showLineNumbers: Bool = true, writeToFile: AnyObject? = nil) { outputLogLevel = logLevel; if let unwrappedLogDestination: XCGLogDestinationProtocol = logDestination(XCGLogger.constants.baseConsoleLogDestinationIdentifier) { if unwrappedLogDestination is XCGConsoleLogDestination { let standardConsoleLogDestination = unwrappedLogDestination as XCGConsoleLogDestination standardConsoleLogDestination.showLogLevel = showLogLevel standardConsoleLogDestination.showFileName = showFileNames standardConsoleLogDestination.showLineNumber = showLineNumbers standardConsoleLogDestination.outputLogLevel = logLevel } } logAppDetails() if let unwrappedWriteToFile : AnyObject = writeToFile { // We've been passed a file to use for logging, set up a file logger let standardFileLogDestination: XCGFileLogDestination = XCGFileLogDestination(owner: self, writeToFile: unwrappedWriteToFile, identifier: XCGLogger.constants.baseFileLogDestinationIdentifier) standardFileLogDestination.showLogLevel = showLogLevel standardFileLogDestination.showFileName = showFileNames standardFileLogDestination.showLineNumber = showLineNumbers standardFileLogDestination.outputLogLevel = logLevel addLogDestination(standardFileLogDestination) } } // MARK: - Logging methods public class func logln(logMessage: String, logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().logln(logMessage, logLevel: logLevel, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func logln(logMessage: String, logLevel: LogLevel = .Debug, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { let date = NSDate() var logDetails: XCGLogDetails? = nil for logDestination in self.logDestinations { if (logDestination.isEnabledForLogLevel(logLevel)) { if logDetails == nil { logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } logDestination.processLogDetails(logDetails!) } } } public class func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) { self.defaultInstance().exec(logLevel: logLevel, closure: closure) } public func exec(logLevel: LogLevel = .Debug, closure: () -> () = {}) { if (!isEnabledForLogLevel(logLevel)) { return } closure() } public func logAppDetails(selectedLogDestination: XCGLogDestinationProtocol? = nil) { let date = NSDate() var buildString = "" if let infoDictionary = NSBundle.mainBundle().infoDictionary { if let CFBundleShortVersionString = infoDictionary["CFBundleShortVersionString"] as? String { buildString = "Version: \(CFBundleShortVersionString) " } if let CFBundleVersion = infoDictionary["CFBundleVersion"] as? String { buildString += "Build: \(CFBundleVersion) " } } let processInfo: NSProcessInfo = NSProcessInfo.processInfo() let XCGLoggerVersionNumber = XCGLogger.constants.versionString let logDetails: Array<XCGLogDetails> = [XCGLogDetails(logLevel: .Info, date: date, logMessage: "\(processInfo.processName) \(buildString)PID: \(processInfo.processIdentifier)", functionName: "", fileName: "", lineNumber: 0), XCGLogDetails(logLevel: .Info, date: date, logMessage: "XCGLogger Version: \(XCGLoggerVersionNumber) - LogLevel: \(outputLogLevel.description())", functionName: "", fileName: "", lineNumber: 0)] for logDestination in (selectedLogDestination != nil ? [selectedLogDestination!] : logDestinations) { for logDetail in logDetails { if !logDestination.isEnabledForLogLevel(.Info) { continue; } logDestination.processInternalLogDetails(logDetail) } } } // MARK: - Convenience logging methods public class func verbose(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().verbose(logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func verbose(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.logln(logMessage, logLevel: .Verbose, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public class func debug(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().debug(logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func debug(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.logln(logMessage, logLevel: .Debug, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public class func info(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().info(logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func info(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.logln(logMessage, logLevel: .Info, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public class func error(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().error(logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func error(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.logln(logMessage, logLevel: .Error, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public class func severe(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.defaultInstance().severe(logMessage, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public func severe(logMessage: String, functionName: String = __FUNCTION__, fileName: String = __FILE__, lineNumber: Int = __LINE__) { self.logln(logMessage, logLevel: .Severe, functionName: functionName, fileName: fileName, lineNumber: lineNumber) } public class func verboseExec(closure: () -> () = {}) { self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Verbose, closure: closure) } public func verboseExec(closure: () -> () = {}) { self.exec(logLevel: XCGLogger.LogLevel.Verbose, closure: closure) } public class func debugExec(closure: () -> () = {}) { self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Debug, closure: closure) } public func debugExec(closure: () -> () = {}) { self.exec(logLevel: XCGLogger.LogLevel.Debug, closure: closure) } public class func infoExec(closure: () -> () = {}) { self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Info, closure: closure) } public func infoExec(closure: () -> () = {}) { self.exec(logLevel: XCGLogger.LogLevel.Info, closure: closure) } public class func errorExec(closure: () -> () = {}) { self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Error, closure: closure) } public func errorExec(closure: () -> () = {}) { self.exec(logLevel: XCGLogger.LogLevel.Error, closure: closure) } public class func severeExec(closure: () -> () = {}) { self.defaultInstance().exec(logLevel: XCGLogger.LogLevel.Severe, closure: closure) } public func severeExec(closure: () -> () = {}) { self.exec(logLevel: XCGLogger.LogLevel.Severe, closure: closure) } // MARK: - Misc methods public func isEnabledForLogLevel (logLevel: XCGLogger.LogLevel) -> Bool { return logLevel >= self.outputLogLevel } public func logDestination(identifier: String) -> XCGLogDestinationProtocol? { for logDestination in logDestinations { if logDestination.identifier == identifier { return logDestination } } return nil } public func addLogDestination(logDestination: XCGLogDestinationProtocol) -> Bool { let existingLogDestination: XCGLogDestinationProtocol? = self.logDestination(logDestination.identifier) if existingLogDestination != nil { return false } logDestinations.append(logDestination) return true } public func removeLogDestination(logDestination: XCGLogDestinationProtocol) { removeLogDestination(logDestination.identifier) } public func removeLogDestination(identifier: String) { logDestinations = logDestinations.filter({$0.identifier != identifier}) } // MARK: - Private methods private func _logln(logMessage: String, logLevel: LogLevel = .Debug) { let date = NSDate() var logDetails: XCGLogDetails? = nil for logDestination in self.logDestinations { if (logDestination.isEnabledForLogLevel(logLevel)) { if logDetails == nil { logDetails = XCGLogDetails(logLevel: logLevel, date: date, logMessage: logMessage, functionName: "", fileName: "", lineNumber: 0) } logDestination.processInternalLogDetails(logDetails!) } } } // MARK: - DebugPrintable public var debugDescription: String { get { var description: String = "XCGLogger: \(identifier) - logDestinations: \r" for logDestination in logDestinations { description += "\t \(logDestination.debugDescription)\r" } return description } } } // Implement Comparable for XCGLogger.LogLevel public func < (lhs:XCGLogger.LogLevel, rhs:XCGLogger.LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
7b192ce64fa199a548a0fbf8694b9a39
39.465116
242
0.653982
false
false
false
false
mozilla-mobile/prox
refs/heads/master
Prox/Prox/Models/GeofenceRegion.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 Foundation class GeofenceRegion { let location: CLLocationCoordinate2D let identifier: String let radius: CLLocationDistance var onEntry: ((GeofenceRegion) -> ())? var onExit: ((GeofenceRegion) -> ())? private(set) lazy var region: CLCircularRegion = { let region = CLCircularRegion(center: self.location, radius: self.radius, identifier: self.identifier) region.notifyOnExit = self.onExit != nil region.notifyOnEntry = self.onEntry != nil return region }() init(location: CLLocationCoordinate2D, identifier: String, radius: CLLocationDistance, onEntry: ((GeofenceRegion)->())? = nil, onExit: ((GeofenceRegion)->())? = nil) { self.location = location self.identifier = identifier self.radius = radius self.onEntry = onEntry self.onExit = onExit } }
97d4488f8a4c2c9c5a9be29d657bf96a
36.034483
171
0.66946
false
false
false
false
DashiDashCam/iOS-App
refs/heads/master
Dashi/Dashi/Controllers/LoginViewController.swift
mit
1
// // LoginViewController.swift // Dashi // // Created by Arslan Memon on 11/5/17. // Copyright © 2017 Senior Design. All rights reserved. // import UIKit import PromiseKit import SwiftyJSON class LoginViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var errorMessage: UILabel! override func viewDidLoad() { super.viewDidLoad() updateConstraints() // Do any additional setup after loading the view. // done button above keyboard let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneClicked)) toolBar.setItems([doneButton], animated: true) email.inputAccessoryView = toolBar password.inputAccessoryView = toolBar // set orientation let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") // lock orientation AppUtility.lockOrientation(.portrait) } @objc func doneClicked() { view.endEditing(true) } override func viewWillAppear(_: Bool) { navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_: Bool) { navigationController?.isNavigationBarHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginPushed(_: Any) { // hide keyboard doneClicked() errorMessage.text = "" DashiAPI.loginWithPassword(username: email.text!, password: password.text!).then { json -> Void in if json["error"] == JSON.null { self.dismiss(animated: true, completion: nil) } }.catch { error in if let e = error as? DashiServiceError { // prints a more detailed error message from slim // print(String(data: (error as! DashiServiceError).body, encoding: String.Encoding.utf8)!) print(e.statusCode) print(JSON(e.body)) let json = JSON(e.body) if json["errors"].array != nil { self.errorMessage.text = json["errors"].arrayValue[0]["message"].string } else { self.errorMessage.text = json["errors"]["message"].string } } } } override func willTransition(to _: UITraitCollection, with _: UIViewControllerTransitionCoordinator) { updateConstraints() } // updates the hardcoded contraints associated with this view func updateConstraints() { // loop through view constraints for constraint in view.constraints { // the device is in landscape if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight { // "Username" label above input if constraint.identifier == "usernameLabelMarginTop" { constraint.constant = 10 } } else { // "Username" label above input if constraint.identifier == "usernameLabelMarginTop" { constraint.constant = 45 } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case email: password.becomeFirstResponder() default: password.resignFirstResponder() } return true } }
68e94ded486db48e88c9cd99227f0bbb
30.466667
140
0.61064
false
false
false
false
AfricanSwift/TUIKit
refs/heads/master
TUIKit/Source/UIElements/Widgets/TUITable.swift
mit
1
// // File: TUITable.swift // Created by: African Swift import Darwin public struct TUITable { /// Progress view // private var view: TUIView public var value = "" public init(_ v: [String]) { let width = maxWidth(v) guard let box = TUIBorder.single.toTUIBox() else { exit(EXIT_FAILURE) } let topMiddle = String(repeating: box.horizontal.top, count: width + 2) let middleMiddle = String(repeating: box.horizontal.middle, count: width + 2) let bottomMiddle = String(repeating: box.horizontal.bottom, count: width + 2) let top = "\(box.top.left)\(topMiddle)\(box.top.right)\n" let middle = "\(box.middle.left)\(middleMiddle)\(box.middle.right)\n" let bottom = "\(box.bottom.left)\(bottomMiddle)\(box.bottom.right)\n" self.value += top self.value += v .map { text in var result = String(box.vertical.left) + " " result += String(text).padding(toLength: width, withPad: " ", startingAt: 0) result += " " + String(box.vertical.right) return result } .joined(separator: "\n\(middle)") self.value += "\n\(bottom)" } public init (_ v: [[String]]) { var widths = Array<Int>(repeating: 0, count: v[0].count) guard let box = TUIBorder.single.toTUIBox() else { exit(EXIT_FAILURE) } for c in 0..<v[0].count { var width = 0 for r in 0..<v.count { let count = v[r][c].characters.count if count > width { width = count } } widths[c] = width } var top = "\(box.top.left)" var bottom = "\(box.bottom.left)" var middle = "\(box.middle.left)" for c in 0..<v[0].count { top += String(repeating: box.horizontal.top, count: widths[c] + 2) if c < v[0].count - 1 { top += "\(box.top.middle)" } bottom += String(repeating: box.horizontal.bottom, count: widths[c] + 2) if c < v[0].count - 1 { bottom += "\(box.bottom.middle)" } middle += String(repeating: box.horizontal.middle, count: widths[c] + 2) if c < v[0].count - 1 { middle += "\(box.middle.middle)" } } top += "\(box.top.right)" bottom += "\(box.bottom.right)" middle += "\(box.middle.right)" var data = "" for r in 0..<v.count { data += "\(box.vertical.left)" for c in 0..<v[0].count { data += " " + String(v[r][c]).padding(toLength: widths[c], withPad: " ", startingAt: 0) + " " if c < v[0].count - 1 { data += "\(box.vertical.middle)" } } data += "\(box.vertical.right)\n" if r < v.count - 1 { data += "\(middle)\n" } } let result = "\(top)\n\(data)\(bottom)\n" print(result) } func maxWidth(_ values: [String]) -> Int { var width = 0 for v in values { let count = v.characters.count if count > width { width = count } } return width } }
0a25a67f98c8e6e204fe5ae61128f75f
25.90991
101
0.536324
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/Common/CloudKitSync/FavoriteCharaDownloader.swift
mit
2
// // FavoriteCharaDownloader.swift // DereGuide // // Created by zzk on 2017/7/27. // Copyright © 2017 zzk. All rights reserved. // import CoreData /// download the newest remote units and re final class FavoriteCharaDownloader: ChangeProcessor { typealias Element = FavoriteChara var remote: FavoriteCharasRemote init(remote: FavoriteCharasRemote) { self.remote = remote } func setup(for context: ChangeProcessorContext) { remote.setupSubscription() } func processChangedLocalObjects(_ objects: [NSManagedObject], in context: ChangeProcessorContext) { // no-op } func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], in context: ChangeProcessorContext, completion: () -> ()) { var creates: [RemoteFavoriteChara] = [] var deletionIDs: [RemoteIdentifier] = [] // var updates: [RemoteFavoriteChara] = [] for change in changes { switch change { case .insert(let r) where r is RemoteFavoriteChara: creates.append(r as! RemoteFavoriteChara) case .delete(let id): deletionIDs.append(id) // case .update(let r) where r is RemoteFavoriteChara: // updates.append(r as! RemoteFavoriteChara) default: continue } } insert(creates, in: context) deleteFavoriteCharas(with: deletionIDs, in: context) if Config.cloudKitDebug && creates.count > 0 { print("favorite chara downloader: insert \(creates.count) from subscription") } context.delayedSaveOrRollback() completion() } func fetchLatestRemoteRecords(in context: ChangeProcessorContext) { remote.fetchLatestRecords(completion: { (remoteFavoriteCharas, errors) in self.insert(remoteFavoriteCharas, in: context) if errors.count == 0 { self.reserve(remoteFavoriteCharas, in: context) } }) } func entityAndPredicateForLocallyTrackedObjects(in context: ChangeProcessorContext) -> EntityAndPredicate<NSManagedObject>? { return nil } } extension FavoriteCharaDownloader { fileprivate func deleteFavoriteCharas(with ids: [RemoteIdentifier], in context: ChangeProcessorContext) { guard !ids.isEmpty else { return } context.perform { let objects = FavoriteChara.fetch(in: context.managedObjectContext) { (request) -> () in request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [FavoriteChara.predicateForRemoteIdentifiers(ids), FavoriteChara.notMarkedForLocalDeletionPredicate]) } if Config.cloudKitDebug && objects.count > 0 { print("favorite chara downloader: delete \(objects.count) from subscription") } objects.forEach { $0.markForLocalDeletion() } } } fileprivate func reserve(_ reserves: [RemoteFavoriteChara], in context: ChangeProcessorContext) { context.perform { let remoteRemoveds = { () -> [RemoteIdentifier] in let ids = reserves.map { $0.id } let favoriteCharas = FavoriteChara.fetch(in: context.managedObjectContext) { request in request.predicate = FavoriteChara.predicateForNotInRemoteIdentifiers(ids) request.returnsObjectsAsFaults = false } return favoriteCharas.map { $0.remoteIdentifier }.compactMap { $0 } }() // delete those have no remote records but left in local database self.deleteFavoriteCharas(with: remoteRemoveds, in: context) context.delayedSaveOrRollback() } } fileprivate func insert(_ remoteFavoriteChara: RemoteFavoriteChara, into context: ChangeProcessorContext) { remoteFavoriteChara.insert(into: context.managedObjectContext) { success in if success { context.delayedSaveOrRollback() } else { self.retryAfter(in: context, task: { self.insert(remoteFavoriteChara, into: context) }) } } } fileprivate func insert(_ inserts: [RemoteFavoriteChara], in context: ChangeProcessorContext) { context.perform { let existingFavoriteCharas = { () -> [RemoteIdentifier: FavoriteChara] in let ids = inserts.map { $0.id } let favoriteCharas = FavoriteChara.fetch(in: context.managedObjectContext) { request in request.predicate = FavoriteChara.predicateForRemoteIdentifiers(ids) request.returnsObjectsAsFaults = false } var result: [RemoteIdentifier: FavoriteChara] = [:] for favoriteChara in favoriteCharas { result[favoriteChara.remoteIdentifier!] = favoriteChara } return result }() for remoteFavoriteChara in inserts { guard existingFavoriteCharas[remoteFavoriteChara.id] == nil else { continue } self.insert(remoteFavoriteChara, into: context) } } } }
ed7719058d3c31a77464451f3adfb9bf
38.323529
188
0.610696
false
false
false
false
brodie20j/Reunion-iOS
refs/heads/master
NSW/PhotoUploadViewController.swift
mit
1
// // PhotoUploadViewController.swift // Carleton Reunion // // Created by Jonathan Brodie on 5/31/15. // Copyright (c) 2015 BTIN. All rights reserved. // Uses a Web View to display photo uploads. import UIKit class PhotoUploadViewController: UIViewController,UIWebViewDelegate { //This is a constant so we don't have some big ugly URL in the middle of the code let urlConstant: String="https://apps.carleton.edu/reunion/photos/submit/" @IBOutlet weak var activity: UIActivityIndicatorView! @IBOutlet weak var photoWebView: UIWebView! @IBOutlet weak var revealButtonItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setNavigationColors() self.navigationItem.title = "Photo Upload" revealButtonItem.target = self.revealViewController() revealButtonItem.action = "revealToggle:" self.photoWebView.delegate=self self.activity.startAnimating() self.navigationController?.navigationBar.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) self.getPhotoPage() } func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) { print("Webview fail with error \(error)"); } func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType)->Bool { return true; } //Start and stop the ActivityIndicator func webViewDidStartLoad(webView: UIWebView!) { self.activity.startAnimating() self.activity.hidden=false print("Webview started Loading") } func webViewDidFinishLoad(webView: UIWebView!) { self.activity.stopAnimating() self.activity.hidden=true print("Webview did finish load") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getPhotoPage() { var request = NSURLRequest(URL: NSURL(string: self.urlConstant)!) self.photoWebView.loadRequest(request) } // Set navbar styling to consistent with rest of app func setNavigationColors() { var navBar: UINavigationBar = self.navigationController!.navigationBar navBar.translucent = false navBar.barTintColor = NSWStyle.oceanBlueColor() navBar.titleTextAttributes = [NSForegroundColorAttributeName: NSWStyle.whiteColor(), NSFontAttributeName: NSWStyle.boldFont()] var barBtnItem: UIBarButtonItem = UIBarButtonItem(title: "", style: .Bordered, target: self, action: "popoverArrowDirection:") self.navigationItem.backBarButtonItem = revealButtonItem self.revealButtonItem.tintColor = NSWStyle.whiteColor() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
149a65b05df9e601723101d77b384cde
35.662921
137
0.697824
false
false
false
false
dcunited001/Spectra
refs/heads/master
Pod/Classes/BufferTexture.swift
mit
1
// // BufferTexture.swift // Pods // // Created by David Conner on 10/3/15. // // import Metal import simd public class BufferTexture { public typealias ColorType = float4 public var size: CGSize public var pixelSize = sizeof(ColorType) public var texture:MTLTexture // no pointer needed for this, just texture.replaceRegion() to write //private var pixelsPtr: UnsafeMutablePointer<Void> = nil init(device: MTLDevice, textureDescriptor: MTLTextureDescriptor) { size = CGSize(width: textureDescriptor.width, height: textureDescriptor.height) texture = device.newTextureWithDescriptor(textureDescriptor) } convenience init(device: MTLDevice, size: CGSize, format: MTLPixelFormat = MTLPixelFormat.RGBA32Float, mipmapped: Bool = false) { let texDesc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(format, width: Int(size.width), height: Int(size.height), mipmapped: false) self.init(device: device, textureDescriptor: texDesc) } public func writePixels(pixels: [ColorType]) { let region = MTLRegionMake2D(0, 0, Int(size.width), Int(size.height)) texture.replaceRegion(region, mipmapLevel: 0, withBytes: pixels, bytesPerRow: calcBytesPerRow()) } public func calcBytesPerRow() -> Int { return Int(size.width) * pixelSize } public func calcTotalBytes() -> Int { return calcTotalBytes(Int(size.width), h: Int(size.height)) } public func calcTotalBytes(w: Int, h: Int) -> Int { return w * h * pixelSize } public func randomPixels() -> [ColorType] { return (0...calcTotalBytes()) .lazy .map { _ in self.randomPixel() } } public func randomPixel() -> float4 { return float4(Float(arc4random())/Float(UInt32.max), Float(arc4random())/Float(UInt32.max), Float(arc4random())/Float(UInt32.max), 1.0) } }
8b4b9b57b43786f05d7f96a3778da514
32.775862
153
0.660541
false
false
false
false
aamays/Yelp
refs/heads/master
Yelp/BusinessDetailsViewController.swift
mit
1
// // BusinessDetailsViewController.swift // Yelp // // Created by Amay Singhal on 9/27/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit class BusinessDetailsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Properties // MARK: Outlets @IBOutlet weak var businessInfoTableView: UITableView! // MARK: Other var business: Business! struct ViewConstants { static let DetailsTableViewCells: [BusinessDetailVCCellIdentifiers] = [.BusinessDetailViewCell, .BusinessMapTableViewCell, .BusinessAddressTableViewCell, .BusinessPhoneTableViewCell] static let EstimatedRowHeight = CGFloat(100) } // MARK: - Life cycle methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] title = business.name setUpBusinessTableConfig() } // MARK: - Table view delegate and datasource methods func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch ViewConstants.DetailsTableViewCells[indexPath.row] { case .BusinessDetailViewCell: let cell = businessInfoTableView.dequeueReusableCellWithIdentifier(BusinessDetailVCCellIdentifiers.BusinessDetailViewCell.rawValue, forIndexPath: indexPath) as! BusinessDetailViewCell cell.business = business return cell case .BusinessMapTableViewCell: let cell = businessInfoTableView.dequeueReusableCellWithIdentifier(BusinessDetailVCCellIdentifiers.BusinessMapTableViewCell.rawValue, forIndexPath: indexPath) as! BusinessMapTableViewCell cell.businessLocation = business.businessLocation return cell case .BusinessAddressTableViewCell: let cell = businessInfoTableView.dequeueReusableCellWithIdentifier(BusinessDetailVCCellIdentifiers.BusinessAddressTableViewCell.rawValue, forIndexPath: indexPath) as! BusinessAddressTableViewCell cell.businessAddress = business.displayAddress return cell case .BusinessPhoneTableViewCell: let cell = businessInfoTableView.dequeueReusableCellWithIdentifier(BusinessDetailVCCellIdentifiers.BusinessPhoneTableViewCell.rawValue, forIndexPath: indexPath) as! BusinessPhoneTableViewCell cell.businessPhoneLabel.text = business.displayPhone return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ViewConstants.DetailsTableViewCells.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { businessInfoTableView.deselectRowAtIndexPath(indexPath, animated: true) if let _ = businessInfoTableView.cellForRowAtIndexPath(indexPath) as? BusinessPhoneTableViewCell { UIApplication.sharedApplication().openURL(NSURL(string: "tel:\(business.displayPhone!)")!) } } // MARK: - Helper methods private func setUpBusinessTableConfig() { businessInfoTableView.delegate = self businessInfoTableView.dataSource = self businessInfoTableView.rowHeight = UITableViewAutomaticDimension businessInfoTableView.estimatedRowHeight = ViewConstants.EstimatedRowHeight businessInfoTableView.tableFooterView = UIView(frame: CGRectZero) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
a3ecc0046d1294b87116106036d93526
43.247191
207
0.740731
false
false
false
false
motylevm/skstylekit
refs/heads/master
StyleKitTests/SKNavigationBarTests.swift
mit
1
// // Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import XCTest @testable import SKStyleKit class SKNavigationBarTests: XCTestCase { override func setUp() { super.setUp() basicSetup() } func testSetStyle() { // given let style = StyleKit.style(withName: "navBarStyle") let view = SKNavigationBar() // when view.style = style // then XCTAssertNotNil(style) XCTAssertEqual(view.styleName, "navBarStyle") } func testSetStyleByName() { // given let view = SKNavigationBar() // when view.styleName = "navBarStyle" // then XCTAssertNotNil(view.style) XCTAssertEqual(view.tintColor, UIColor.green) XCTAssertEqual(view.barTintColor, UIColor.blue) XCTAssertEqual(view.isTranslucent, false) checkStringStyle(attributes: view.titleTextAttributes, aligmentCheck: false) } }
501009480625001cfdc0a85643140d03
33.603175
86
0.661468
false
true
false
false
movabletype/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/ViewController/FolderListTableViewController.swift
mit
1
// // FolderListTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/08. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class FolderList: CategoryList { override func toModel(json: JSON)->BaseObject { return Folder(json: json) } override func fetch(offset: Int, success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) { if working {return} self.working = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo let success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in LOG("\(result)") if self.refresh { self.items = [] } self.totalCount = total self.parseItems(result) self.makeLevel() success(items: result, total: total) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } let failure: (JSON!-> Void) = { (error: JSON!)-> Void in LOG("failure:\(error.description)") failure(error) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } api.authenticationV2(authInfo.username, password: authInfo.password, remember: true, success:{_ in let params = ["limit":"9999", "sortOrder":"ascend"] api.listFolders(siteID: self.blog.id, options: params, success: success, failure: failure) }, failure: failure ) } } class FolderListTableViewController: BaseCategoryListTableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Select folders", comment: "Select folders") list = FolderList() (list as! FolderList).blog = self.blog // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() actionMessage = NSLocalizedString("Fetch folders", comment: "Fetch folders") self.fetch() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = self.list[indexPath.row] as! Folder object.isDirty = true if let sel = selected[selectedItem.id] { selected[selectedItem.id] = !sel } else { selected[selectedItem.id] = true } for item in self.list.items { if item.id != selectedItem.id { selected[item.id] = false } } self.tableView.reloadData() } @IBAction override func saveButtonPushed(sender: UIBarButtonItem) { var selectedObjects = [BaseObject]() for (id, value) in selected { if value { if !id.isEmpty { selectedObjects.append(list.objectWithID(id)!) } } } (object as! PageFolderItem).selected = selectedObjects as! [Folder] self.navigationController?.popViewControllerAnimated(true) } }
57cc1e7041e3d2fe6a5363eb7e46beb0
33.365714
157
0.617892
false
false
false
false
PedroTrujilloV/TIY-Assignments
refs/heads/develop
37--Resurgence/VenuesMenuQuadrat/Pods/QuadratTouch/Source/Shared/Endpoints/Users.swift
cc0-1.0
3
// // Users.swift // Quadrat // // Created by Constantine Fry on 26/10/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation public let UserSelf = "self" public class Users: Endpoint { override var endpoint: String { return "users" } /** https://developer.foursquare.com/docs/users/users */ public func get(userId: String = UserSelf, completionHandler: ResponseClosure? = nil) -> Task { return self.getWithPath(userId, parameters: nil, completionHandler: completionHandler) } // MARK: - General /** https://developer.foursquare.com/docs/users/requests */ public func requests(completionHandler: ResponseClosure? = nil) -> Task { let path = "requests" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/search */ public func search(parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = "search" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } // MARK: - Aspects /** https://developer.foursquare.com/docs/users/checkins */ public func checkins(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/checkins" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/friends */ public func friends(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/friends" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/lists */ public func lists(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/lists" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/mayorships */ public func mayorships(userId: String = UserSelf, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/mayorships" return self.getWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/photos */ public func photos(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/photos" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/tastes */ public func tastes(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/tastes" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/venuehistory */ public func venuehistory(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/venuehistory" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/venuelikes */ public func venuelikes(userId: String = UserSelf, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/venuelikes" return self.getWithPath(path, parameters: parameters, completionHandler: completionHandler) } // MARK: - Actions /** https://developer.foursquare.com/docs/users/approve */ public func approve(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/approve" return self.postWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/deny */ public func deny(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/deny" return self.postWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/setpings */ public func setpings(userId: String, value: Bool, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/setpings" let parameters = [Parameter.value: (value) ? "true":"false"] return self.postWithPath(path, parameters: parameters, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/unfriend */ public func unfriend(userId: String, completionHandler: ResponseClosure? = nil) -> Task { let path = userId + "/unfriend" return self.postWithPath(path, parameters: nil, completionHandler: completionHandler) } /** https://developer.foursquare.com/docs/users/update */ public func update(photoURL: NSURL, completionHandler: ResponseClosure? = nil) -> Task { let path = UserSelf + "/update" let task = self.uploadTaskFromURL(photoURL, path: path, parameters: nil, completionHandler: completionHandler) return task } }
65ed1119c49aa89c39aca7cccb471579
43.703125
118
0.665851
false
false
false
false
mikaelbo/MBFacebookImagePicker
refs/heads/master
MBFacebookImagePicker/ViewControllers/MBFacebookImagePickerController.swift
mit
1
// // MBFacebookImagePickerController.swift // FacebookImagePicker // // Copyright © 2017 Mikaelbo. All rights reserved. // import UIKit public enum MBFacebookImagePickerError: CustomNSError { case noFacebookAccessToken case unknown case invalidData case noConnection public static var errorDomain: String { return "MBFacebookImagePickerError" } public var errorCode: Int { switch self { case .noFacebookAccessToken: return 0 case .unknown: return 1 case .invalidData: return 2 case .noConnection: return 3 } } } public enum MBFacebookImagePickerResult { case completed(UIImage) case failed(Error) case cancelled } public class MBFacebookImagePickerController: UINavigationController { public var finishedCompletion: ((MBFacebookImagePickerResult) -> Void)? public init() { super.init(navigationBarClass: nil, toolbarClass: nil) viewControllers = [MBFacebookAlbumsViewController()] } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) viewControllers = [MBFacebookAlbumsViewController()] } public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } public override func viewDidLoad() { super.viewDidLoad() navigationBar.barTintColor = UIColor(red: 0.129995, green: 0.273324, blue: 0.549711, alpha: 1) navigationBar.tintColor = UIColor.white navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
dc0a03ea47dd4cb6c145823dd3abf61b
26.734375
102
0.700282
false
false
false
false
kickstarter/ios-ksapi
refs/heads/master
KsApi/models/templates/CategoryTemplates.swift
apache-2.0
1
import Prelude extension KsApi.Category { internal static let template = Category( color: nil, id: 1, name: "Art", parent: nil, parentId: nil, position: 1, projectsCount: 450, slug: "art" ) internal static let art = template |> Category.lens.id .~ 1 <> Category.lens.name .~ "Art" <> Category.lens.slug .~ "art" <> Category.lens.position .~ 1 internal static let filmAndVideo = template |> Category.lens.id .~ 11 <> Category.lens.name .~ "Film & Video" <> Category.lens.slug .~ "film-and-video" <> Category.lens.position .~ 7 internal static let games = template |> Category.lens.id .~ 12 <> Category.lens.name .~ "Games" <> Category.lens.slug .~ "games" <> Category.lens.position .~ 9 internal static let illustration = template |> Category.lens.id .~ 22 <> Category.lens.name .~ "Illustration" <> Category.lens.slug .~ "art/illustration" <> Category.lens.position .~ 4 <> Category.lens.parentId .~ Category.art.id <> Category.lens.parent .~ Category.art internal static let documentary = template |> Category.lens.id .~ 30 <> Category.lens.name .~ "Documentary" <> Category.lens.slug .~ "film-and-video/documentary" <> Category.lens.position .~ 4 <> Category.lens.parentId .~ Category.filmAndVideo.id <> Category.lens.parent .~ Category.filmAndVideo internal static let tabletopGames = template |> Category.lens.id .~ 34 <> Category.lens.name .~ "Tabletop Games" <> Category.lens.slug .~ "games/tabletop-games" <> Category.lens.position .~ 9 <> Category.lens.parentId .~ Category.games.id <> Category.lens.parent .~ Category.games }
7f28fe09a9654e3c9ec11054718a8b2f
29.535714
57
0.639766
false
false
false
false
grpc/grpc-swift
refs/heads/main
Sources/GRPC/WebCORSHandler.swift
apache-2.0
1
/* * Copyright 2019, gRPC 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 NIOCore import NIOHTTP1 /// Handler that manages the CORS protocol for requests incoming from the browser. internal class WebCORSHandler { var requestMethod: HTTPMethod? } extension WebCORSHandler: ChannelInboundHandler { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart func channelRead(context: ChannelHandlerContext, data: NIOAny) { // If the request is OPTIONS, the request is not propagated further. switch self.unwrapInboundIn(data) { case let .head(requestHead): self.requestMethod = requestHead.method if self.requestMethod == .OPTIONS { var headers = HTTPHeaders() headers.add(name: "Access-Control-Allow-Origin", value: "*") headers.add(name: "Access-Control-Allow-Methods", value: "POST") headers.add( name: "Access-Control-Allow-Headers", value: "content-type,x-grpc-web,x-user-agent" ) headers.add(name: "Access-Control-Max-Age", value: "86400") context.write( self.wrapOutboundOut(.head(HTTPResponseHead( version: requestHead.version, status: .ok, headers: headers ))), promise: nil ) return } case .body: if self.requestMethod == .OPTIONS { // OPTIONS requests do not have a body, but still handle this case to be // cautious. return } case .end: if self.requestMethod == .OPTIONS { context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) self.requestMethod = nil return } } // The OPTIONS request should be fully handled at this point. context.fireChannelRead(data) } } extension WebCORSHandler: ChannelOutboundHandler { typealias OutboundIn = HTTPServerResponsePart func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { let responsePart = self.unwrapOutboundIn(data) switch responsePart { case let .head(responseHead): var headers = responseHead.headers // CORS requires all requests to have an Allow-Origin header. headers.add(name: "Access-Control-Allow-Origin", value: "*") //! FIXME: Check whether we can let browsers keep connections alive. It's not possible // now as the channel has a state that can't be reused since the pipeline is modified to // inject the gRPC call handler. headers.add(name: "Connection", value: "close") context.write( self.wrapOutboundOut(.head(HTTPResponseHead( version: responseHead.version, status: responseHead.status, headers: headers ))), promise: promise ) default: context.write(data, promise: promise) } } }
1c6ef111b7f5ac0fa613509cd7b674f1
33.908163
94
0.671441
false
false
false
false