repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
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
allbto/iOS-DynamicRegistration
refs/heads/master
Pods/Swiftility/Swiftility/Swiftility/Classes/Types/Dynamic.swift
mit
1
// // Dynamic.swift // Swiftility // // Created by Allan Barbato on 9/9/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation public struct Dynamic<T> { public typealias Listener = T -> Void // MARK: - Private private var _listener: Listener? // MARK: - Properties /// Contained value. Changes fire listener if `self.shouldFire == true` public var value: T { didSet { guard shouldFire == true else { return } self.fire() } } /// Whether value didSet should fire or not public var shouldFire: Bool = true /// Whether fire() should call listener on main thread or not public var fireOnMainThread: Bool = true // Has a listener public var isBinded: Bool { return _listener != nil } // MARK: - Life cycle /// Init with a value public init(_ v: T) { value = v } // MARK: - Binding /** Bind a listener to value changes - parameter listener: Closure called when value changes */ public mutating func bind(listener: Listener?) { _listener = listener } /** Same as `bind` but also fires immediately - parameter listener: Closure called immediately and when value changes */ public mutating func bindAndFire(listener: Listener?) { self.bind(listener) self.fire() } // MARK: - Actions // Fires listener if not nil. Regardless of `self.shouldFire` public func fire() { if fireOnMainThread { dispatch_async(dispatch_get_main_queue(), { self._listener?(self.value) }) } else { self._listener?(self.value) } } /** Set value with optional firing. Regardless of `self.shouldFire` - parameter value: Value to update to - parameter =true;fire: Should fire changes of value */ public mutating func setValue(value: T, fire: Bool = true) { let originalShouldFire = shouldFire shouldFire = fire self.value = value shouldFire = originalShouldFire } }
395cd73058a2986fb6ca6f5344ba8cc3
21.3
76
0.571108
false
false
false
false
SPECURE/rmbt-ios-client
refs/heads/main
Sources/OperatorsResponse.swift
apache-2.0
1
/***************************************************************************************************** * Copyright 2016 SPECURE GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************************************/ import Foundation import ObjectMapper /// open class OperatorsResponse: BasicResponse { open class Operator: NSObject, Mappable { open var isDefault = false open var title: String = "" open var subtitle: String = "" open var idProvider: Int? open var provider: String? open var providerForRequest: String { if let idProvider = self.idProvider { return String(format: "%d", idProvider) } else if let provider = provider { return provider } return "" } public required init?(map: Map) { } open func mapping(map: Map) { isDefault <- map["default"] idProvider <- map["id_provider"] provider <- map["provider"] title <- map["title"] subtitle <- map["detail"] } } /// open var operators: [OperatorsResponse.Operator]? open var title: String = "" /// override open func mapping(map: Map) { super.mapping(map: map) operators <- map["options"] title <- map["title"] } }
f6d7d03ed89b73fcf89b06e73c14d39f
30.634921
103
0.529353
false
false
false
false
eBardX/XestiMonitors
refs/heads/master
Sources/Core/CoreLocation/BeaconRangingMonitor.swift
mit
1
// // BeaconRangingMonitor.swift // XestiMonitors // // Created by J. G. Pusey on 2018-03-21. // // © 2018 J. G. Pusey (see LICENSE.md) // #if os(iOS) import CoreLocation /// /// A `BeaconRangingMonitor` instance monitors a region for changes to the /// ranges (*i.e.,* the relative proximity) to the Bluetooth low-energy beacons /// within. /// public class BeaconRangingMonitor: BaseMonitor { /// /// Encapsulates changes to the beacon ranges within a region. /// public enum Event { /// /// The beacon ranges have been updated. /// case didUpdate(Info) } /// /// Encapsulates information associated with a beacon ranging monitor /// event. /// public enum Info { /// /// The current beacon ranges. /// case beacons([CLBeacon], CLBeaconRegion) /// /// The error encountered in attempting to determine the beacon ranges /// within the region. /// case error(Error, CLBeaconRegion) } /// /// Initializes a new `BeaconRangingMonitor`. /// /// - Parameters: /// - region: The beacon region to monitor. /// - queue: The operation queue on which the handler executes. /// - handler: The handler to call when a beacon range change is /// detected. /// public init(region: CLBeaconRegion, queue: OperationQueue, handler: @escaping (Event) -> Void) { self.adapter = .init() self.handler = handler self.locationManager = LocationManagerInjector.inject() self.queue = queue self.region = region super.init() self.adapter.didFail = handleDidFail self.adapter.didRangeBeacons = handleDidRangeBeacons self.adapter.rangingBeaconsDidFail = handleRangingBeaconsDidFail self.locationManager.delegate = self.adapter } /// /// The beacon region being monitored. /// public let region: CLBeaconRegion /// /// A Boolean value indicating whether the region is actively being tracked /// using ranging. There is a system-imposed, per-app limit to how many /// regions can be actively ranged. /// public var isActivelyRanged: Bool { return isMonitoring && locationManager.rangedRegions.contains(region) } /// /// A Boolean value indicating whether the device supports the ranging of /// Bluetooth beacons. /// public var isAvailable: Bool { return type(of: locationManager).isRangingAvailable() } private let adapter: LocationManagerDelegateAdapter private let handler: (Event) -> Void private let locationManager: LocationManagerProtocol private let queue: OperationQueue private func handleDidFail(_ error: Error) { handler(.didUpdate(.error(error, region))) } private func handleDidRangeBeacons(_ region: CLBeaconRegion, _ beacons: [CLBeacon]) { if self.region == region { self.handler(.didUpdate(.beacons(beacons, region))) } } private func handleRangingBeaconsDidFail(_ region: CLBeaconRegion, _ error: Error) { if self.region == region { self.handler(.didUpdate(.error(error, region))) } } override public func cleanupMonitor() { locationManager.stopRangingBeacons(in: region) super.cleanupMonitor() } override public func configureMonitor() { super.configureMonitor() locationManager.startRangingBeacons(in: region) } } #endif
eae718b2739a1074b1ebf62fc5679a05
26.864662
79
0.607933
false
false
false
false
Authman2/AUNavigationMenuController
refs/heads/master
AUNavigationMenuController/Classes/NavigationMenuItem.swift
gpl-3.0
2
// // NavigationMenuItem.swift // TestingAUNavMenuCont // // Created by Adeola Uthman on 11/25/16. // Copyright © 2016 Adeola Uthman. All rights reserved. // import Foundation import UIKit public class NavigationMenuItem: NSObject { // The name of the menu item. public var name: String!; // The iamge that goes along with the menu item. public var image: UIImage?; // The destination view controller for when this menu item is tapped. public var destination: UIViewController!; // The overall navigation controller. let navCont: AUNavigationMenuController!; // The completion method. var completion: (() -> Void)?; ///////////////////////// // // Methods // ///////////////////////// init(name: String, image: UIImage?, navCont: AUNavigationMenuController, destination: UIViewController, completion: (() -> Void)?) { self.name = name; self.image = image; self.destination = destination; self.navCont = navCont; self.completion = completion; navCont.navigationItem.hidesBackButton = true; } /* Goes to the destination view controller. */ public func goToDestination(toggle: Bool) { if navCont.topViewController != destination { navCont.popToRootViewController(animated: false); navCont.pushViewController(destination, animated: false); destination.navigationItem.hidesBackButton = true; if(toggle) { navCont.togglePulldownMenu(); } } else { navCont.togglePulldownMenu(); } if let comp = completion { comp(); } } }
204f361a579b43a6fd245f7413c2baa2
22.818182
136
0.56434
false
false
false
false
WestlakeAPC/game-off-2016
refs/heads/master
external/Fiber2D/Fiber2D/Scheduler.swift
apache-2.0
1
// // Scheduler.swift // Fiber2D // // Created by Andrey Volodin on 28.08.16. // Copyright © 2016 s1ddok. All rights reserved. // private class MockNode: Node { override var priority: Int { get { return Int.min } set { } } } internal struct UnownedContainer<T> where T: AnyObject { unowned var value : T init(_ value: T) { self.value = value } } /** Scheduler is responsible for triggering scheduled callbacks. All scheduled and timed events should use this class, rather than NSTimer. Generally, you interface with the scheduler by using the "schedule"/"scheduleBlock" methods in Node. You may need to aess Scheduler in order to aess read-only time properties or to adjust the time scale. */ public final class Scheduler { /** Modifies the time of all scheduled callbacks. You can use this property to create a 'slow motion' or 'fast forward' effect. Default is 1.0. To create a 'slow motion' effect, use values below 1.0. To create a 'fast forward' effect, use values higher than 1.0. @warning It will affect EVERY scheduled selector / action. */ public var timeScale: Time = 1.0 /** Current time the scheduler is calling a block for. */ internal(set) var currentTime: Time = 0.0 /** Time of the most recent update: calls. */ internal(set) var lastUpdateTime: Time = 0.0 /** Time of the most recent fixedUpdate: calls. */ private(set) var lastFixedUpdateTime: Time = 0.0 /** Maximum allowed time step. If the CPU can't keep up with the game, time will slow down. */ var maxTimeStep: Time = 1.0 / 10.0 /** The time between fixedUpdate: calls. */ var fixedUpdateInterval: Time { get { return fixedUpdateTimer.repeatInterval } set { fixedUpdateTimer.repeatInterval = newValue } } internal var heap = [Timer]() var scheduledTargets = [ScheduledTarget]() var updatableTargets = [Updatable & Pausable]() var fixedUpdatableTargets = [FixedUpdatable & Pausable]() var actionTargets = [UnownedContainer<ScheduledTarget>]() internal var updatableTargetsNeedSorting = true internal var fixedUpdatableTargetsNeedSorting = true var fixedUpdateTimer: Timer! private let mock = MockNode() public var actionsRunInFixedMode = false init() { fixedUpdateTimer = schedule(block: { [unowned self](timer:Timer) in if timer.invokeTime > 0.0 { if self.fixedUpdatableTargetsNeedSorting { self.fixedUpdatableTargets.sort { $0.priority < $1.priority } self.fixedUpdatableTargetsNeedSorting = false } for t in self.fixedUpdatableTargets { t.fixedUpdate(delta: timer.repeatInterval) } if self.actionsRunInFixedMode { self.updateActions(timer.repeatInterval) } self.lastFixedUpdateTime = timer.invokeTime } }, for: mock, withDelay: 0) fixedUpdateTimer.repeatCount = TIMER_REPEAT_COUNT_FOREVER fixedUpdateTimer.repeatInterval = Time(Setup.shared.fixedUpdateInterval) } } // MARK: Update extension Scheduler { internal func schedule(timer: Timer) { heap.append(timer) timer.scheduled = true } internal func update(to targetTime: Time) { assert(targetTime >= currentTime, "Cannot step to a time in the past") heap.sort() while heap.count > 0 { let timer = heap.first! let invokeTime = timer.invokeTimeInternal if invokeTime > targetTime { break; } else { heap.removeFirst() timer.scheduled = false } currentTime = invokeTime guard !timer.paused else { continue } if timer.requiresDelay { timer.apply(pauseDelay: currentTime) schedule(timer: timer) } else { timer.block?(timer) if timer.repeatCount > 0 { if timer.repeatCount < TIMER_REPEAT_COUNT_FOREVER { timer.repeatCount -= 1 } timer.deltaTime = timer.repeatInterval let delay = timer.deltaTime timer.invokeTimeInternal += delay assert(delay > 0.0, "Rescheduling a timer with a repeat interval of 0 will cause an infinite loop.") self.schedule(timer: timer) } else { guard let scheduledTarget = timer.scheduledTarget else { continue } scheduledTarget.remove(timer: timer) if scheduledTarget.empty { scheduledTargets.removeObject(scheduledTarget) } timer.invalidate() } } } currentTime = targetTime } internal func update(_ dt: Time) { let clampedDelta = min(dt*timeScale, maxTimeStep) update(to: currentTime + clampedDelta) if self.updatableTargetsNeedSorting { self.updatableTargets.sort { $0.priority < $1.priority } self.updatableTargetsNeedSorting = false } for t in updatableTargets { if !t.paused { t.update(delta: clampedDelta) } } if !self.actionsRunInFixedMode { updateActions(dt) } lastUpdateTime = currentTime } internal func updateActions(_ dt: Time) { actionTargets = actionTargets.filter { let st = $0.value guard !st.paused else { return st.hasActions } for i in 0..<st.actions.count { st.actions[i].step(dt: dt) if st.actions[i].isDone { st.actions[i].stop() } } st.actions = st.actions.filter { return !$0.isDone } return st.hasActions } } } // MARK: Getters extension Scheduler { func scheduledTarget(for target: Node, insert: Bool) -> ScheduledTarget? { var scheduledTarget = scheduledTargets.first { $0.target === target } if scheduledTarget == nil && insert { scheduledTarget = ScheduledTarget(target: target) scheduledTargets.append(scheduledTarget!) // New targets are implicitly paused. scheduledTarget!.paused = true } return scheduledTarget } func schedule(block: @escaping TimerBlock, for target: Node, withDelay delay: Time) -> Timer { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! let timer = Timer(delay: delay, scheduler: self, scheduledTarget: scheduledTarget, block: block) self.schedule(timer: timer) timer.next = scheduledTarget.timers scheduledTarget.timers = timer return timer } func schedule(target: Node) { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! // Don't schedule something more than once. if !scheduledTarget.enableUpdates { scheduledTarget.enableUpdates = true if target.updatableComponents.count > 0 { schedule(updatable: target) } if target.fixedUpdatableComponents.count > 0 { schedule(fixedUpdatable: target) } } } func unscheduleUpdates(from target: Node) { guard let scheduledTarget = self.scheduledTarget(for: target, insert: false) else { return } scheduledTarget.enableUpdates = false let target = scheduledTarget.target! if target.updatableComponents.count > 0 { unschedule(updatable: target) } if target.fixedUpdatableComponents.count > 0 { unschedule(fixedUpdatable: target) } } func unschedule(target: Node) { if let scheduledTarget = self.scheduledTarget(for: target, insert: false) { // Remove the update methods if they are scheduled if scheduledTarget.enableUpdates { unschedule(updatable: scheduledTarget.target!) unschedule(fixedUpdatable: scheduledTarget.target!) } if scheduledTarget.hasActions { actionTargets.remove(at: actionTargets.index { $0.value === scheduledTarget }!) } scheduledTarget.invalidateTimers() scheduledTargets.removeObject(scheduledTarget) } } func isTargetScheduled(target: Node) -> Bool { return self.scheduledTarget(for: target, insert: false) != nil } func setPaused(paused: Bool, target: Node) { let scheduledTarget = self.scheduledTarget(for: target, insert: false)! scheduledTarget.paused = paused } func isTargetPaused(target: Node) -> Bool { let scheduledTarget = self.scheduledTarget(for: target, insert: false)! return scheduledTarget.paused } func timersForTarget(target: Node) -> [Timer] { guard let scheduledTarget = self.scheduledTarget(for: target, insert: false) else { return [] } var arr = [Timer]() var timer = scheduledTarget.timers while timer != nil { if !timer!.invalid { arr.append(timer!) } timer = timer!.next } return arr } } // MARK: Scheduling Actions extension Scheduler { func add(action: ActionContainer, target: Node, paused: Bool) { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! scheduledTarget.paused = paused if scheduledTarget.hasActions { //assert(!scheduledTarget.actions.contains(action), "Action already running on this target.") } else { // This is the first action that has been scheduled for this target. // It needs to be added to the list of targets with actions. actionTargets.append(UnownedContainer(scheduledTarget)) } scheduledTarget.add(action: action) scheduledTarget.actions[scheduledTarget.actions.count - 1].start(with: target) } func removeAllActions(from target: Node) { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! scheduledTarget.actions = [] if let idx = actionTargets.index(where: { $0.value === scheduledTarget }) { actionTargets.remove(at: idx) } } func removeAction(by tag: Int, target: Node) { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! scheduledTarget.actions = scheduledTarget.actions.filter { return $0.tag != tag } guard scheduledTarget.hasActions else { return } actionTargets.remove(at: actionTargets.index { $0.value === scheduledTarget }!) } func getAction(by tag: Int, target: Node) -> ActionContainer? { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! for action: ActionContainer in scheduledTarget.actions { if (action.tag == tag) { return action } } return nil } func actions(for target: Node) -> [ActionContainer] { let scheduledTarget = self.scheduledTarget(for: target, insert: true)! return scheduledTarget.actions } } public extension Scheduler { public func schedule(updatable: Updatable & Pausable) { updatableTargets.append(updatable) updatableTargetsNeedSorting = true } public func unschedule(updatable: Updatable & Pausable) { updatableTargets.removeObject(updatable) } public func schedule(fixedUpdatable: FixedUpdatable & Pausable) { fixedUpdatableTargets.append(fixedUpdatable) fixedUpdatableTargetsNeedSorting = true } public func unschedule(fixedUpdatable: FixedUpdatable & Pausable) { fixedUpdatableTargets.removeObject(fixedUpdatable) } }
a77e5cbc2a5c175e28e4e275f84ff9c9
32.269923
136
0.571936
false
false
false
false
uias/Pageboy
refs/heads/main
Sources/Pageboy/Utilities/WeakContainer.swift
mit
1
// // WeakContainer.swift // Pageboy iOS // // Created by Merrick Sapsford on 02/03/2019. // Copyright © 2019 UI At Six. All rights reserved. // import Foundation internal final class WeakWrapper<T: AnyObject> { private(set) weak var object: T? init(_ object: T) { self.object = object } } extension WeakWrapper: Equatable { static func == (lhs: WeakWrapper, rhs: WeakWrapper) -> Bool { return lhs.object === rhs.object } }
1b2728f3bd7bac48b6d841475e2ac69e
18.28
65
0.622407
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
refs/heads/master
Example/winguSDK-iOS/ViewController.swift
apache-2.0
1
// // ViewController.swift // winguSDK-iOS // // Created by Jakub Mazur on 08/16/2017. // Copyright (c) 2017 wingu AG. All rights reserved. // import UIKit import winguSDK class ViewController: UIViewController { let winguSegueIdentifier = "loadWinguSegue" @IBOutlet weak var tableView: UITableView! var beaconsLocationManger : WinguLocations! var channels : [Channel] = [Channel]() { didSet { self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() self.beaconsLocationManger = WinguLocations.sharedInstance self.beaconsLocationManger.delegate = self self.beaconsLocationManger.startBeaconsRanging() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == winguSegueIdentifier { let gp = sender as? Channel let destVC = (segue.destination as! WinguDeckViewController) destVC.content = gp?.content! destVC.channelId = gp?.uID } } } // MARK: - BeaconsLocationManagerDelegate extension ViewController : WinguLocationsDelegate { func winguRangedChannels(_ channels: [Channel]) { self.channels = channels } } // MARK: - UITableViewDelegate, UITableViewDataSource extension ViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell=UITableViewCell(style: .subtitle, reuseIdentifier: "winguDemoCell") let guidepost : Channel = self.channels[indexPath.row] cell.textLabel?.text = guidepost.name cell.detailTextLabel?.text = guidepost.uID return cell } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.channels.count } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: winguSegueIdentifier, sender: self.channels[indexPath.row]) } }
7fbb71f9f8412e63639973e1ce3ec3ee
31.846154
101
0.684309
false
false
false
false
jgainfort/FRPlayer
refs/heads/master
FRPlayer/PlayerReducer.swift
mit
1
// // PlayerReducer.swift // FRPlayer // // Created by John Gainfort Jr on 3/31/17. // Copyright © 2017 John Gainfort Jr. All rights reserved. // import AVFoundation import ReSwift func playerReducer(state: PlayerState?, action: Action) -> PlayerState { var state = state ?? initialPlayerState() switch action { case _ as ReSwiftInit: break case let action as UpdatePlayerStatus: state.status = action.status case let action as UpdateTimeControlStatus: state.timeControlStatus = action.status case let action as UpdatePlayerItemStatus: state.itemStatus = action.status case let action as UpdatePlayerItem: state.currentItem = action.item case let action as UpdatePlayerCurrentTime: state.currentTime = action.currentTime default: break } return state } func initialPlayerState() -> PlayerState { let url = URL(string: "nil")! let item = AVPlayerItem(url: url) return PlayerState(status: .unknown, timeControlStatus: .waitingToPlayAtSpecifiedRate, itemStatus: .unknown, currentItem: item, currentTime: -1) }
edb0adafbbb3de977d75394fba8a15da
28.128205
148
0.695423
false
false
false
false
josmas/swiftFizzBuzz
refs/heads/master
FizzBuzzTests/BrainTests.swift
mit
1
// // BrainTests.swift // FizzBuzz // // Created by Jose Dominguez on 15/01/2016. // Copyright © 2016 Jos. All rights reserved. // import XCTest @testable import FizzBuzz class BrainTests: XCTestCase { let brain = Brain() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testIsDivisibleByThree(){ let result = brain.isDivisibleByThree(3); XCTAssertEqual(result, true) let result2 = brain.isDivisibleByThree(1); XCTAssertEqual(result2, false) } func testIsDivisibleByFive(){ let result = brain.isDivisibleByFive(5); XCTAssertEqual(result, true) let result2 = brain.isDivisibleByFive(3); XCTAssertEqual(result2, false) } func testIsDivisibleByFifteen(){ let result = brain.isDivisibleByFive(30); XCTAssertEqual(result, true) let result2 = brain.isDivisibleByFive(51); XCTAssertEqual(result2, false) } func testSayFizz(){ XCTAssertEqual(brain.check(3), Move.Fizz) } func testSayBuzz(){ XCTAssertEqual(brain.check(5), Move.Buzz) } func testSayFizzBuzz(){ XCTAssertEqual(brain.check(30), Move.FizzBuzz) } func testSayNumber(){ XCTAssertEqual(brain.check(1), Move.Number) } }
8da15e81a890ff8f69e10fce50673f05
19.815385
54
0.630451
false
true
false
false
mmisesin/github_client
refs/heads/master
Github Client/LoginViewController.swift
mit
1
// // ViewController.swift // Github Client // // Created by Artem Misesin on 3/16/17. // Copyright © 2017 Artem Misesin. All rights reserved. // import UIKit import OAuthSwift import SwiftyJSON class SingleOAuth{ static let shared = SingleOAuth() var oAuthSwift: OAuthSwift? var owner: String? } class LoginViewController: OAuthViewController { var oAuthSwift: OAuthSwift? @IBOutlet weak var mainTableView: UITableView! var repos: [(name: String, language: String)] = [] var reposInfo: JSON? var spinner: UIActivityIndicatorView = UIActivityIndicatorView() @IBOutlet weak var logOutItem: UIBarButtonItem! @IBOutlet weak var signInItem: UIBarButtonItem! lazy var internalWebViewController: WebViewController = { let controller = WebViewController() controller.view = UIView(frame: UIScreen.main.bounds) // needed if no nib or not loaded from storyboard controller.delegate = self controller.viewDidLoad()// allow WebViewController to use this ViewController as parent to be presented return controller }() override func viewDidLoad() { super.viewDidLoad() logOutItem.isEnabled = false spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray) spinner.frame = CGRect(x: self.view.bounds.midX - 10, y: self.view.bounds.midY - 10, width: 20.0, height: 20.0) // (or wherever you want it in the button) self.view.addSubview(spinner) doOAuthGithub() // Do any additional setup after loading the view, typically from a nib. let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem } @IBAction func signIn(_ sender: UIBarButtonItem) { doOAuthGithub() //self.test(SingleOAuth.shared.oAuthSwift as! OAuth2Swift) } @IBAction func logOut(_ sender: UIBarButtonItem) { let token = self.oAuthSwift?.client.credential.oauthToken let storage = HTTPCookieStorage.shared if let cookies = storage.cookies { for cookie in cookies { storage.deleteCookie(cookie) } } URLCache.shared.removeAllCachedResponses() URLCache.shared.diskCapacity = 0 URLCache.shared.memoryCapacity = 0 self.oAuthSwift?.cancel() //doOAuthGithub() repos.removeAll() self.mainTableView.reloadData() signInItem.isEnabled = true logOutItem.isEnabled = false } func doOAuthGithub(){ let oauthswift = OAuth2Swift( consumerKey: "dc77c40af509089c9af0", consumerSecret: "b0d78d5401b2324db779aaf0029c793400935487", authorizeUrl: "https://github.com/login/oauth/authorize", accessTokenUrl: "https://github.com/login/oauth/access_token", responseType: "code" ) self.oAuthSwift = oauthswift SingleOAuth.shared.oAuthSwift = oauthswift oauthswift.authorizeURLHandler = getURLHandler() let state = generateState(withLength: 20) let _ = oauthswift.authorize( withCallbackURL: URL(string: "http://oauthswift.herokuapp.com/callback/github_client")!, scope: "user,repo", state: state, success: { credential, response, parameters in self.spinner.startAnimating() self.spinner.alpha = 1.0 self.mainTableView.isHidden = true self.signInItem.isEnabled = false self.logOutItem.isEnabled = true self.test(oauthswift) }, failure: { error in print(error.description) } ) } func test(_ oauthswift: OAuth2Swift) { let url :String = "https://api.github.com/user/repos" let parameters :Dictionary = Dictionary<String, AnyObject>() let _ = oauthswift.client.get( url, parameters: parameters, success: { response in let jsonDict = try? JSON(response.jsonObject()) if let arrayNames = jsonDict?.arrayValue.map({$0["name"].stringValue}){ if let arrayLanguages = jsonDict?.arrayValue.map({$0["language"].stringValue}){ for i in 0..<arrayNames.count{ self.repos.append((arrayNames[i], arrayLanguages[i])) } } } //print(jsonDict) self.spinner.stopAnimating() self.spinner.alpha = 0.0 self.mainTableView.isHidden = false self.reposInfo = jsonDict self.mainTableView.reloadData() }, failure: { error in self.showAlertView(title: "Error", message: error.localizedDescription) } ) } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController!, ontoPrimaryViewController primaryViewController: UIViewController!) -> Bool{ return true } } extension LoginViewController: OAuthWebViewControllerDelegate { func oauthWebViewControllerDidPresent() { } func oauthWebViewControllerDidDismiss() { } func oauthWebViewControllerWillAppear() { } func oauthWebViewControllerDidAppear() { } func oauthWebViewControllerWillDisappear() { } func oauthWebViewControllerDidDisappear() { // Ensure all listeners are removed if presented web view close oAuthSwift?.cancel() } } extension LoginViewController{ func showAlertView(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } func showTokenAlert(name: String?, credential: OAuthSwiftCredential) { var message = "oauth_token:\(credential.oauthToken)" if !credential.oauthTokenSecret.isEmpty { message += "\n\noauth_token_secret:\(credential.oauthTokenSecret)" } self.showAlertView(title: "Service", message: message) } // MARK: handler func getURLHandler() -> OAuthSwiftURLHandlerType { if internalWebViewController.parent == nil { self.addChildViewController(internalWebViewController) } return internalWebViewController } // override func prepare(for segue: OAuthStoryboardSegue, sender: Any?) { // if segue.identifier == Storyboards.Main.FormSegue { // #if os(OSX) // let controller = segue.destinationController as? FormViewController // #else // let controller = segue.destination as? FormViewController // #endif // // Fill the controller // if let controller = controller { // controller.delegate = self // } // } // // super.prepare(for: segue, sender: sender) // } } extension LoginViewController: UITableViewDelegate, UITableViewDataSource { // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell") cell.textLabel?.text = repos[indexPath.row].name cell.detailTextLabel?.text = repos[indexPath.row].language return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let vc = self.parent?.parent as? GlobalSplitViewController{ vc.collapseDVC = false performSegue(withIdentifier: "showDetail", sender: tableView.cellForRow(at: indexPath)) mainTableView.deselectRow(at: indexPath, animated: false) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.mainTableView.indexPathForSelectedRow { let repoInfoVC = (segue.destination as! UINavigationController).topViewController as! MainViewController repoInfoVC.title = repos[indexPath.row].name let arrayAuthor = reposInfo?.arrayValue.map({$0["owner"].dictionaryValue}).map({$0["login"]?.stringValue}) repoInfoVC.authorString = arrayAuthor![indexPath.row]! let arrayImage = reposInfo?.arrayValue.map({$0["owner"].dictionaryValue}).map({$0["avatar_url"]?.stringValue}) repoInfoVC.imageURLString = arrayImage![indexPath.row]! let arrayForks = reposInfo?.arrayValue.map({$0["forks"].stringValue}) repoInfoVC.forksNumber = Int(arrayForks![indexPath.row])! let arrayWatchers = reposInfo?.arrayValue.map({$0["watchers_count"].stringValue}) repoInfoVC.watchersNumber = Int(arrayWatchers![indexPath.row])! let arrayDescription = reposInfo?.arrayValue.map({$0["description"].stringValue}) repoInfoVC.descriptionString = arrayDescription![indexPath.row] } } } }
ba8ab13ce8d5dce49f5e37fb8df12ac5
37
225
0.624794
false
false
false
false
m-alani/contests
refs/heads/master
leetcode/letterCombinationsOfAPhoneNumber.swift
mit
1
// // letterCombinationsOfAPhoneNumber.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/letter-combinations-of-a-phone-number/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { var mapping: [[Character]] = [[" "], [], ["a","b","c"], ["d","e","f"], ["g","h","i"], ["j","k","l"], ["m","n","o"], ["p","q","r","s"], ["t","u","v"], ["w","x","y","z"] ] var output = [String]() func letterCombinations(_ digits: String) -> [String] { let input = [Character](digits.characters) if (input.count > 0) { recursiveSolution(input, [Character]()) } return output } func recursiveSolution(_ digits: [Character], _ word: [Character]) { if digits.count == 0 { output.append(String(word)) return } let digit = Int(String(digits[0]).utf8.first!) - 48 var newDigits = digits newDigits.removeFirst() for char in mapping[digit] { var newWord = word newWord.append(char) recursiveSolution(newDigits, newWord) } } }
58405c405b8c6a50e9475d636c4c36db
31.543478
123
0.469606
false
false
false
false
priya273/stockAnalyzer
refs/heads/master
Stock Analyzer/Stock Analyzer/UserProvider.swift
apache-2.0
1
// // UserTrackServices.swift // Stock Analyzer // // Created by Naga sarath Thodime on 3/14/16. // Copyright © 2016 Priyadarshini Ragupathy. All rights reserved. // import Foundation import Alamofire import UIKit protocol UserCreationDelegate { func UserCreationSuccess() func UserCreationFailed() } class UserProvider { let UserStatusCodeAlreadyExists = 200; let UserCreatedStatusCode = 201 let BadRequest = 400 var Delegate : UserCreationDelegate! func PostNewUserRecord(user : UserContract) { let url = NSURL(string: "http://stockanalyzer.azurewebsites.net/api/user"); let req = NSMutableURLRequest(URL : url!) req.HTTPMethod = "POST" let dict: [String : String] = [ "id" : user.id!, "Email": user.Email! ] req.setValue("application/json", forHTTPHeaderField: "Content-Type") do { req.HTTPBody = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions()) } catch { print("Exception Converting to jason.") } Alamofire.request(req).responseJSON { Response in print(Response.response?.statusCode); if(Response.response?.statusCode == 400 || Response.response?.statusCode == 500) { self.Delegate?.UserCreationFailed() } else { self.Delegate?.UserCreationSuccess() } } } }
6caa1783d6f3f3c7fb2f330e016498c1
22.32
108
0.522883
false
false
false
false
brendancboyle/SecTalk-iOS
refs/heads/master
SecTalk/SecTalk Framework/STConnection.swift
mit
1
// // STConnection.swift // SecTalk // // Created by Brendan Boyle on 5/29/15. // Copyright (c) 2015 DBZ Technology. All rights reserved. // import UIKit import AFNetworking import SwiftyJSON import CryptoSwift class STConnection: NSObject { static let TOTPSecret:String = "JBSWY3DPEHPK3PXP" static var APNSToken:String = "" class func getTOTPCode() -> String { let secretData:NSData = NSData(base32String: STConnection.TOTPSecret) var now:NSDate = NSDate() var generator:TOTPGenerator = TOTPGenerator(secret: secretData, algorithm: kOTPGeneratorSHA512Algorithm, digits: 6, period: 30) let pin: String = generator.generateOTPForDate(now) //println("Pin:"+pin) //let data = pin.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) //let encryptedData = pin.sha512() return pin } /* HTTP GET request. Returns HTML as a string value url (String): URL of the data resource callback (JSON): Callback method to update local data source (Requires SwiftyJSON) */ class func getHTML(url:String, callback: (String) -> Void, verbose: Bool) { //Allocate an AFHTTP Request object var manager = AFHTTPRequestOperationManager(); manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token") manager.responseSerializer = AFHTTPResponseSerializer(); //Query using the GET method. If successful, pass the JSON object to the callback function manager.GET( url, parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in let text = NSString(data: responseObject as! NSData, encoding: NSUTF8StringEncoding) if verbose { println(String(format: "HTML: %@", text!)) } /* Build a SwiftyJSON object from the JSON object let dataFromString = text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var jsonResponse = JSON(data: dataFromString!) */ //Invoke the callback method callback(text as! String) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error ("+url+"): " + error.localizedDescription) }) } /* HTTP GET request. Returns JSON as a SwiftyJSON object url (String): URL of the data resource callback (JSON): Callback method to update local data source (Requires SwiftyJSON) */ class func getJSON(url:String, callback: (JSON) -> Void, verbose: Bool) { //Allocate an AFHTTP Request object var manager = AFHTTPRequestOperationManager(); manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token") //Query using the GET method. If successful, pass the JSON object to the callback function manager.GET( url, parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in if verbose { println("JSON: " + responseObject.description) } //Build a SwiftyJSON object from the JSON object let jsonResponse = JSON(responseObject) //Invoke the callback method callback(jsonResponse) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error ("+url+"): " + error.localizedDescription) }) } /* HTTP PUT request. Returns JSON as a SwiftyJSON object url (String): URL of the data resource parameters (NSDictionary): POST parameters callback (JSON): Callback method to update local data source (Requires SwiftyJSON) verbose (boolean): Print query result to the console */ class func put(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) { //Allocate an AFHTTP Request object var manager = AFHTTPRequestOperationManager(); manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token") //Query using the PUT method. If successful, pass the JSON object to the callback function manager.PUT( url, parameters: parameters, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in if verbose { println("JSON: " + responseObject.description) } //Build a SwiftyJSON object from the JSON object let jsonResponse = JSON(responseObject) //Invoke the callback method callback(jsonResponse) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error ("+url+"): " + error.localizedDescription) }) } /* HTTP POST request. Returns JSON as a SwiftyJSON object url (String): URL of the data resource parameters (NSDictionary): POST parameters callback (JSON): Callback method to update local data source (Requires SwiftyJSON) verbose (boolean): Print query result to the console */ class func post(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) { //Allocate an AFHTTP Request object var manager = AFHTTPRequestOperationManager(); manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token") //Query using the POST method. If successful, pass the JSON object to the callback function manager.POST( url, parameters: parameters, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in if verbose { println("JSON: " + responseObject.description) } //Build a SwiftyJSON object from the JSON object let jsonResponse = JSON(responseObject) //Invoke the callback method callback(jsonResponse) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error ("+url+"): " + error.localizedDescription) }) } /* HTTP DELETE request. Returns JSON as a SwiftyJSON object url (String): URL of the data resource parameters (NSDictionary): POST parameters callback (JSON): Callback method to update local data source (Requires SwiftyJSON) verbose (boolean): Print query result to the console */ class func delete(url:String, parameters: NSDictionary, callback: (JSON) -> Void, verbose: Bool) { //Allocate an AFHTTP Request object var manager = AFHTTPRequestOperationManager(); manager.requestSerializer.setValue(STConnection.getTOTPCode(), forHTTPHeaderField: "X-Auth-Token") //Query using the DELETE method. If successful, pass the JSON object to the callback function manager.DELETE( url, parameters: parameters, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in if verbose { println("JSON: " + responseObject.description) } //Build a SwiftyJSON object from the JSON object let jsonResponse = JSON(responseObject) //Invoke the callback method callback(jsonResponse) }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in println("Error ("+url+"): " + error.localizedDescription) }) } }
62dc774261df383ba2b05782402cf3cd
34.847107
135
0.566686
false
false
false
false
mhergon/AVPlayerViewController-Subtitles
refs/heads/master
Example/Shared/ContentView.swift
apache-2.0
1
// // ContentView.swift // Shared // // Created by TungLim on 21/6/2022. // Copyright © 2022 Marc Hervera. All rights reserved. // import SwiftUI import AVKit import Combine struct ContentView: View { @State private var currentTime: TimeInterval = 0 @State private var currentText = "" private let timeObserver: PlayerTimeObserver private let avplayer: AVPlayer private let parser: Subtitles? init() { avplayer = AVPlayer(url: Bundle.main.url(forResource: "trailer_720p", withExtension: "mov")!) parser = try? Subtitles(file: URL(fileURLWithPath: Bundle.main.path(forResource: "trailer_720p", ofType: "srt")!), encoding: .utf8) timeObserver = PlayerTimeObserver(player: avplayer) } var body: some View { VideoPlayer(player: avplayer) { VStack { Spacer() Text(currentText) .foregroundColor(.white) .font(.subheadline) .multilineTextAlignment(.center) .padding() .onReceive(timeObserver.publisher) { time in currentText = parser?.searchSubtitles(at: time) ?? "" } } .frame(maxWidth: .infinity, maxHeight: .infinity) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } class PlayerTimeObserver { let publisher = PassthroughSubject<TimeInterval, Never>() private var timeObservation: Any? init(player: AVPlayer) { // Periodically observe the player's current time, whilst playing timeObservation = player.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 60), queue: nil) { [weak self] time in guard let self = self else { return } // Publish the new player time self.publisher.send(time.seconds) } } }
b898ed206a68d658c5fbe52342accf14
28.424242
139
0.6138
false
false
false
false
radhakrishnapai/Gallery-App-Swift
refs/heads/master
Gallery App Swift/Gallery App Swift/CollectionListTableViewController.swift
mit
1
// // CollectionListTableViewController.swift // Gallery App Swift // // Created by Pai on 21/03/16. // Copyright © 2016 Pai. All rights reserved. // import UIKit import Photos class CollectionListTableViewController : UITableViewController { var albumFetchResult:PHFetchResult = PHFetchResult() override func viewDidLoad() { self.albumFetchResult = PHAssetCollection.fetchAssetCollectionsWithType(PHAssetCollectionType.Album, subtype: PHAssetCollectionSubtype.AlbumRegular, options: nil) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.albumFetchResult.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:AlbumListCell = tableView.dequeueReusableCellWithIdentifier("AlbumListCell", forIndexPath: indexPath) as! AlbumListCell let collection:PHAssetCollection = self.albumFetchResult[indexPath.row] as! PHAssetCollection cell.albumTitle.text = collection.localizedTitle cell.albumCount.text = "\(collection.estimatedAssetCount)" return cell } }
a4440ff81297ede471b096963669f650
32.125
170
0.727547
false
false
false
false
adis300/Swift-Learn
refs/heads/master
SwiftLearn/Source/Random.swift
apache-2.0
1
// // Random.swift // Swift-Learn // // Created by Innovation on 11/12/16. // Copyright © 2016 Votebin. All rights reserved. // import Foundation class Random{ static func randMinus1To1(length: Int) -> [Double]{ return (0..<length).map{_ in Double(arc4random())/Double(INT32_MAX) - 1} } static func randMinus1To1() -> Double{ return Double(arc4random())/Double(INT32_MAX) - 1 } static func randN(n:Int) -> Int{ return Int(arc4random_uniform(UInt32(n))) } static func rand0To1() -> Double{ return Double(arc4random()) / Double(UINT32_MAX) } static var y2 = 0.0 static var use_last = false /// static Function to get a random value for a given distribution // static func gaussianRandom(_ mean : Double, standardDeviation : Double) -> Double static func normalRandom() -> Double { var y1 : Double if (use_last) /* use value from previous call */ { y1 = y2 use_last = false } else { var w = 1.0 var x1 = 0.0 var x2 = 0.0 repeat { x1 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 x2 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 w = x1 * x1 + x2 * x2 } while ( w >= 1.0 ) w = sqrt( (-2.0 * log( w ) ) / w ) y1 = x1 * w y2 = x2 * w use_last = true } return( y1 * 1 ) } /* static func normalDistribution(μ:Double, σ:Double, x:Double) -> Double { let a = exp( -1 * pow(x-μ, 2) / ( 2 * pow(σ,2) ) ) let b = σ * sqrt( 2 * M_PI ) return a / b } static func standardNormalDistribution(_ x:Double) -> Double { return exp( -1 * pow(x, 2) / 2 ) / sqrt( 2 * M_PI ) }*/ }
b139ccb535fb0d6730359d80ac5f3c15
25.093333
88
0.485437
false
false
false
false
themungapp/themungapp
refs/heads/master
Mung/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // Mung // // Created by Chike Chiejine on 30/09/2016. // Copyright © 2016 Color & Space. All rights reserved. // import UIKit import MXParallaxHeader class ViewController: UIViewController, SimpleTabsDelegate { //Tab View // @IBOutlet weak var containerView: UIView! // @IBOutlet weak var profileImage: UIImageView! // // // // // // @IBOutlet weak var discoverFeed: UIView! // @IBOutlet weak var newFeed: UIView! // @IBOutlet weak var anotherFeed: UIView! var scrollView: MXScrollView! var vc:SimpleTabsViewController! var containerView = UIView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var frame = view.frame let customview = Bundle.main.loadNibNamed("customView", owner: nil, options: nil)![0] as! customView let tabContainerView = customview.tabContainerView print("CUSTOM CORNER RADIUS") print(customview.cornerRadius) customview.cornerRadius = 20 scrollView = MXScrollView() scrollView.parallaxHeader.view = Bundle.main.loadNibNamed("customView", owner: nil, options: nil)![0] as! customView scrollView.parallaxHeader.height = 300 scrollView.parallaxHeader.mode = MXParallaxHeaderMode.fill scrollView.parallaxHeader.minimumHeight = 10 view.addSubview(scrollView) containerView.translatesAutoresizingMaskIntoConstraints = false containerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: frame.size.height - 8) containerView.backgroundColor = UIColor.white view.addSubview(containerView) let controller = storyboard?.instantiateViewController(withIdentifier: "ViewController1") addChildViewController(controller!) controller?.view.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview((controller?.view)!) controller?.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: frame.size.height - 8) scrollView.addSubview(containerView) let scrollHeight = frame.size.height let scrollWidth = frame.size.width // NSLayoutConstraint.activate([ // containerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: scrollWidth), // containerView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: scrollHeight), // containerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10), // containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0), // ]) controller?.didMove(toParentViewController: self) //Tabs Confiigure let tab1 = SimpleTabItem(title:"DISCOVER", count: 3) let tab2 = SimpleTabItem(title:"NEWS FEED", count: 2) let tab3 = SimpleTabItem(title:"ANOTHER FEED", count: 0) vc = SimpleTabsViewController.create(self, baseView: tabContainerView, delegate: self, items: [tab1,tab2,tab3]) vc.setTabTitleColor(UIColor(red:0.54, green:0.54, blue:0.54, alpha:1.0)) vc.setNumberColor(UIColor.black) vc.setNumberBackgroundColor(UIColor.yellow) vc.setMarkerColor(UIColor(red:0.01, green:0.68, blue:0.88, alpha:1.0)) vc.setTabTitleFont(UIFont.systemFont(ofSize: 10)) vc.setNumberFont(UIFont.systemFont(ofSize: 14)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var frame = view.frame scrollView.frame = frame scrollView.contentSize.height = frame.size.height + 20 scrollView.contentSize.width = frame.size.width // frame.size.height -= scrollView.parallaxHeader.minimumHeight scrollView.frame = frame // // // let bottomConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) // let horizConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) // let widthConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: scrollWidth) // let heightConstraint = NSLayoutConstraint(item: containerView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: scrollHeight) // // NSLayoutConstraint.activate([bottomConstraint, horizConstraint, widthConstraint, heightConstraint]) // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK : - SimpleTabsDelegate func tabSelected(_ tabIndex:Int){ // if tabIndex == 0 { // // UIView.animate(withDuration: 0.5, animations: { // // // self.discoverFeed.alpha = 1 // self.newFeed.alpha = 0 // self.anotherFeed.alpha = 0 // // }) // } else if tabIndex == 1 { // // UIView.animate(withDuration: 0.5, animations: { // // self.discoverFeed.alpha = 0 // self.newFeed.alpha = 1 // self.anotherFeed.alpha = 0 // // }) // // } else { // // UIView.animate(withDuration: 0.5, animations: { // // self.discoverFeed.alpha = 0 // self.newFeed.alpha = 0 // self.anotherFeed.alpha = 1 // // }) // // } // var indexInfo = "Index selected: \(tabIndex)" print(indexInfo) } }
f37ad3898d147b33c3a15f117a4a5214
33.795699
241
0.617429
false
false
false
false
smockle/TorToggle
refs/heads/master
TorToggle/AppDelegate.swift
isc
1
// // AppDelegate.swift // TorToggle // // Created by Clay Miller on 4/3/15. // Copyright (c) 2015 Clay Miller. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var statusMenu: NSMenu! let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) func updateStatusMenuState() { let isDisabled = SOCKSIsDisabled(); /* Show disabled icon variant if the SOCKS proxy is disabled */ statusItem.button?.appearsDisabled = isDisabled /* Modify menu item text if the SOCKS proxy is disabled */ if (isDisabled) { (statusMenu.itemArray[0] as! NSMenuItem).title = "Enable Tor" } else { (statusMenu.itemArray[0] as! NSMenuItem).title = "Disable Tor" } } func applicationDidFinishLaunching(aNotification: NSNotification) { let icon = NSImage(named: "statusIcon") icon?.setTemplate(true) statusItem.image = icon statusItem.menu = statusMenu updateStatusMenuState() } func SOCKSIsDisabled() -> Bool { /* Check whether Tor is already enabled */ let task = NSTask() let pipe = NSPipe() task.launchPath = "/usr/sbin/networksetup" task.arguments = ["-getsocksfirewallproxy", "Wi-Fi"] task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let string = NSString(data: data, encoding: NSUTF8StringEncoding) as! String let array = string.componentsSeparatedByString("\n").filter { ($0 as NSString).containsString("Enabled:") && !($0 as NSString).containsString(" Enabled:") } return array[0].lowercaseString == "enabled: no" } /* Toggle Tor launchctl */ func toggleTor(command: String) { let task = NSTask() task.launchPath = "/bin/launchctl" task.arguments = [command, "/usr/local/opt/tor/homebrew.mxcl.tor.plist"] task.launch() task.waitUntilExit() } /* Toggle SOCKS proxy */ func toggleSOCKS(command: String) { let task = NSTask() task.launchPath = "/usr/sbin/networksetup" task.arguments = ["-setsocksfirewallproxystate", "Wi-Fi", command] task.launch() task.waitUntilExit() } @IBAction func menuClicked(sender: NSMenuItem) { if (sender.title == "Disable Tor") { toggleSOCKS("off") if (SOCKSIsDisabled()) { toggleTor("unload") } } else { toggleSOCKS("on") if (!SOCKSIsDisabled()) { toggleTor("load") } } updateStatusMenuState() } @IBAction func terminateApplication(sender: AnyObject) { if (!SOCKSIsDisabled()) { toggleSOCKS("off") if (SOCKSIsDisabled()) { toggleTor("unload") } } NSApplication.sharedApplication().terminate(self) } }
69eab61f8b9ef5b5f45a79924c221712
29.911765
164
0.587377
false
false
false
false
jrmgx/swift
refs/heads/master
jrmgx/Classes/Extension/UIImage.swift
mit
1
import UIKit public extension UIImage { /** * NAME * * - parameters * - name: String * - returns: nothing */ public func jrmgx_writeJPEGToFile(_ filePath: URL, quality: CGFloat = 0.7) { try? UIImageJPEGRepresentation(self, quality)?.write(to: filePath, options: [.atomic]) } /** * NAME * * - parameters * - name: String * - returns: nothing */ public func jrmgx_CropToSquare() -> UIImage { let imageSize = size let width = imageSize.width let height = imageSize.height guard width != height else { return self } let newDimension = min(width, height) let widthOffset = (width - newDimension) / 2 let heightOffset = (height - newDimension) / 2 UIGraphicsBeginImageContextWithOptions(CGSize(width: newDimension, height: newDimension), false, 0) draw(at: CGPoint(x: -widthOffset, y: -heightOffset), blendMode: CGBlendMode.copy, alpha: 1.0) let destImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return destImage! } /** * NAME * * - parameters * - name: String * - returns: nothing */ public func jrmgx_resize(_ to: CGSize) -> UIImage { let imageSize = size let ratio = imageSize.width / imageSize.height var scale: CGFloat = 1 if ratio > 0 { scale = to.height / imageSize.height } else { scale = to.width / imageSize.width } let finalSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale) UIGraphicsBeginImageContextWithOptions(finalSize, false, 0) draw(in: CGRect(origin: CGPoint.zero, size: finalSize)) let destImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return destImage! } /** * NAME * * - parameters * - name: String * - returns: nothing */ public static func Jrmgx_ImageWithColor(_ color: UIColor) -> UIImage { return UIImage.Jrmgx_ImageWithColor(color, andSize: CGRect(x: 0, y: 0, width: 1, height: 1)) } /** * NAME * * - parameters * - name: String * - returns: nothing */ public static func Jrmgx_ImageWithColor(_ color: UIColor, andSize rect: CGRect) -> UIImage { UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
82c7df8dc41789a85892ca40bf8c8d1a
25.883495
107
0.591188
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/E2EE/APSSignalingKeysStore.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 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/. // import UIKit import WireTransport import WireUtilities public struct SignalingKeys { let verificationKey: Data let decryptionKey: Data init(verificationKey: Data? = nil, decryptionKey: Data? = nil) { self.verificationKey = verificationKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes) self.decryptionKey = decryptionKey ?? NSData.secureRandomData(ofLength: APSSignalingKeysStore.defaultKeyLengthBytes) } } @objcMembers public final class APSSignalingKeysStore: NSObject { public var apsDecoder: ZMAPSMessageDecoder! internal var verificationKey: Data! internal var decryptionKey: Data! internal static let verificationKeyAccountName = "APSVerificationKey" internal static let decryptionKeyAccountName = "APSDecryptionKey" internal static let defaultKeyLengthBytes: UInt = 256 / 8 public init?(userClient: UserClient) { super.init() if let verificationKey = userClient.apsVerificationKey, let decryptionKey = userClient.apsDecryptionKey { self.verificationKey = verificationKey self.decryptionKey = decryptionKey self.apsDecoder = ZMAPSMessageDecoder(encryptionKey: decryptionKey, macKey: verificationKey) } else { return nil } } /// use this method to create new keys, e.g. for client registration or update static func createKeys() -> SignalingKeys { return SignalingKeys() } /// we previously stored keys in the key chain. use this method to retreive the previously stored values to move them into the selfClient static func keysStoredInKeyChain() -> SignalingKeys? { guard let verificationKey = ZMKeychain.data(forAccount: self.verificationKeyAccountName), let decryptionKey = ZMKeychain.data(forAccount: self.decryptionKeyAccountName) else { return nil } return SignalingKeys(verificationKey: verificationKey, decryptionKey: decryptionKey) } static func clearSignalingKeysInKeyChain() { ZMKeychain.deleteAllKeychainItems(withAccountName: self.verificationKeyAccountName) ZMKeychain.deleteAllKeychainItems(withAccountName: self.decryptionKeyAccountName) } public func decryptDataDictionary(_ payload: [AnyHashable: Any]!) -> [AnyHashable: Any]! { return self.apsDecoder.decodeAPSPayload(payload) } }
0ddfd1629469c46c5a16e2eab7b0d901
39.868421
141
0.735673
false
false
false
false
YoungGary/30daysSwiftDemo
refs/heads/master
day28/day28/ViewController.swift
mit
1
// // ViewController.swift // day28 // // Created by YOUNG on 2016/10/18. // Copyright © 2016年 Young. All rights reserved. // import UIKit import CoreSpotlight import MobileCoreServices class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{ @IBOutlet weak var tableView: UITableView! var datas :NSMutableArray! var selectedIndex : Int = 0 override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0) loadDatas() setupSearchableContent() let nib = UINib(nibName: "TableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: "cell") } func loadDatas(){ let path = NSBundle.mainBundle().pathForResource("MoviesData.plist", ofType: nil) datas = NSMutableArray(contentsOfFile: path!) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell let currentMovieInfo = datas[indexPath.row] as! [String: String] cell.titleLabel.text = currentMovieInfo["Title"]! cell.iconImageView.image = UIImage(named: currentMovieInfo["Image"]!) cell.descLabel.text = currentMovieInfo["Description"]! cell.pointLabel.text = currentMovieInfo["Rating"]! return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100.0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedIndex = indexPath.row performSegueWithIdentifier("tableView2ViewController", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier else{ return } if identifier == "tableView2ViewController"{ let pushVC = segue.destinationViewController as! PushViewController pushVC.movieDict = datas[selectedIndex] as! [String: String] } } func setupSearchableContent() { var searchableItems = [CSSearchableItem]() for i in 0...(datas.count - 1) { let movie = datas[i] as! [String: String] let searchableItemAttributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String) //set the title searchableItemAttributeSet.title = movie["Title"]! //set the image let imagePathParts = movie["Image"]!.componentsSeparatedByString(".") searchableItemAttributeSet.thumbnailURL = NSBundle.mainBundle().URLForResource(imagePathParts[0], withExtension: imagePathParts[1]) // Set the description. searchableItemAttributeSet.contentDescription = movie["Description"]! var keywords = [String]() let movieCategories = movie["Category"]!.componentsSeparatedByString(", ") for movieCategory in movieCategories { keywords.append(movieCategory) } let stars = movie["Stars"]!.componentsSeparatedByString(", ") for star in stars { keywords.append(star) } searchableItemAttributeSet.keywords = keywords let searchableItem = CSSearchableItem(uniqueIdentifier: "com.appcoda.SpotIt.\(i)", domainIdentifier: "movies", attributeSet: searchableItemAttributeSet) searchableItems.append(searchableItem) CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems) { (error) -> Void in if error != nil { print(error?.localizedDescription) } } } } override func restoreUserActivityState(activity: NSUserActivity) { if activity.activityType == CSSearchableItemActionType { if let userInfo = activity.userInfo { let selectedMovie = userInfo[CSSearchableItemActivityIdentifier] as! String selectedIndex = Int(selectedMovie.componentsSeparatedByString(".").last!)! performSegueWithIdentifier("tableView2ViewController", sender: self) } } } }
3252e09e6441ade50c3fa01842992e7c
30.54902
164
0.624819
false
false
false
false
breadwallet/breadwallet-core
refs/heads/develop
Swift/BRCrypto/BRCryptoUnit.swift
mit
1
// // BRCryptoUnit.swift // BRCrypto // // Created by Ed Gamble on 3/27/19. // Copyright © 2019 Breadwallet AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import BRCryptoC /// /// A unit of measure for a currency. There can be multiple units for a given currency (analogous /// to 'System International' units of (meters, kilometers, miles, ...) for a dimension of /// 'length'). For example, Ethereum has units of: WEI, GWEI, ETHER, METHER, ... and Bitcoin of: /// BTC, SATOSHI, ... /// /// Each Currency has a 'baseUnit' - which is defined as the 'integer-ish' unit - such as SATOSHI /// ane WEI for Bitcoin and Ethereum, respectively. There can be multiple 'derivedUnits' - which /// are derived by scaling off of a baseUnit. For example, BTC and ETHER respectively. /// public final class Unit: Hashable { internal let core: BRCryptoUnit public var currency: Currency { return Currency (core: cryptoUnitGetCurrency(core), take: false) } internal var uids: String { return asUTF8String (cryptoUnitGetUids (core)) } public var name: String { return asUTF8String (cryptoUnitGetName (core)) } public var symbol: String { return asUTF8String (cryptoUnitGetSymbol (core)) } public var base: Unit { return Unit (core: cryptoUnitGetBaseUnit (core), take: false) } public var decimals: UInt8 { return cryptoUnitGetBaseDecimalOffset (core) } public func isCompatible (with that: Unit) -> Bool { return CRYPTO_TRUE == cryptoUnitIsCompatible (self.core, that.core) } public func hasCurrency (_ currency: Currency) -> Bool { return CRYPTO_TRUE == cryptoUnitHasCurrency (core, currency.core); } internal init (core: BRCryptoUnit, take: Bool) { self.core = take ? cryptoUnitTake(core) : core } internal convenience init (core: BRCryptoUnit) { self.init (core: core, take: true) } internal convenience init (currency: Currency, code: String, name: String, symbol: String) { self.init (core: cryptoUnitCreateAsBase (currency.core, code, name, symbol), take: false) } internal convenience init (currency: Currency, code: String, name: String, symbol: String, base: Unit, decimals: UInt8) { self.init (core: cryptoUnitCreate (currency.core, code, name, symbol, base.core, decimals), take: false) } deinit { cryptoUnitGive (core) } public static func == (lhs: Unit, rhs: Unit) -> Bool { return lhs === rhs || CRYPTO_TRUE == cryptoUnitIsIdentical (lhs.core, rhs.core) } public func hash (into hasher: inout Hasher) { hasher.combine (uids) } }
02b64260d5a3e5bc66d7c617cdd8743c
31.614583
99
0.600447
false
false
false
false
davidahouse/chute
refs/heads/master
chute/Output/DifferenceReport/DifferenceReportDetailViews.swift
mit
1
// // DifferenceReportDetailViews.swift // chute // // Created by David House on 11/16/17. // Copyright © 2017 David House. All rights reserved. // import Foundation struct DifferenceReportDetailViews: ChuteOutputDifferenceRenderable { enum Constants { static let Template = """ <style> .gallery { -webkit-column-count: 3; /* Chrome, Safari, Opera */ -moz-column-count: 3; /* Firefox */ column-count: 3; } .gallery img{ width: 100%; padding: 7px 0; margin-bottom: 7px; } @media (max-width: 500px) { .gallery { -webkit-column-count: 1; /* Chrome, Safari, Opera */ -moz-column-count: 1; /* Firefox */ column-count: 1; } } .gallery-image { border: 1px solid lightgray; margin-bottom: 17px; border-radius: 5px; width: 100%; height: auto; display: inline-block; } .gallery-image > h5 { color: #777; padding: 7px 5px 0px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-bottom: 1px solid lightgray; } .compare-gallery { -webkit-column-count: 2; /* Chrome, Safari, Opera */ -moz-column-count: 2; /* Firefox */ column-count: 2; } .compare-gallery img{ width: 100%; padding: 7px 0; margin-bottom: 7px; } </style> <div class="jumbotron"> <h1>View Difference Details</h1> <h3>New Views:</h3> <div class="gallery"> {{new_views}} </div> <h3>Changed Views:</h3> {{changed_views}} </div> """ static let TestAttachmentTemplate = """ <div class="gallery-image"> <h5>{{attachment_name}}</h5> <img src="attachments/{{attachment_file_name}}" alt="{{attachment_name}}"> </div> """ static let TestCompareAttachmentTemplate = """ <div class="compare-gallery"> <div class="gallery-image"> <h5>BEFORE {{attachment_name}}</h5> <img src="attachments/{{before_attachment_file_name}}" alt="{{attachment_name}}"> </div> <div class="gallery-image"> <h5>AFTER {{attachment_name}}</h5> <img src="attachments/{{attachment_file_name}}" alt="{{attachment_name}}"> </div> </div> """ } func render(difference: DataCaptureDifference) -> String { let parameters: [String: CustomStringConvertible] = [ "new_views": newViews(difference: difference), "changed_views": changedViews(difference: difference) ] return Constants.Template.render(parameters: parameters) } private func newViews(difference: DataCaptureDifference) -> String { var views = "" for attachment in difference.viewDifference.newViews.sortedByName() { let attachmentParameters: [String: CustomStringConvertible] = [ "attachment_name": attachment.attachmentName, "attachment_file_name": attachment.attachmentFileName ] views += Constants.TestAttachmentTemplate.render(parameters: attachmentParameters) } return views } private func changedViews(difference: DataCaptureDifference) -> String { var views = "" for (attachment, beforeAttachment) in difference.viewDifference.changedViews { let attachmentParameters: [String: CustomStringConvertible] = [ "attachment_name": attachment.attachmentName, "before_attachment_file_name": "before_" + beforeAttachment.attachmentFileName, "attachment_file_name": attachment.attachmentFileName ] views += Constants.TestCompareAttachmentTemplate.render(parameters: attachmentParameters) } return views } }
1d0808d2c56ae9a80c0faedc17c0ad41
35.264463
101
0.518915
false
false
false
false
gobetti/Swift
refs/heads/master
NSBlockOperation/NSBlockOperation/ViewController.swift
mit
1
// // ViewController.swift // NSBlockOperation // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2014 Carlos Butron. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { let queue = NSOperationQueue() let operation1 : NSBlockOperation = NSBlockOperation ( block: { self.getWebs() let operation2 : NSBlockOperation = NSBlockOperation(block: { self.loadWebs() }) queue.addOperation(operation2) }) queue.addOperation(operation1) super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadWebs(){ let urls : NSMutableArray = NSMutableArray (objects:NSURL(string:"http://www.google.es")!, NSURL(string: "http://www.apple.com")!,NSURL(string: "http://carlosbutron.es")!, NSURL(string: "http://www.bing.com")!,NSURL(string: "http://www.yahoo.com")!) urls.addObjectsFromArray(googlewebs as [AnyObject]) for iterator:AnyObject in urls{ /// NSData(contentsOfURL:iterator as! NSURL) print("Downloaded \(iterator)") } } var googlewebs:NSArray = [] func getWebs(){ let languages:NSArray = ["com","ad","ae","com.af","com.ag","com.ai","am","co.ao","com.ar","as","at"] let languageWebs = NSMutableArray() for(var i=0;i < languages.count; i++){ let webString: NSString = "http://www.google.\(languages[i])" languageWebs.addObject(NSURL(fileURLWithPath: webString as String)) } googlewebs = languageWebs } }
e5e172c91b6cfbb42e97c299faa9d8ed
26.470588
257
0.56424
false
false
false
false
AirHelp/Mimus
refs/heads/master
Sources/Mimus/Verification/VerificationHandler.swift
mit
1
// // Copyright (©) 2017 AirHelp. All rights reserved. // import XCTest internal class VerificationHandler { private let mismatchMessageBuilder = MismatchMessageBuilder() static var shared: VerificationHandler = VerificationHandler() func verifyCall(callIdentifier: String, matchedResults: [MimusComparator.ComparisonResult], mismatchedArgumentsResults: [MimusComparator.ComparisonResult], mode: VerificationMode, testLocation: TestLocation) { switch mode { case .never: assertNever(callIdentifier: callIdentifier, matchCount: matchedResults.count, differentArgumentsMatchCount: mismatchedArgumentsResults.count, testLocation: testLocation) case .atLeast(let count): assertAtLeast(callIdentifier: callIdentifier, times: count, matchCount: matchedResults.count, differentArgumentsMatch: mismatchedArgumentsResults, testLocation: testLocation) case .atMost(let count): assertAtMost(callIdentifier: callIdentifier, times: count, matchCount: matchedResults.count, differentArgumentsMatchCount: mismatchedArgumentsResults.count, testLocation: testLocation) case .times(let count): assert(callIdentifier: callIdentifier, times: count, matchCount: matchedResults.count, differentArgumentsMatch: mismatchedArgumentsResults, testLocation: testLocation) } } // MARK: Actual assertions private func assertNever(callIdentifier: String, matchCount: Int, differentArgumentsMatchCount: Int, testLocation: TestLocation) { guard matchCount > 0 else { return } XCTFail("Expected to not receive call with identifier \(callIdentifier)", file: testLocation.file, line: testLocation.line) } private func assertAtMost(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatchCount: Int, testLocation: TestLocation) { guard matchCount > times else { return } var message = "No call with identifier \(callIdentifier) was captured" if matchCount > 0 { message = "Call with identifier \(callIdentifier) was recorded \(matchCount) times, but expected at most \(times)" } XCTFail(message, file: testLocation.file, line: testLocation.line) } private func assertAtLeast(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatch: [MimusComparator.ComparisonResult], testLocation: TestLocation) { guard matchCount < times else { return } let differentArgumentsMatchCount = differentArgumentsMatch.count var message = "No call with identifier \(callIdentifier) was captured" if matchCount > 0 { let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch) message = """ Call with identifier \(callIdentifier) was recorded \(matchCount) times, but expected at least \(times). \(differentArgumentsMatchCount) additional call(s) matched identifier, but not arguments:\n\n\(mismatchedResultsMessage) """ } else if differentArgumentsMatchCount > 0 { let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch) message = """ Call with identifier \(callIdentifier) was recorded \(differentArgumentsMatchCount) times, but arguments didn't match.\n\(mismatchedResultsMessage) """ } XCTFail(message, file: testLocation.file, line: testLocation.line) } private func assert(callIdentifier: String, times: Int, matchCount: Int, differentArgumentsMatch: [MimusComparator.ComparisonResult], testLocation: TestLocation) { guard matchCount != times else { return } let differentArgumentsMatchCount = differentArgumentsMatch.count var message = "No call with identifier \(callIdentifier) was captured" if matchCount > 0 { let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch) message = """ Call with identifier was recorded \(matchCount) times, but expected \(times). \(differentArgumentsMatchCount) additional call(s) matched identifier, but not arguments:\n\n\(mismatchedResultsMessage) """ } else if differentArgumentsMatchCount > 0 { let mismatchedResultsMessage = mismatchMessageBuilder.message(for: differentArgumentsMatch) message = """ Call with identifier \(callIdentifier) was recorded \(differentArgumentsMatchCount) times, but arguments didn't match.\n\(mismatchedResultsMessage) """ } XCTFail(message, file: testLocation.file, line: testLocation.line) } }
473026e1be49b40e2578a4d3ded380dd
46.178571
213
0.640045
false
true
false
false
aolan/Cattle
refs/heads/master
CattleKit/CAProgressWidget.swift
mit
1
// // CAProgressWidget.swift // cattle // // Created by lawn on 15/11/5. // Copyright © 2015年 zodiac. All rights reserved. // import UIKit public class CAProgressWidget: UIView { // MARK: - Property /// 单例 static let sharedInstance = CAProgressWidget() /// 黑色背景圆角 static let blackViewRadius: CGFloat = 10.0 /// 黑色背景透明度 static let blackViewAlpha: CGFloat = 0.8 /// 黑色背景边长 let blackViewWH: CGFloat = 100.0 /// 标签高度 let labelHeight: CGFloat = 15.0 /// 间距 let margin: CGFloat = 10.0 /// 控件显示的最长时间 let timeout: Double = 20.0 /// 提示信息展示时间 let shortTimeout: Double = 2.0 /// 动画时间,秒为单位 let animateTime: Double = 0.2 lazy var label: UILabel? = { var tmpLbl = UILabel() tmpLbl.textColor = UIColor.whiteColor() tmpLbl.textAlignment = NSTextAlignment.Center tmpLbl.font = UIFont.systemFontOfSize(12) return tmpLbl }() lazy var detailLabel: UILabel? = { var tmpLbl = UILabel() tmpLbl.textColor = UIColor.whiteColor() tmpLbl.textAlignment = NSTextAlignment.Center tmpLbl.font = UIFont.systemFontOfSize(12) return tmpLbl }() lazy var blackView: UIView? = { var tmpView = UIView() tmpView.backgroundColor = UIColor.blackColor() tmpView.layer.cornerRadius = blackViewRadius tmpView.layer.masksToBounds = true tmpView.alpha = blackViewAlpha return tmpView }() var progressView: UIActivityIndicatorView? = { var tmpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge) return tmpView }() // MARK: - Private Methods func dismissLoading(animated:NSNumber, didDissmiss: () -> Void) -> Void{ if superview == nil { return } if animated.boolValue{ UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() didDissmiss() } }else{ removeAllSubViews() removeFromSuperview() didDissmiss() } } func dismissLoading(animated: NSNumber) -> Void{ NSObject.cancelPreviousPerformRequestsWithTarget(self) if superview == nil { return } if animated.boolValue { UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() } }else{ removeAllSubViews() removeFromSuperview() } } func showLoading(inView: UIView?, text: String?, detailText: String?) { //如果已经显示了,先隐藏 if superview != nil{ dismissLoading(NSNumber(bool: false)) } //设置黑色背景和菊花 if inView != nil && blackView != nil && progressView != nil{ alpha = 0 frame = inView!.bounds backgroundColor = UIColor.clearColor() inView?.addSubview(self) blackView?.ca_size(CGSize(width: blackViewWH, height: blackViewWH)) blackView?.ca_center(inView!.ca_center()) addSubview(blackView!) progressView?.ca_center(inView!.ca_center()) addSubview(progressView!) //设置标题 if text != nil && label != nil{ progressView?.ca_addY(-margin) addSubview(label!) label?.frame = CGRect(x: blackView!.ca_minX(), y: progressView!.ca_maxY() + margin, width: blackView!.ca_width(), height: labelHeight) label?.text = text //设置描述 if detailText != nil && detailLabel != nil{ progressView?.ca_addY(-margin) label?.ca_addY(-margin) addSubview(detailLabel!) detailLabel?.frame = CGRect(x: blackView!.ca_minX(), y: label!.ca_maxY() + margin/2.0, width: blackView!.ca_width(), height: labelHeight) detailLabel?.text = detailText } } //显示 UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 1.0 }, completion: { (finished) -> Void in self.progressView?.startAnimating() self.performSelector(Selector("dismissLoading:"), withObject: NSNumber(bool: true), afterDelay: self.timeout) }) } } func dismissMessage(animated: NSNumber) -> Void{ NSObject.cancelPreviousPerformRequestsWithTarget(self) if animated.boolValue{ UIView.animateWithDuration(animateTime, animations: { () -> Void in self.ca_addY(20.0) self.alpha = 0 }) { (isFininshed) -> Void in self.removeAllSubViews() self.removeFromSuperview() } }else{ removeAllSubViews() removeFromSuperview() } } func showMessage(inView: UIView?, text: String?) { //如果已经显示了,先隐藏 if superview != nil{ dismissMessage(NSNumber(bool: false)) } if inView != nil && text != nil && blackView != nil && label != nil{ alpha = 0 frame = inView!.bounds backgroundColor = UIColor.clearColor() inView?.addSubview(self) addSubview(blackView!) addSubview(label!) label?.text = text label?.numberOfLines = 2 let attributes = NSDictionary(object: label!.font, forKey: NSFontAttributeName) let size = label?.text?.boundingRectWithSize(CGSize(width: 200, height: 200), options: [.UsesLineFragmentOrigin, .UsesFontLeading], attributes: attributes as? [String : AnyObject], context: nil) label?.frame = CGRect(x: 0, y: 0, width: 200, height: (size?.height)! + 30) label?.ca_center(ca_center()) label?.ca_addY(-20.0) blackView!.frame = label!.frame //显示 UIView.animateWithDuration(animateTime, animations: { () -> Void in self.alpha = 1.0 self.label?.ca_addY(20.0) self.blackView!.frame = self.label!.frame }, completion: { (finished) -> Void in self.performSelector(Selector("dismissMessage:"), withObject: NSNumber(bool: true), afterDelay: self.shortTimeout) }) } } // MARK: - Class Methods /** 展示加载框 - parameter inView: 父视图 */ class func loading(inView: UIView?) -> Void { sharedInstance.showLoading(inView, text: nil, detailText: nil) } /** 展示带标题的加载框 - parameter superView: 父视图 - parameter text: 标题内容 */ class func loading(inView: UIView?, text:String?) -> Void { sharedInstance.showLoading(inView, text: text, detailText: nil) } /** 展示带标题和描述的加载框 - parameter superView: 父视图 - parameter text: 标题内容 - parameter detailText: 描述内容 */ class func loading(inView: UIView?, text: String?, detailText: String?) -> Void{ sharedInstance.showLoading(inView, text: text, detailText: detailText) } /** 消息提示【几秒钟自动消失】 - parameter text: 提示信息 */ class func message(text:String?) -> Void{ let window: UIWindow? = UIApplication.sharedApplication().keyWindow sharedInstance.showMessage(window, text: text) } /** 隐藏加载框 */ class func dismiss(didDissmiss: () -> Void) -> Void { sharedInstance.dismissLoading(NSNumber(bool: true), didDissmiss: didDissmiss) } }
3d353cb468d0c7e1ffe538eb1e57ded9
29.907407
206
0.533853
false
false
false
false
tgu/HAP
refs/heads/master
Sources/HAP/Controllers/PairSetupController.swift
mit
1
import func Evergreen.getLogger import Foundation import HKDF import SRP fileprivate let logger = getLogger("hap.controllers.pair-setup") class PairSetupController { struct Session { let server: SRP.Server } enum Error: Swift.Error { case invalidParameters case invalidPairingMethod case couldNotDecryptMessage case couldNotDecodeMessage case couldNotSign case couldNotEncrypt case alreadyPaired case alreadyPairing case invalidSetupState case authenticationFailed } let device: Device public init(device: Device) { self.device = device } func startRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 { guard let method = data[.pairingMethod]?.first.flatMap({ PairingMethod(rawValue: $0) }) else { throw Error.invalidParameters } // TODO: according to spec, this should be `method == .pairSetup` guard method == .default else { throw Error.invalidPairingMethod } // If the accessory is already paired it must respond with // Error_Unavailable if device.pairingState == .paired { throw Error.alreadyPaired } // If the accessory has received more than 100 unsuccessful // authentication attempts it must respond with // Error_MaxTries // TODO // If the accessory is currently performing a Pair Setup operation with // a different controller it must respond with // Error_Busy if device.pairingState == .pairing { throw Error.alreadyPairing } // Notify listeners of the pairing event and record the paring state // swiftlint:disable:next force_try try! device.changePairingState(.pairing) let (salt, serverPublicKey) = session.server.getChallenge() logger.info("Pair setup started") logger.debug("<-- s \(salt.hex)") logger.debug("<-- B \(serverPublicKey.hex)") let result: PairTagTLV8 = [ (.state, Data(bytes: [PairSetupStep.startResponse.rawValue])), (.publicKey, serverPublicKey), (.salt, salt) ] return result } func verifyRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8? { guard let clientPublicKey = data[.publicKey], let clientKeyProof = data[.proof] else { logger.warning("Invalid parameters") throw Error.invalidSetupState } logger.debug("--> A \(clientPublicKey.hex)") logger.debug("--> M \(clientKeyProof.hex)") guard let serverKeyProof = try? session.server.verifySession(publicKey: clientPublicKey, keyProof: clientKeyProof) else { logger.warning("Invalid PIN") throw Error.authenticationFailed } logger.debug("<-- HAMK \(serverKeyProof.hex)") let result: PairTagTLV8 = [ (.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])), (.proof, serverKeyProof) ] return result } func keyExchangeRequest(_ data: PairTagTLV8, _ session: Session) throws -> PairTagTLV8 { guard let encryptedData = data[.encryptedData] else { throw Error.invalidParameters } let encryptionKey = deriveKey(algorithm: .sha512, seed: session.server.sessionKey!, info: "Pair-Setup-Encrypt-Info".data(using: .utf8), salt: "Pair-Setup-Encrypt-Salt".data(using: .utf8), count: 32) guard let plaintext = try? ChaCha20Poly1305.decrypt(cipher: encryptedData, nonce: "PS-Msg05".data(using: .utf8)!, key: encryptionKey) else { throw Error.couldNotDecryptMessage } guard let data: PairTagTLV8 = try? decode(plaintext) else { throw Error.couldNotDecodeMessage } guard let publicKey = data[.publicKey], let username = data[.identifier], let signatureIn = data[.signature] else { throw Error.invalidParameters } logger.debug("--> identifier \(String(data: username, encoding: .utf8)!)") logger.debug("--> public key \(publicKey.hex)") logger.debug("--> signature \(signatureIn.hex)") let hashIn = deriveKey(algorithm: .sha512, seed: session.server.sessionKey!, info: "Pair-Setup-Controller-Sign-Info".data(using: .utf8), salt: "Pair-Setup-Controller-Sign-Salt".data(using: .utf8), count: 32) + username + publicKey try Ed25519.verify(publicKey: publicKey, message: hashIn, signature: signatureIn) let hashOut = deriveKey(algorithm: .sha512, seed: session.server.sessionKey!, info: "Pair-Setup-Accessory-Sign-Info".data(using: .utf8), salt: "Pair-Setup-Accessory-Sign-Salt".data(using: .utf8), count: 32) + device.identifier.data(using: .utf8)! + device.publicKey guard let signatureOut = try? Ed25519.sign(privateKey: device.privateKey, message: hashOut) else { throw Error.couldNotSign } let resultInner: PairTagTLV8 = [ (.identifier, device.identifier.data(using: .utf8)!), (.publicKey, device.publicKey), (.signature, signatureOut) ] logger.debug("<-- identifier \(self.device.identifier)") logger.debug("<-- public key \(self.device.publicKey.hex)") logger.debug("<-- signature \(signatureOut.hex)") logger.info("Pair setup completed") guard let encryptedResultInner = try? ChaCha20Poly1305.encrypt(message: encode(resultInner), nonce: "PS-Msg06".data(using: .utf8)!, key: encryptionKey) else { throw Error.couldNotEncrypt } // At this point, the pairing has completed. The first controller is granted admin role. device.add(pairing: Pairing(identifier: username, publicKey: publicKey, role: .admin)) let resultOuter: PairTagTLV8 = [ (.state, Data(bytes: [PairSetupStep.keyExchangeResponse.rawValue])), (.encryptedData, encryptedResultInner) ] return resultOuter } }
578f154ccc2cf81edc754393d99c2930
37.530387
109
0.55879
false
false
false
false
CodaFi/swift-compiler-crashes
refs/heads/master
crashes-duplicates/06369-resolvetypedecl.swift
mit
11
// 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 b<T where T, g = c struct c<T where T: d = g<T where T struct c<T where T.Element == c var b = c<T
ada04f8e12c4605b0832b5bc9b8e109d
33.125
87
0.717949
false
true
false
false
CUITCHE/code-obfuscation
refs/heads/master
Gen/Gen/gen.swift
mit
1
// // gen.swift // Gen // // Created by hejunqiu on 2017/8/28. // Copyright © 2017年 hejunqiu. All rights reserved. // import Foundation struct Gen { fileprivate var cache = EnumerateObjectiveClass() fileprivate var fileBuffer = NSMutableString.init() func gencode() { guard validation() else { print("Invalid!") return } gen() do { try fileBuffer.write(toFile: (NSTemporaryDirectory() as NSString).appendingPathComponent("GenMetaData.cpp"), atomically: true, encoding: String.Encoding.utf8.rawValue) print("Generate successfully! File at \(NSTemporaryDirectory())GenMetaData.cpp") exit(0) } catch { print(error) exit(-1) } } } fileprivate extension Gen { func validation() -> Bool { let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("output.data") guard NSKeyedArchiver.archiveRootObject(cache, toFile: path) else { print("Archiver Failed...") return false } if let data = NSData.init(contentsOfFile: path) { if let check = NSKeyedUnarchiver.unarchiveObject(with: data as Data) { return NSDictionary.init(dictionary: cache).isEqual(to: check as! [AnyHashable : Any]) } } return false } func writeln(_ content: String) { fileBuffer.append("\(content)\n") } func write_prepare() { writeln("///// For iOS SDK \(ProcessInfo.processInfo.operatingSystemVersionString)\n") writeln("#ifndef structs_h\n#define structs_h\n") writeln("struct __method__ {\n" + " const char *name;\n" + "};\n") writeln("struct __method__list {\n" + " unsigned int reserved;\n" + " unsigned int count;\n" + " struct __method__ methods[0];\n" + "};\n") writeln("struct __class__ {\n" + " struct __class__ *superclass;\n" + " const char *name;\n" + " const struct __method__list *method_list;\n" + "};\n") writeln("#ifndef CO_EXPORT") writeln("#define CO_EXPORT extern \"C\"") writeln("#endif") } func _write(clazzName: String, methodcount: Int, methoddesc: String) { writeln("") writeln("/// Meta data for \(clazzName)") writeln("") writeln("static struct /*__method__list_t*/ {") writeln(" unsigned int entsize;") writeln(" unsigned int method_count;") writeln(" struct __method__ method_list[\(methodcount == 0 ? 1 : methodcount)];") writeln("} _CO_METHODNAMES_\(clazzName)_$ __attribute__ ((used, section (\"__DATA,__co_const\"))) = {") writeln(" sizeof(__method__),") writeln(" \(methodcount),") writeln(" {\(methoddesc)}\n};") var super_class_t: String? = nil if let superClass = class_getSuperclass(NSClassFromString(clazzName)) { super_class_t = "_CO_CLASS_$_\(NSString.init(utf8String: class_getName(superClass)) ?? "")" writeln("\nCO_EXPORT struct __class__ \(super_class_t!);") } writeln("CO_EXPORT struct __class__ _CO_CLASS_$_\(clazzName) __attribute__ ((used, section (\"__DATA,__co_data\"))) = {") if super_class_t != nil { writeln(" &\(super_class_t!),") } else { writeln(" 0,") } writeln(" \"\(clazzName)\",") writeln(" (const struct __method__list *)&_CO_METHODNAMES_\(clazzName)_$\n};") } func write_tail() { writeln("\nCO_EXPORT struct __class__ *L_CO_LABEL_CLASS_$[\(cache.count)] __attribute__((used, section (\"__DATA, __co_classlist\"))) = {") for (key, _) in cache { writeln(" &_CO_CLASS_$_\(key),") } fileBuffer.deleteCharacters(in: NSMakeRange(fileBuffer.length - 2, 1)) writeln("};") writeln("\nCO_EXPORT struct /*__image_info*/ {\n" + " const char *version;\n" + " unsigned long size;\n" + "} _CO_CLASS_IMAGE_INFO_$ __attribute__ ((used, section (\"__DATA,__co_const\"))) = {\n" + " \"\(ProcessInfo.processInfo.operatingSystemVersionString)\",\n" + " \(cache.count)\n" + "};"); writeln("\n#endif"); } func gen() { write_prepare() for (key, obj) in cache { var methods = [String]() for m in obj { methods.append(m.method) } _write(clazzName: key, methodcount: obj.count, methoddesc: "{\"\(methods.joined(separator: "\"},{\""))\"}") } write_tail() } }
9bf795cd35dcb46b1f00834324faaa7f
35.074074
179
0.517659
false
false
false
false
MxABC/LBXAlertAction
refs/heads/master
TestSwiftAlertAction/ViewController.swift
mit
1
// // ViewController.swift // TestSwiftAlertAction // // Created by lbxia on 16/6/17. // Copyright © 2016年 lbx. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func testAlertView(_ sender: AnyObject) { // let alert = UIAlertView(title: "title", message: "message", delegate: nil, cancelButtonTitle: "cance", otherButtonTitles: "sure", "sure2") // // alert .show { (buttonIndex) in // // print(buttonIndex) // } let items = ["cancel","ok1","ok2"]; AlertAction.showAlert(title: "title", message: "message", btnStatements:items ) { (buttonIndex) in let items = ["cancel","ok1","ok2"]; print(buttonIndex) print(items[buttonIndex]) } } @IBAction func testSheetView(_ sender: AnyObject) { let destrucitve:String? = "destructive" // let destrucitve:String? = nil AlertAction.showSheet(title: "title", message: "ios8之后才会显示本条信息", destructiveButtonTitle: destrucitve,cancelButtonTitle: "cancel", otherButtonTitles: ["other1","other2"]) { (buttonIdx, itemTitle) in /* 经测试 buttonIdx: destructiveButtonTitle 为0, cancelButtonTitle 为1,otherButtonTitles按顺序增加 如果destructiveButtonTitle 传入值为nil,那么 cancelButtonTitle 为0,otherButtonTitles按顺序增加 或者按照itemTitle来判断用户点击那个按钮更稳妥 */ print(buttonIdx) print(itemTitle) } } func alertResult(_ buttonIndex:Int) -> Void { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7c1dc5328ba0c2eb933fb1c47d265b31
24.439024
206
0.555129
false
false
false
false
tidepool-org/nutshell-ios
refs/heads/develop
Nutshell/ViewControllers/EventListViewController.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 class EventListViewController: BaseUIViewController, ENSideMenuDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var searchTextField: NutshellUITextField! @IBOutlet weak var searchPlaceholderLabel: NutshellUILabel! @IBOutlet weak var tableView: NutshellUITableView! @IBOutlet weak var coverView: UIControl! fileprivate var sortedNutEvents = [(String, NutEvent)]() fileprivate var filteredNutEvents = [(String, NutEvent)]() fileprivate var filterString = "" override func viewDidLoad() { super.viewDidLoad() self.title = "All events" // 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() // Add a notification for when the database changes let moc = NutDataController.controller().mocForNutEvents() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(EventListViewController.databaseChanged(_:)), name: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: moc) notificationCenter.addObserver(self, selector: #selector(EventListViewController.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: nil) if let sideMenu = self.sideMenuController()?.sideMenu { sideMenu.delegate = self menuButton.target = self menuButton.action = #selector(EventListViewController.toggleSideMenu(_:)) let revealWidth = min(ceil((240.0/320.0) * self.view.bounds.width), 281.0) sideMenu.menuWidth = revealWidth sideMenu.bouncingEnabled = false } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } fileprivate var viewIsForeground: Bool = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewIsForeground = true configureSearchUI() if let sideMenu = self.sideMenuController()?.sideMenu { sideMenu.allowLeftSwipe = true sideMenu.allowRightSwipe = true sideMenu.allowPanGesture = true } if sortedNutEvents.isEmpty || eventListNeedsUpdate { eventListNeedsUpdate = false getNutEvents() } checkNotifyUserOfTestMode() // periodically check for authentication issues in case we need to force a new login let appDelegate = UIApplication.shared.delegate as? AppDelegate appDelegate?.checkConnection() APIConnector.connector().trackMetric("Viewed Home Screen (Home Screen)") } // each first time launch of app, let user know we are still in test mode! fileprivate func checkNotifyUserOfTestMode() { if AppDelegate.testMode && !AppDelegate.testModeNotification { AppDelegate.testModeNotification = true let alert = UIAlertController(title: "Test Mode", message: "Nutshell has Test Mode enabled!", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { Void in return })) alert.addAction(UIAlertAction(title: "Turn Off", style: .default, handler: { Void in AppDelegate.testMode = false })) self.present(alert, animated: true, completion: nil) } } deinit { NotificationCenter.default.removeObserver(self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) searchTextField.resignFirstResponder() viewIsForeground = false if let sideMenu = self.sideMenuController()?.sideMenu { //NSLog("swipe disabled") sideMenu.allowLeftSwipe = false sideMenu.allowRightSwipe = false sideMenu.allowPanGesture = false } } @IBAction func toggleSideMenu(_ sender: AnyObject) { APIConnector.connector().trackMetric("Clicked Hamburger (Home Screen)") toggleSideMenuView() } // // MARK: - ENSideMenu Delegate // fileprivate func configureForMenuOpen(_ open: Bool) { if open { if let sideMenuController = self.sideMenuController()?.sideMenu?.menuViewController as? MenuAccountSettingsViewController { // give sidebar a chance to update // TODO: this should really be in ENSideMenu! sideMenuController.menuWillOpen() } } tableView.isUserInteractionEnabled = !open self.navigationItem.rightBarButtonItem?.isEnabled = !open coverView.isHidden = !open } func sideMenuWillOpen() { //NSLog("EventList sideMenuWillOpen") configureForMenuOpen(true) } func sideMenuWillClose() { //NSLog("EventList sideMenuWillClose") configureForMenuOpen(false) } func sideMenuShouldOpenSideMenu() -> Bool { //NSLog("EventList sideMenuShouldOpenSideMenu") return true } func sideMenuDidClose() { //NSLog("EventList sideMenuDidClose") configureForMenuOpen(false) } func sideMenuDidOpen() { //NSLog("EventList sideMenuDidOpen") configureForMenuOpen(true) APIConnector.connector().trackMetric("Viewed Hamburger Menu (Hamburger)") } // // 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. super.prepare(for: segue, sender: sender) if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventGroupSegue { let cell = sender as! EventListTableViewCell let eventGroupVC = segue.destination as! EventGroupTableViewController eventGroupVC.eventGroup = cell.eventGroup! APIConnector.connector().trackMetric("Clicked a Meal (Home screen)") } else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue { let cell = sender as! EventListTableViewCell let eventDetailVC = segue.destination as! EventDetailViewController let group = cell.eventGroup! eventDetailVC.eventGroup = group eventDetailVC.eventItem = group.itemArray[0] APIConnector.connector().trackMetric("Clicked a Meal (Home screen)") } else if (segue.identifier) == EventViewStoryboard.SegueIdentifiers.HomeToAddEventSegue { APIConnector.connector().trackMetric("Click Add (Home screen)") } else { NSLog("Unprepped segue from eventList \(segue.identifier)") } } // Back button from group or detail viewer. @IBAction func done(_ segue: UIStoryboardSegue) { NSLog("unwind segue to eventList done!") } // Multiple VC's on the navigation stack return all the way back to this initial VC via this segue, when nut events go away due to deletion, for test purposes, etc. @IBAction func home(_ segue: UIStoryboardSegue) { NSLog("unwind segue to eventList home!") } // The add/edit VC will return here when a meal event is deleted, and detail vc was transitioned to directly from this vc (i.e., the Nut event contained a single meal event which was deleted). @IBAction func doneItemDeleted(_ segue: UIStoryboardSegue) { NSLog("unwind segue to eventList doneItemDeleted") } @IBAction func cancel(_ segue: UIStoryboardSegue) { NSLog("unwind segue to eventList cancel") } fileprivate var eventListNeedsUpdate: Bool = false func databaseChanged(_ note: Notification) { NSLog("EventList: Database Change Notification") if viewIsForeground { getNutEvents() } else { eventListNeedsUpdate = true } } func getNutEvents() { var nutEvents = [String: NutEvent]() func addNewEvent(_ newEvent: EventItem) { /// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING! if newEvent.userid == nil { newEvent.userid = NutDataController.controller().currentUserId if let moc = newEvent.managedObjectContext { NSLog("NOTE: Updated nil userid to \(newEvent.userid)") moc.refresh(newEvent, mergeChanges: true) _ = DatabaseUtils.databaseSave(moc) } } /// TODO: TEMP UPGRADE CODE, REMOVE BEFORE SHIPPING! let newEventId = newEvent.nutEventIdString() if let existingNutEvent = nutEvents[newEventId] { _ = existingNutEvent.addEvent(newEvent) //NSLog("appending new event: \(newEvent.notes)") //existingNutEvent.printNutEvent() } else { nutEvents[newEventId] = NutEvent(firstEvent: newEvent) } } sortedNutEvents = [(String, NutEvent)]() filteredNutEvents = [(String, NutEvent)]() filterString = "" // Get all Food and Activity events, chronologically; this will result in an unsorted dictionary of NutEvents. do { let nutEvents = try DatabaseUtils.getAllNutEvents() for event in nutEvents { //if let event = event as? Workout { // NSLog("Event type: \(event.type), id: \(event.id), time: \(event.time), created time: \(event.createdTime!.timeIntervalSinceDate(event.time!)), duration: \(event.duration), title: \(event.title), notes: \(event.notes), userid: \(event.userid), timezone offset:\(event.timezoneOffset)") //} addNewEvent(event) } } catch let error as NSError { NSLog("Error: \(error)") } sortedNutEvents = nutEvents.sorted() { $0.1.mostRecent.compare($1.1.mostRecent as Date) == ComparisonResult.orderedDescending } updateFilteredAndReload() // One time orphan check after application load EventListViewController.checkAndDeleteOrphans(sortedNutEvents) } static var _checkedForOrphanPhotos = false class func checkAndDeleteOrphans(_ allNutEvents: [(String, NutEvent)]) { if _checkedForOrphanPhotos { return } _checkedForOrphanPhotos = true if let photoDirPath = NutUtils.photosDirectoryPath() { var allLocalPhotos = [String: Bool]() let fm = FileManager.default do { let dirContents = try fm.contentsOfDirectory(atPath: photoDirPath) //NSLog("Photos dir: \(dirContents)") if !dirContents.isEmpty { for file in dirContents { allLocalPhotos[file] = false } for (_, nutEvent) in allNutEvents { for event in nutEvent.itemArray { for url in event.photoUrlArray() { if url.hasPrefix("file_") { //NSLog("\(NutUtils.photoInfo(url))") allLocalPhotos[url] = true } } } } } } catch let error as NSError { NSLog("Error accessing photos at \(photoDirPath), error: \(error)") } let orphans = allLocalPhotos.filter() { $1 == false } for (url, _) in orphans { NSLog("Deleting orphaned photo: \(url)") NutUtils.deleteLocalPhoto(url) } } } // MARK: - Search @IBAction func dismissKeyboard(_ sender: AnyObject) { searchTextField.resignFirstResponder() } func textFieldDidChange() { updateFilteredAndReload() } @IBAction func searchEditingDidEnd(_ sender: AnyObject) { configureSearchUI() } @IBAction func searchEditingDidBegin(_ sender: AnyObject) { configureSearchUI() APIConnector.connector().trackMetric("Typed into Search (Home Screen)") } fileprivate func searchMode() -> Bool { var searchMode = false if searchTextField.isFirstResponder { searchMode = true } else if let searchText = searchTextField.text { if !searchText.isEmpty { searchMode = true } } return searchMode } fileprivate func configureSearchUI() { let searchOn = searchMode() searchPlaceholderLabel.isHidden = searchOn self.title = searchOn && !filterString.isEmpty ? "Events" : "All events" } fileprivate func updateFilteredAndReload() { if !searchMode() { filteredNutEvents = sortedNutEvents filterString = "" } else if let searchText = searchTextField.text { if !searchText.isEmpty { if searchText.localizedCaseInsensitiveContains(filterString) { // if the search is just getting longer, no need to check already filtered out items filteredNutEvents = filteredNutEvents.filter() { $1.containsSearchString(searchText) } } else { filteredNutEvents = sortedNutEvents.filter() { $1.containsSearchString(searchText) } } filterString = searchText } else { filteredNutEvents = sortedNutEvents filterString = "" } // Do this last, after filterString is configured configureSearchUI() } tableView.reloadData() } } // // MARK: - Table view delegate // extension EventListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, estimatedHeightForRowAt estimatedHeightForRowAtIndexPath: IndexPath) -> CGFloat { return 102.0; } func tableView(_ tableView: UITableView, heightForRowAt heightForRowAtIndexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let tuple = self.filteredNutEvents[indexPath.item] let nutEvent = tuple.1 let cell = tableView.cellForRow(at: indexPath) if nutEvent.itemArray.count == 1 { self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue, sender: cell) } else if nutEvent.itemArray.count > 1 { self.performSegue(withIdentifier: EventViewStoryboard.SegueIdentifiers.EventGroupSegue, sender: cell) } } } // // MARK: - Table view data source // extension EventListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredNutEvents.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Note: two different list cells are used depending upon whether a location will be shown or not. var cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellNoLoc var nutEvent: NutEvent? if (indexPath.item < filteredNutEvents.count) { let tuple = self.filteredNutEvents[indexPath.item] nutEvent = tuple.1 if !nutEvent!.location.isEmpty { cellId = EventViewStoryboard.TableViewCellIdentifiers.eventListCellWithLoc } } let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! EventListTableViewCell if let nutEvent = nutEvent { cell.configureCell(nutEvent) } return cell } /* // 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 } */ }
b43a49c0ff9357cb579cce91ff1df059
38.587738
305
0.628785
false
false
false
false
vinivendra/jokr
refs/heads/master
jokr/Translators/JKRObjcTranslator.swift
apache-2.0
1
// doc // test class JKRObjcTranslator: JKRTranslator { //////////////////////////////////////////////////////////////////////////// // MARK: Interface init(writingWith writer: JKRWriter = JKRConsoleWriter()) { self.writer = writer } static func create(writingWith writer: JKRWriter) -> JKRTranslator { return JKRObjcTranslator(writingWith: writer) } func translate(program: JKRTreeProgram) throws { do { if let statements = program.statements { changeFile("main.m") indentation = 0 write("#import <Foundation/Foundation.h>\n\nint main(int argc, const char * argv[]) {\n") // swiftlint:disable:previous line_length indentation += 1 addIntentation() write("@autoreleasepool {\n") indentation += 1 writeWithStructure(statements) indentation = 1 addIntentation() write("}\n") addIntentation() write("return 0;\n}\n") } // if let declarations = program.declarations { // } try writer.finishWriting() } catch (let error) { throw error } } //////////////////////////////////////////////////////////////////////////// // MARK: Implementation private static let valueTypes = ["int", "float", "void"] // Transpilation (general structure) private var indentation = 0 private func writeWithStructure(_ statements: [JKRTreeStatement]) { for statement in statements { writeWithStructure(statement) } } private func writeWithStructure(_ statement: JKRTreeStatement) { addIntentation() write(translate(statement)) // if let block = statement.block { // write(" {\n") // indentation += 1 // writeWithStructure(block) // indentation -= 1 // addIntentation() // write("}\n") // } } // Translation (pieces of code) private func translate(_ statement: JKRTreeStatement) -> String { switch statement { case let .assignment(assignment): return translate(assignment) case let .functionCall(functionCall): return translate(functionCall) case let .returnStm(returnStm): return translate(returnStm) } } private func translate( _ assignment: JKRTreeAssignment) -> String { switch assignment { case let .declaration(type, id, expression): let typeText = string(for: type, withSpaces: true) let idText = string(for: id) let expressionText = translate(expression) return "\(typeText)\(idText) = \(expressionText);\n" case let .assignment(id, expression): let idText = string(for: id) let expressionText = translate(expression) return "\(idText) = \(expressionText);\n" } } private func translate(_ functionCall: JKRTreeFunctionCall) -> String { if functionCall.id == "print" { if functionCall.parameters.count == 0 { return "NSLog(@\"Hello jokr!\\n\");\n" } else { let format = functionCall.parameters.map {_ in "%d" } .joined(separator: " ") let parameters = functionCall.parameters.map(translate) .joined(separator: ", ") return "NSLog(@\"\(format)\\n\", \(parameters));\n" } } return "\(string(for: functionCall.id))();\n" } private func translateHeader( _ function: JKRTreeFunctionDeclaration) -> String { var contents = "- (\(string(for: function.type)))\(string(for: function.id))" let parameters = function.parameters.map(strings(for:)) if let parameter = parameters.first { contents += ":(\(parameter.type))\(parameter.id)" } for parameter in parameters.dropFirst() { contents += " \(parameter.id):(\(parameter.type))\(parameter.id)" } return contents } private func translate(_ returnStm: JKRTreeReturn) -> String { let expression = translate(returnStm.expression) return "return \(expression);\n" } private func translate( _ expression: JKRTreeExpression) -> String { switch expression { case let .int(int): return string(for: int) case let .parenthesized(innerExpression): let innerExpressionText = translate(innerExpression) return "(\(innerExpressionText))" case let .operation(leftExpression, op, rightExpression): let leftText = translate(leftExpression) let rightText = translate(rightExpression) return "\(leftText) \(op.text) \(rightText)" case let .lvalue(id): return string(for: id) } } private func strings( for parameter: JKRTreeParameterDeclaration) -> (type: String, id: String) { return (string(for: parameter.type), string(for: parameter.id)) } private func string(for type: JKRTreeType, withSpaces: Bool = false) -> String { let lowercased = type.text.lowercased() if JKRObjcTranslator.valueTypes.contains(lowercased) { if withSpaces { return lowercased + " " } else { return lowercased } } else { return type.text + " *" } } func string(for id: JKRTreeID) -> String { return id.text } func string(for int: JKRTreeInt) -> String { return String(int.value) } // Writing private let writer: JKRWriter private func write(_ string: String) { writer.write(string) } private func changeFile(_ string: String) { writer.changeFile(string) } private func addIntentation() { for _ in 0..<indentation { write("\t") } } }
52439bc6ed439db574901e15c7b37f5b
23.598086
93
0.650846
false
false
false
false
Snail93/iOSDemos
refs/heads/dev
SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/MyImagePickerViewController.swift
apache-2.0
2
// // MyImagePickerViewController.swift // SnailSwiftDemos // // Created by Jian Wu on 2017/3/23. // Copyright © 2017年 Snail. All rights reserved. // import UIKit //import ImagePicker class MyImagePickerViewController: CustomViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navTitleLabel.text = "ImagePicker" rightBtn.isHidden = false } override func rightAction() { // Configuration.doneButtonTitle = "Finshi" // Configuration.noImagesTitle = "Sorry! Threre" // // super.rightAction() // let iPController = ImagePickerController() // iPController.delegate = self // self.present(iPController, animated: true, completion: nil) } // // //MARK: - ImagePickerDelegate methods // func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { // print(images.count) // } // // func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { // print(images) // } // // func cancelButtonDidPress(_ imagePicker: ImagePickerController) { // print("???") // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
7cbc3c242cdc7f21246e5a0a27827df7
26.761905
106
0.64837
false
false
false
false
UrbanCompass/Snail
refs/heads/main
Snail/Scheduler.swift
mit
1
// Copyright © 2018 Compass. All rights reserved. import Foundation public class Scheduler { let delay: TimeInterval let repeats: Bool public let observable = Observable<Void>() private var timer: Timer? public init(_ delay: TimeInterval, repeats: Bool = true) { self.delay = delay self.repeats = repeats } @objc public func onNext() { observable.on(.next(())) } public func start() { stop() timer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(onNext), userInfo: nil, repeats: repeats) } public func stop() { timer?.invalidate() } }
a437ad310ef460d6c3fa4cc54c26f3b3
22.068966
133
0.621824
false
false
false
false
radicalbear/radbear-ios
refs/heads/master
radbear-ios/Classes/SimpleCell.swift
mit
1
// // SimpleCell.h // radbear-ios // // Created by Gary Foster on 6/26/12. // Copyright (c) 2012 Radical Bear LLC. All rights reserved. // public class SimpleCell: UITableViewCell { var image_y: Int = 0 public func changeStyle(_ row: Int, cellText: String, sub1: String?, sub2: String?, sub3: String?, highlight: Bool, color: UIColor?, tableWidth: Int, imageY: Int) { let myEnvironment = Environment.sharedInstance image_y = imageY if color != nil { let bgView = UITableViewCell(frame: CGRect.zero) bgView.backgroundColor = color self.backgroundView = bgView self.backgroundColor = color } else { let bgView = UITableViewCell(frame: CGRect.zero) if myEnvironment.darkTheme { let evenColor = UIColor(patternImage: AppTools.getImage(name: "row-background-1-opaque.png")!) let oddColor = UIColor(patternImage: AppTools.getImage(name: "row-background-2-opaque.png")!) bgView.backgroundColor = (row % 2) == 0 ? evenColor : oddColor } else { let evenColor = UIColor(patternImage: AppTools.getImage(name: "row-background-1.png")!) let oddColor = UIColor(patternImage: AppTools.getImage(name: "row-background-2.png")!) bgView.backgroundColor = (row % 2) == 0 ? evenColor : oddColor } self.backgroundView = bgView } var lblX: Int = 17 var lblY: Int = (sub3 != nil ) ? 5 : 11 var lblW: Int = tableWidth - 70 var lblH: Int = 21 let imageW: Int = 60 var subW: Int = RBAppTools.isIpad() ? 120 : 60 var rightMargin: Int = 23 if RBAppTools.isIpad() { rightMargin = rightMargin * 2 subW = subW * 2 } let subX: Int = tableWidth - subW - rightMargin let subY: Int = (sub3 != nil) ? 5 : 0 if ((self.imageView?.image) != nil) { lblX = lblX + imageW lblW = lblW - imageW } if (sub1 != nil) || (sub2 != nil) { lblW = lblW - 40 lblY = lblY - 6 lblH = lblH + 12 } var lbl: UILabel? = (self.viewWithTag(1) as? UILabel) if lbl == nil { lbl = UILabel(frame: CGRect(x: CGFloat(lblX), y: CGFloat(lblY), width: CGFloat(lblW), height: CGFloat(lblH))) } if highlight { lbl?.textColor = UIColor.red } else { if myEnvironment.darkTheme { lbl?.textColor = (color == nil) ? UIColor.white : UIColor.black } else { lbl?.textColor = (color == nil) ? UIColor.black : UIColor.white } } if (sub1 != nil) || (sub2 != nil) { lbl?.numberOfLines = 2 lbl?.lineBreakMode = .byWordWrapping lbl?.font = UIFont.boldSystemFont(ofSize: CGFloat(14)) lbl?.adjustsFontSizeToFitWidth = true } else { lbl?.font = UIFont.boldSystemFont(ofSize: CGFloat(16)) } lbl?.text = cellText lbl?.backgroundColor = UIColor.clear lbl?.tag = 1 self.contentView.addSubview(lbl!) var lblSub1: UILabel? = (self.viewWithTag(2) as? UILabel) if lblSub1 == nil { lblSub1 = UILabel(frame: CGRect(x: CGFloat(subX), y: CGFloat(subY), width: CGFloat(subW), height: CGFloat(21))) } lblSub1?.font = UIFont.systemFont(ofSize: CGFloat(13)) lblSub1?.textColor = UIColor.darkGray lblSub1?.adjustsFontSizeToFitWidth = false lblSub1?.text = sub1 lblSub1?.backgroundColor = UIColor.clear lblSub1?.tag = 2 lblSub1?.isHidden = (sub1 == nil) self.contentView.addSubview(lblSub1!) var lblSub2: UILabel? = (self.viewWithTag(3) as? UILabel) if lblSub2 == nil { lblSub2 = UILabel(frame: CGRect(x: CGFloat(subX), y: CGFloat(20), width: CGFloat(subW), height: CGFloat(21))) } lblSub2?.font = UIFont.systemFont(ofSize: CGFloat(13)) lblSub2?.textColor = UIColor.darkGray lblSub2?.adjustsFontSizeToFitWidth = false lblSub2?.text = sub2 lblSub2?.backgroundColor = UIColor.clear lblSub2?.tag = 3 lblSub2?.isHidden = (sub2 == nil) self.contentView.addSubview(lblSub2!) var lblSub3: UILabel? = (self.viewWithTag(4) as? UILabel) if lblSub3 == nil { lblSub3 = UILabel(frame: CGRect(x: CGFloat(lblX), y: CGFloat(lblY + 22), width: CGFloat(tableWidth - lblX - 25), height: CGFloat(40))) } lblSub3?.font = UIFont.systemFont(ofSize: CGFloat(12)) lblSub3?.textColor = UIColor.darkGray lblSub3?.adjustsFontSizeToFitWidth = false lblSub3?.text = sub3 lblSub3?.backgroundColor = UIColor.clear lblSub3?.numberOfLines = 2 lblSub3?.tag = 4 lblSub3?.isHidden = (sub3 == nil) self.contentView.addSubview(lblSub3!) } public func changeStyle(_ row: Int, cellText: String, sub1: String?, sub2: String?, highlight: Bool, tableWidth: Int, imageY: Int) { self.changeStyle(row, cellText: cellText, sub1: sub1, sub2: sub2, sub3: nil, highlight: highlight, color: nil, tableWidth: tableWidth, imageY: imageY) } public func changeStyle(_ cellText: String, sub1: String, sub2: String, sub3: String, highlight: Bool, color: UIColor, tableWidth: Int) { self.changeStyle(-1, cellText: cellText, sub1: sub1, sub2: sub2, sub3: sub3, highlight: highlight, color: color, tableWidth: tableWidth, imageY: 11) } public override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = CGRect(x: CGFloat(20), y: CGFloat(image_y), width: CGFloat(48), height: CGFloat(48)) } }
3443a07bb5b112483b8bbdcc1b9aabe7
41.3
168
0.579027
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
refs/heads/master
Playground Collection/Part 4 - Alien Adventure 2/Advanced Operators/Advanced Operators.playground/Pages/Bitwise Operators.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) /*: ## Bitwise Operators Bitwise NOT operator (also called INVERT) */ var someBits: UInt8 = 0b00001111 let invertedBits = ~someBits // equals 11110000 //: **Bitwise AND operator** someBits = 0b01011100 var someMoreBits: UInt8 = 0b11101000 let andBits = someBits & someMoreBits // equals 0b01001000 //: **Bitwise OR operator** someBits = 0b01101111 someMoreBits = 0b10001111 let orBits = someBits | someMoreBits // equals 0b11101111 //: **Bitwise XOR operator** someBits = 0b11000011 someMoreBits = 0b10011001 let xorBits = someBits ^ someMoreBits // equals 0b01011010 /*: **Bitwise Left Shift operator** See [Apple's Docs on Advanced Operators](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html), go to the "Bitwise Left and Right Shift Operators" section) */ someBits = 0b00010001 var leftShiftedBits = someBits << 1 // equals 0b00100010 leftShiftedBits = leftShiftedBits << 2 // eqauls 0b10001000 /*: **Bitwise Right Shift operator** See [Apple's Docs on Advanced Operators](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html), go to the "Bitwise Left and Right Shift Operators" section) */ someBits = 0b00010001 var rightShiftedBits = someBits >> 3 // equals 0b000000010 /*: Note: You can combine the following bitwise operators with assignment: - <<= Left bit shift and assign - >>= Right bit shift and assign - &= Bitwise AND and assign - ^= Bitwise XOR and assign - |= Bitwise OR and assign */ let bottomBitMask: UInt8 = 0b00001111 someBits = 0b01011100 someMoreBits = 0b1101000 // here is an example of Bitwise AND and assignment someBits &= bottomBitMask // equals 0b00001100 someMoreBits &= bottomBitMask // equals 0b00001000 //: Here is a more practical example with bitwise operators that seperates the RGB components of a color. Check out [this fun video](https://www.youtube.com/watch?v=5KZJbMomxa4) to see how RGB color theory works! import UIKit func colorFromHex(hexValue: UInt32) -> UIColor { // 1. filters each component (rgb) with bitwise AND // 2. shifts each component (rgb) to a 0-255 value with bitwise right shift // 3. divides each component (rgb) by 255.0 to create a value between 0.0 - 1.0 return UIColor( red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hexValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } let pink: UInt32 = 0xCC6699 let redComponent = (pink & 0xFF0000) // equals 0xCC0000 let greenComponent = (pink & 0x00FF00) // equals 0x006600 let blueComponent = (pink & 0x0000FF) // equals 0x000099 colorFromHex(hexValue: pink) colorFromHex(hexValue: redComponent) colorFromHex(hexValue: greenComponent) colorFromHex(hexValue: blueComponent) //: [Next](@next)
319f44e404ca952b83f84d5960091362
33.670588
234
0.734645
false
false
false
false
nethergrim/xpolo
refs/heads/master
XPolo/Pods/BFKit-Swift/Sources/BFKit/Linux/BFKit/BFApp.swift
gpl-3.0
1
// // BFApp.swift // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2017 Fabrizio Brancati. 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 #if os(iOS) import UIKit #endif // MARK: - Global variables #if os(iOS) /// Get AppDelegate. To use it, cast to AppDelegate with "as! AppDelegate". public let appDelegate: UIApplicationDelegate? = UIApplication.shared.delegate #endif #if !os(Linux) // MARK: - Global functions /// NSLocalizedString without comment parameter. /// /// - Parameter key: The key of the localized string. /// - Returns: Returns a localized string. public func NSLocalizedString(_ key: String) -> String { return NSLocalizedString(key, comment: "") } #endif // MARK: - BFApp struct /// This class adds some useful functions for the App. public struct BFApp { // MARK: - Variables /// Used to store the BFHasBeenOpened in defaults. private static let BFAppHasBeenOpened = "BFAppHasBeenOpened" // MARK: - Functions /// Executes a block only if in DEBUG mode. /// /// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797). /// /// - Parameter block: The block to be executed. public static func debug(_ block: () -> Void) { #if DEBUG block() #endif } /// Executes a block only if NOT in DEBUG mode. /// /// More info on how to use it [here](http://stackoverflow.com/questions/26890537/disabling-nslog-for-production-in-swift-project/26891797#26891797). /// /// - Parameter block: The block to be executed. public static func release(_ block: () -> Void) { #if !DEBUG block() #endif } /// If version is set returns if is first start for that version, /// otherwise returns if is first start of the App. /// /// - Parameter version: Version to be checked, you can use the variable BFApp.version to pass the current App version. /// - Returns: Returns if is first start of the App or for custom version. public static func isFirstStart(version: String = "") -> Bool { let key: String = BFAppHasBeenOpened + "\(version)" let defaults = UserDefaults.standard let hasBeenOpened: Bool = defaults.bool(forKey: key) return !hasBeenOpened } /// Executes a block on first start of the App, if version is set it will be for given version. /// /// Remember to execute UI instuctions on main thread. /// /// - Parameters: /// - version: Version to be checked, you can use the variable BFApp.version to pass the current App version. /// - block: The block to execute, returns isFirstStart. public static func onFirstStart(version: String = "", block: (_ isFirstStart: Bool) -> Void) { let key: String if version == "" { key = BFAppHasBeenOpened } else { key = BFAppHasBeenOpened + "\(version)" } let defaults = UserDefaults.standard let hasBeenOpened: Bool = defaults.bool(forKey: key) if hasBeenOpened != true { defaults.set(true, forKey: key) } block(!hasBeenOpened) } #if !os(Linux) && !os(macOS) /// Set the App setting for a given object and key. The file will be saved in the Library directory. /// /// - Parameters: /// - object: Object to set. /// - objectKey: Key to set the object. /// - Returns: Returns true if the operation was successful, otherwise false. @discardableResult public static func setAppSetting(object: Any, forKey objectKey: String) -> Bool { return FileManager.default.setSettings(filename: BFApp.name, object: object, forKey: objectKey) } /// Get the App setting for a given key. /// /// - Parameter objectKey: Key to get the object. /// - Returns: Returns the object for the given key. public static func getAppSetting(objectKey: String) -> Any? { return FileManager.default.getSettings(filename: BFApp.name, forKey: objectKey) } #endif } // MARK: - BFApp extension /// Extends BFApp with project infos. public extension BFApp { // MARK: - Variables /// Return the App name. public static var name: String = { return BFApp.stringFromInfoDictionary(forKey: "CFBundleDisplayName") }() /// Returns the App version. public static var version: String = { return BFApp.stringFromInfoDictionary(forKey: "CFBundleShortVersionString") }() /// Returns the App build. public static var build: String = { return BFApp.stringFromInfoDictionary(forKey: "CFBundleVersion") }() /// Returns the App executable. public static var executable: String = { return BFApp.stringFromInfoDictionary(forKey: "CFBundleExecutable") }() /// Returns the App bundle. public static var bundle: String = { return BFApp.stringFromInfoDictionary(forKey: "CFBundleIdentifier") }() // MARK: - Functions /// Returns a String from the Info dictionary of the App. /// /// - Parameter key: Key to search. /// - Returns: Returns a String from the Info dictionary of the App. private static func stringFromInfoDictionary(forKey key: String) -> String { guard let infoDictionary = Bundle.main.infoDictionary, let value = infoDictionary[key] as? String else { return "" } return value } }
3e3d48c49aaf8bef6c8ec5cb7aa81e12
35.175532
153
0.644611
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/UIComponents/UIComponentsKit/Theme/Color+Theme.swift
lgpl-3.0
1
import SwiftUI extension Color { // MARK: Borders public static let borderPrimary = Color(paletteColor: .grey100) public static let borderFocused = Color(paletteColor: .blue600) public static let borderSuccess = Color(paletteColor: .green800) public static let borderError = Color(paletteColor: .red600) // MARK: Backgrounds public static let lightContentBackground = Color(paletteColor: .grey900) public static let viewPrimaryBackground = Color(paletteColor: .white) public static let shimmeringLight = Color(paletteColor: .grey000) public static let shimmeringDark = Color(paletteColor: .grey200) // MARK: PrimaryButton public static let buttonPrimaryBackground = Color(paletteColor: .blue600) public static let buttonPrimaryText = Color(paletteColor: .white) // MARK: SecondaryButton public static let buttonSecondaryBackground = Color(paletteColor: .white) public static let buttonSecondaryText = Color(paletteColor: .blue600) // MARK: MinimalDoubleButton public static let buttonMinimalDoubleBackground = Color(paletteColor: .white) public static let buttonMinimalDoublePressedBackground = Color(paletteColor: .grey000) public static let buttonMinimalDoubleText = Color(paletteColor: .blue600) // MARK: Links public static let buttonLinkText = Color(paletteColor: .blue600) // MARK: Divider public static let dividerLine = Color(paletteColor: .grey100) public static let dividerLineLight = Color(paletteColor: .grey000) // MARK: Text public static let textTitle = Color(paletteColor: .grey900) public static let textDetail = Color(paletteColor: .grey600) public static let textHeading = Color(paletteColor: .grey900) public static let textSubheading = Color(paletteColor: .grey600) public static let textBody = Color(paletteColor: .grey800) public static let textMuted = Color(paletteColor: .grey400) public static let textError = Color(paletteColor: .red600) public static let formField = Color(paletteColor: .greyFade800) // MARK: TextField public static let textFieldPrefilledAndDisabledBackground = Color(paletteColor: .grey100) public static let textCallOutBackground = Color(paletteColor: .grey000) public static let secureFieldEyeSymbol = Color(paletteColor: .grey400) // MARK: Password Strength public static let weakPassword = Color(paletteColor: .red600) public static let mediumPassword = Color(paletteColor: .orange600) public static let strongPassword = Color(paletteColor: .green600) // MARK: Badge public static let badgeTextInfo = Color(paletteColor: .blue400) public static let badgeTextError = Color(paletteColor: .red400) public static let badgeTextWarning = Color(paletteColor: .orange400) public static let badgeTextSuccess = Color(paletteColor: .green400) public static let badgeBackgroundInfo = Color(paletteColor: .blue000) public static let badgeBackgroundError = Color(paletteColor: .red000) public static let badgeBackgroundWarning = Color(paletteColor: .orange000) public static let badgeBackgroundSuccess = Color(paletteColor: .green000) // MARK: Other Elements public static let backgroundFiat = Color(paletteColor: .green500) public static let positiveTrend = Color(paletteColor: .green600) public static let negativeTrend = Color(paletteColor: .red600) public static let neutralTrend = Color(paletteColor: .grey600) public static let disclosureIndicator = Color(paletteColor: .grey600) }
bd413a7bb21f05e963f5604c107a58ca
40.616279
93
0.755239
false
false
false
false
cloudinary/cloudinary_ios
refs/heads/master
Cloudinary/Classes/Core/BaseNetwork/CLDNTaskDelegate.swift
mit
1
// // CLDNTaskDelegate.swift // // 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 /// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as /// executing all operations attached to the serial operation queue upon task completion. internal class CLDNTaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. internal let queue: OperationQueue /// The data returned by the server. internal var data: Data? { return nil } /// The error generated throughout the lifecyle of the task. internal var error: Error? var task: URLSessionTask? { set { taskLock.lock(); defer { taskLock.unlock() } _task = newValue } get { taskLock.lock(); defer { taskLock.unlock() } return _task } } var initialResponseTime: CFAbsoluteTime? var credential: URLCredential? var metrics: AnyObject? // URLSessionTaskMetrics private var _task: URLSessionTask? { didSet { reset() } } private let taskLock = NSLock() // MARK: Lifecycle init(task: URLSessionTask?) { _task = task self.queue = { let operationQueue = OperationQueue() operationQueue.name = "com.cloudinary.CLDNTaskDelegateOperationQueue" operationQueue.maxConcurrentOperationCount = 1 operationQueue.isSuspended = true operationQueue.qualityOfService = .utility return operationQueue }() } func reset() { error = nil initialResponseTime = nil } // MARK: URLSessionTaskDelegate var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } @objc(URLSession:task:didReceiveChallenge:completionHandler:) func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let taskDidReceiveChallenge = taskDidReceiveChallenge { (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) } else { if challenge.previousFailureCount > 0 { disposition = .rejectProtectionSpace } else { credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) if credential != nil { disposition = .useCredential } } } completionHandler(disposition, credential) } @objc(URLSession:task:needNewBodyStream:) func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { var bodyStream: InputStream? if let taskNeedNewBodyStream = taskNeedNewBodyStream { bodyStream = taskNeedNewBodyStream(session, task) } completionHandler(bodyStream) } @objc(URLSession:task:didCompleteWithError:) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { if self.error == nil { self.error = error } } queue.isSuspended = false } } } // MARK: - class CLDNDataTaskDelegate: CLDNTaskDelegate, URLSessionDataDelegate { // MARK: Properties var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } override var data: Data? { if dataStream != nil { return nil } else { return mutableData } } var progress: Progress var progressHandler: (closure: CLDNRequest.ProgressHandler, queue: DispatchQueue)? var dataStream: ((_ data: Data) -> Void)? private var totalBytesReceived: Int64 = 0 private var mutableData: Data private var expectedContentLength: Int64? // MARK: Lifecycle override init(task: URLSessionTask?) { mutableData = Data() progress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() progress = Progress(totalUnitCount: 0) totalBytesReceived = 0 mutableData = Data() expectedContentLength = nil } // MARK: URLSessionDataDelegate var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { var disposition: URLSession.ResponseDisposition = .allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { if let dataStream = dataStream { dataStream(data) } else { mutableData.append(data) } let bytesReceived = Int64(data.count) totalBytesReceived += bytesReceived let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived if let progressHandler = progressHandler { progressHandler.queue.async { progressHandler.closure(self.progress) } } } } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { var cachedResponse: CachedURLResponse? = proposedResponse if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) } completionHandler(cachedResponse) } } // MARK: - class CLDNUploadTaskDelegate: CLDNDataTaskDelegate { // MARK: Properties var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } var uploadProgress: Progress var uploadProgressHandler: (closure: CLDNRequest.ProgressHandler, queue: DispatchQueue)? // MARK: Lifecycle override init(task: URLSessionTask?) { uploadProgress = Progress(totalUnitCount: 0) super.init(task: task) } override func reset() { super.reset() uploadProgress = Progress(totalUnitCount: 0) } // MARK: URLSessionTaskDelegate var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? func URLSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { uploadProgress.totalUnitCount = totalBytesExpectedToSend uploadProgress.completedUnitCount = totalBytesSent if let uploadProgressHandler = uploadProgressHandler { uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } } } } }
a750775b102350bd444c832117adab9c
32.789634
149
0.674637
false
false
false
false
atuooo/notGIF
refs/heads/master
notGIF/Extensions/Realm+NG.swift
mit
1
// // Realm+NG.swift // notGIF // // Created by Atuooo on 18/06/2017. // Copyright © 2017 xyz. All rights reserved. // import Foundation import RealmSwift public extension List { func add(object: Element, update: Bool) { if update { if !contains(object) { append(object) } } else { append(object) } } func add<S: Sequence>(objectsIn objects: S, update: Bool) where S.Iterator.Element == T { if update { objects.forEach{ add(object: $0, update: true) } } else { append(objectsIn: objects) } } func remove(_ object: Element) { if let index = index(of: object) { remove(objectAtIndex: index) } } func remove<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == T { objects.forEach { remove($0) } } }
ba6f444fed55e34fc41555e3c5ad5173
21.380952
93
0.52234
false
false
false
false
SomeHero/iShopAwayAPIManager
refs/heads/master
IShopAwayApiManager/Classes/models/PaymentMethod.swift
mit
1
// // PaymentMethod.swift // Pods // // Created by James Rhodes on 6/21/16. // // import Foundation import ObjectMapper public class PaymentMethod: Mappable { public var id: String! public var type: String! public var cardType: String! public var cardLastFour: String! public var expirationMonth: Int! public var expirationYear: Int! public var isDefault: Bool = false public init(type: String, cardType: String, cardLastFour: String, expirationMonth: Int, expirationYear: Int, isDefault: Bool) { self.type = type self.cardType = cardType self.cardLastFour = cardLastFour self.expirationMonth = expirationMonth self.expirationYear = expirationYear } public required init?(_ map: Map){ mapping(map) } public func mapping(map: Map) { id <- map["_id"] type <- map["type"] cardType <- map["card_info.card_type"] cardLastFour <- map["card_info.card_last_four"] expirationMonth <- map["card_info.expiration_month"] expirationYear <- map["card_info.expiration_year"] isDefault <- map["is_default"] } }
3076e0705968379d9799489266be1f04
27.439024
131
0.638937
false
false
false
false
tqtifnypmb/Framenderer
refs/heads/master
Framenderer/Sources/Filters/Blur/GaussianBlur/GaussianBlurFilter.swift
mit
2
// // GaussianBlurFilter.swift // Framenderer // // Created by tqtifnypmb on 12/12/2016. // Copyright © 2016 tqitfnypmb. All rights reserved. // import Foundation import OpenGLES.ES3.gl import OpenGLES.ES3.glext import CoreMedia import AVFoundation public class GaussianBlurFilter: TwoPassFilter { private let _radius: Int private let _sigma: Double /// sigma value used by Gaussian algorithm public var gaussianSigma: Double = 0 /** init a [Gaussian blur](https://en.wikipedia.org/wiki/Gaussian_blur) filter - parameter radius: specifies the distance from the center of the blur effect. - parameter implement: specifies which implement to use. - box: mimic Gaussian blur by applying box blur mutiple times - normal: use Gaussian algorithm */ public init(radius: Int = 3, sigma: Double = 0) { if sigma == 0 { _radius = radius // source from OpenCV (http://docs.opencv.org/3.2.0/d4/d86/group__imgproc__filter.html) _sigma = 0.3 * Double(_radius - 1) + 0.8 } else { // kernel size <= 6sigma is good enough // reference: https://en.wikipedia.org/wiki/Gaussian_blur _radius = min(radius, Int(floor(6 * sigma))) _sigma = sigma } } override public var name: String { return "GaussianBlurFilter" } override public func setUniformAttributs(context ctx: Context) { super.setUniformAttributs(context: ctx) let texelWidth = 1 / GLfloat(ctx.inputWidth) _program.setUniform(name: kXOffset, value: texelWidth) _program.setUniform(name: kYOffset, value: GLfloat(0)) _program.setUniform(name: "radius", value: _radius) _program.setUniform(name: "sigma", value: Float(_sigma)) } override public func setUniformAttributs2(context ctx: Context) { super.setUniformAttributs2(context: ctx) let texelHeight = 1 / GLfloat(ctx.inputHeight) _program2.setUniform(name: kXOffset, value: GLfloat(0)) _program2.setUniform(name: kYOffset, value: texelHeight) _program2.setUniform(name: "radius", value: _radius) _program2.setUniform(name: "sigma", value: Float(_sigma)) } override func buildProgram() throws { _program = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader") _program2 = try Program.create(fragmentSourcePath: "GaussianBlurFragmentShader") } }
b232a1d8b28e42e4244367705856d073
34.583333
99
0.636222
false
false
false
false
nerd0geek1/TableViewManager
refs/heads/master
TableViewManager/classes/implementation/TableViewDelegate.swift
mit
1
// // TableViewDelegate.swift // TableViewManager // // Created by Kohei Tabata on 6/23/16. // Copyright © 2016 Kohei Tabata. All rights reserved. // import Foundation import UIKit public class TableViewDelegate: NSObject, TableViewDelegateType { public var didSelectRow: ((IndexPath) -> Void)? public var didDeselectRow: ((IndexPath) -> Void)? public weak var dataSource: TableViewDataSource? // MARK: - UITableViewDelegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { didSelectRow?(indexPath) } public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { didDeselectRow?(indexPath) } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let cellClass: UITableViewCell.Type? = dataSource?.cellClassResolver.cellClass(for: indexPath) if let cellClass = cellClass, let customizedHeightCellClass = cellClass as? CustomizedCellHeightType.Type { return customizedHeightCellClass.customizedHeight } return 44 } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sectionData(for: section)?.headerData?.headerHeight ?? 0 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sectionData = self.sectionData(for: section) else { return nil } let sectionHeaderView = sectionData.headerView if let sectionHeaderView = sectionHeaderView as? SectionHeaderDataAcceptableType, let sectionHeaderData = sectionData.headerData { sectionHeaderView.update(sectionHeaderData) } return sectionHeaderView } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return sectionData(for: section)?.footerData?.footerHeight ?? 0 } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let sectionData = self.sectionData(for: section) else { return nil } let sectionFooterView = sectionData.footerView if let sectionFooterView = sectionFooterView as? SectionFooterDataAcceptableType, let sectionFooterData = sectionData.footerData { sectionFooterView.update(sectionFooterData) } return sectionFooterView } // MARK: - private private func sectionData(for section: Int) -> SectionData? { guard let dataSource = dataSource else { return nil } if section > dataSource.sectionDataList.count - 1 { return nil } return dataSource.sectionDataList[section] } }
d5feaf65c47733e24939343498622417
32.423529
138
0.690602
false
false
false
false
0dayZh/LTMorphingLabel
refs/heads/master
LTMorphingLabel/NSString+LTMorphingLabel.swift
apache-2.0
2
// // NSString+LTMorphingLabel.swift // LTMorphingLabel // https://github.com/lexrus/LTMorphingLabel // // Created by Lex on 6/24/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // // The MIT License (MIT) // Copyright © 2014 Lex Tang, http://LexTang.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation enum LTCharacterDiffType: Int, DebugPrintable { case Same = 0 case Add = 1 case Delete case Move case MoveAndAdd case Replace var debugDescription: String { get { switch self { case .Same: return "Same" case .Add: return "Add" case .Delete: return "Delete" case .Move: return "Move" case .MoveAndAdd: return "MoveAndAdd" default: return "Replace" } } } } struct LTCharacterDiffResult: DebugPrintable { var diffType: LTCharacterDiffType var moveOffset: Int var skip: Bool var debugDescription: String { get { switch diffType { case .Same: return "The character is unchanged." case .Add: return "A new character is ADDED." case .Delete: return "The character is DELETED." case .Move: return "The character is MOVED to \(moveOffset)." case .MoveAndAdd: return "The character is MOVED to \(moveOffset) and a new character is ADDED." default: return "The character is REPLACED with a new character." } } } } @infix func >>(lhs: String, rhs: String) -> Array<LTCharacterDiffResult> { var diffResults = Array<LTCharacterDiffResult>() let newChars = enumerate(rhs) let lhsLength = countElements(lhs) let rhsLength = countElements(rhs) var skipIndexes = Array<Int>() for i in 0..(max(lhsLength, rhsLength) + 1) { var result = LTCharacterDiffResult(diffType: .Add, moveOffset: 0, skip: false) // If new string is longer than the original one if i > lhsLength - 1 { result.diffType = .Add diffResults.append(result) continue } // There must be another way to get a Character in String by index let leftChar = { (s:String) -> Character in for (j, char) in enumerate(s) { if i == j { return char } } return Character("") }(lhs) // Search left character in the new string var foundCharacterInRhs = false for (j, newChar) in newChars { let currentCharWouldBeReplaced = { (index: Int) -> Bool in for k in skipIndexes { if index == k { return true } } return false }(j) if currentCharWouldBeReplaced { continue } if leftChar == newChar { skipIndexes.append(j) foundCharacterInRhs = true if i == j { // Character not changed result.diffType = .Same } else { // foundCharacterInRhs and move result.diffType = .Move if i <= rhsLength - 1 { // Move to a new index and add a new character to new original place result.diffType = .MoveAndAdd } result.moveOffset = j - i } break } } if !foundCharacterInRhs { if i < countElements(rhs) - 1 { result.diffType = .Replace } else { result.diffType = .Delete } } if i > lhsLength - 1 { result.diffType = .Add } diffResults.append(result) } var i = 0 for result in diffResults { switch result.diffType { case .Move, .MoveAndAdd: diffResults[i + result.moveOffset].skip = true default: NSNotFound } i++ } return diffResults }
fcaee16651a2f48c09ae945fbad04500
28.765027
92
0.544336
false
false
false
false
Burning-Man-Earth/iBurn-iOS
refs/heads/master
iBurn/BRCDataObject.swift
mpl-2.0
1
// // BRCDataObject.swift // iBurn // // Created by Chris Ballinger on 8/7/17. // Copyright © 2017 Burning Man Earth. All rights reserved. // import Foundation extension BRCDataObjectTableViewCell { /** Mapping between cell identifiers and cell classes */ public static let cellIdentifiers = [BRCDataObjectTableViewCell.cellIdentifier: BRCDataObjectTableViewCell.self, BRCArtObjectTableViewCell.cellIdentifier: BRCArtObjectTableViewCell.self, BRCEventObjectTableViewCell.cellIdentifier: BRCEventObjectTableViewCell.self, ArtImageCell.cellIdentifier: ArtImageCell.self] } extension BRCDataObject { /** Returns the cellIdentifier for table cell subclass */ @objc public var tableCellIdentifier: String { var cellIdentifier = BRCDataObjectTableViewCell.cellIdentifier if let art = self as? BRCArtObject { if art.localThumbnailURL != nil { cellIdentifier = ArtImageCell.cellIdentifier } else { cellIdentifier = BRCArtObjectTableViewCell.cellIdentifier } } else if let _ = self as? BRCEventObject { cellIdentifier = BRCEventObjectTableViewCell.cellIdentifier } else if let _ = self as? BRCCampObject { cellIdentifier = BRCDataObjectTableViewCell.cellIdentifier } return cellIdentifier } /** Short address e.g. 7:45 & G */ @objc public var shortBurnerMapAddress: String? { guard let string = self.burnerMapLocationString else { return nil } let components = string.components(separatedBy: " & ") guard let radial = components.first, let street = components.last, street.count > 1 else { return self.burnerMapLocationString } let index = street.index(street.startIndex, offsetBy: 1) let trimmedStreet = street[..<index] let shortAddress = "\(radial) & \(trimmedStreet)" return shortAddress } }
29e5193ca397c788b55668b4a4955854
38.711538
116
0.650847
false
false
false
false
richardpiazza/SOSwift
refs/heads/master
Sources/SOSwift/QuantitativeValue.swift
mit
1
import Foundation /// A point value or interval for product characteristics and other purposes. public class QuantitativeValue: StructuredValue { /// A property-value pair representing an additional characteristics of the entity. /// /// A product feature or another characteristic for which there is no matching property in schema.org. /// /// - note: Publishers should be aware that applications designed to use specific schema.org properties ( /// [http://schema.org/width](http://schema.org/width), /// [http://schema.org/color](http://schema.org/color), /// [http://schema.org/gtin13](http://schema.org/gtin13) /// ) will typically expect such data to be provided using those properties, rather than using the generic property/value mechanism. public var additionalProperty: PropertyValue? /// The upper value of some characteristic or property. public var maxValue: Number? /// The lower value of some characteristic or property. public var minValue: Number? /// The unit of measurement given using the UN/CEFACT Common Code (3 characters) or a URL. /// /// Other codes than the UN/CEFACT Common Code may be used with a prefix followed by a colon. public var unitCode: URLOrText? /// A string or text indicating the unit of measurement. Useful if you cannot provide a standard unit code for unitCode. public var unitText: String? /// The value of the quantitative value or property value node. /// /// - For QuantitativeValue and MonetaryAmount, the recommended type for values is 'Number'. /// - For PropertyValue, it can be 'Text;', 'Number', 'Boolean', or 'StructuredValue'. public var value: Value? /// A pointer to a secondary value that provides additional information on the original value /// /// ## For Example /// A reference temperature. public var valueReference: ValueReference? internal enum QuantitativeValueCodingKeys: String, CodingKey { case additionalProperty case maxValue case minValue case unitCode case unitText case value case valueReference } public override init() { super.init() } public required init(from decoder: Decoder) throws { try super.init(from: decoder) let container = try decoder.container(keyedBy: QuantitativeValueCodingKeys.self) additionalProperty = try container.decodeIfPresent(PropertyValue.self, forKey: .additionalProperty) maxValue = try container.decodeIfPresent(Number.self, forKey: .maxValue) minValue = try container.decodeIfPresent(Number.self, forKey: .minValue) unitCode = try container.decodeIfPresent(URLOrText.self, forKey: .unitText) unitText = try container.decodeIfPresent(String.self, forKey: .unitText) value = try container.decodeIfPresent(Value.self, forKey: .value) valueReference = try container.decodeIfPresent(ValueReference.self, forKey: .valueReference) } public override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: QuantitativeValueCodingKeys.self) try container.encodeIfPresent(additionalProperty, forKey: .additionalProperty) try container.encodeIfPresent(maxValue, forKey: .maxValue) try container.encodeIfPresent(minValue, forKey: .minValue) try container.encodeIfPresent(unitCode, forKey: .unitCode) try container.encodeIfPresent(unitText, forKey: .unitText) try container.encodeIfPresent(value, forKey: .value) try container.encodeIfPresent(valueReference, forKey: .valueReference) try super.encode(to: encoder) } }
9a0db50eab83a75da6911a4aa1eb0b4e
44.547619
144
0.689493
false
false
false
false
SlackKit/SKServer
refs/heads/main
SKServer/Sources/Middleware/MessageActionMiddleware.swift
mit
3
// // MessageActionMiddleware.swift // // Copyright © 2017 Peter Zignego. 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. public struct MessageActionMiddleware: Middleware { let token: String let routes: [MessageActionRoute] public init(token: String, routes: [MessageActionRoute]) { self.token = token self.routes = routes } public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { if let form = request.0.formURLEncodedBody.first(where: {$0.name == "ssl_check"}), form.value == "1" { return (request.0, Response(200)) } guard let actionRequest = MessageActionRequest(request: request.0), let middleware = routes.first(where: {$0.action.name == actionRequest.action?.name})?.middleware, actionRequest.token == token else { return (request.0, Response(400)) } return middleware.respond(to: request) } }
924f83df516dc63de1d1914979a41688
43.326087
110
0.703776
false
false
false
false
kasei/kineo
refs/heads/master
Sources/Kineo/QuadStore/SPARQLClientQuadStore.swift
mit
1
// // SPARQLClientQuadStore.swift // Kineo // // Created by Gregory Todd Williams on 6/6/18. // import Foundation import SPARQLSyntax // swiftlint:disable:next type_body_length open class SPARQLClientQuadStore: Sequence, QuadStoreProtocol { var client: SPARQLClient var defaultGraph: Term public init(endpoint: URL, defaultGraph: Term) { self.client = SPARQLClient(endpoint: endpoint) self.defaultGraph = defaultGraph } public var count: Int { if let r = try? client.execute("SELECT (COUNT(*) AS ?count) WHERE { { GRAPH ?g { ?s ?p ?o} } UNION { ?s ?p ?o } }") { if case .bindings(_, let rows) = r { return rows.count } } return 0 } public var graphsCount: Int { return Array(graphs()).count } public func graphs() -> AnyIterator<Term> { if let r = try? client.execute("SELECT ?g WHERE { GRAPH ?g {} }") { if case .bindings(_, let rows) = r { let graphs = rows.compactMap { $0["g"] } return AnyIterator(graphs.makeIterator()) } } return AnyIterator([].makeIterator()) } public func graphTerms(in graph: Term) -> AnyIterator<Term> { if let r = try? client.execute("SELECT DISTINCT ?t WHERE { GRAPH \(graph) { { ?t ?p ?o } UNION { ?s ?p ?t } }") { if case .bindings(_, let rows) = r { let graphs = rows.compactMap { $0["t"] } return AnyIterator(graphs.makeIterator()) } } return AnyIterator([].makeIterator()) } public func makeIterator() -> AnyIterator<Quad> { if let r = try? client.execute("SELECT * WHERE { { GRAPH ?g { ?s ?p ?o } } UNION { ?s ?p ?o } }") { if case .bindings(_, let rows) = r { let quads = rows.compactMap { (row) -> Quad? in if let s = row["s"], let p = row["p"], let o = row["o"] { if let g = row["g"] { return Quad(subject: s, predicate: p, object: o, graph: g) } else { return Quad(subject: s, predicate: p, object: o, graph: defaultGraph) } } return nil } return AnyIterator(quads.makeIterator()) } } return AnyIterator([].makeIterator()) } public func results(matching pattern: QuadPattern) throws -> AnyIterator<SPARQLResultSolution<Term>> { let query : String if pattern.graph == .bound(defaultGraph) { query = "SELECT * WHERE { \(pattern.subject) \(pattern.predicate) \(pattern.object) }" } else { query = "SELECT * WHERE { GRAPH \(pattern.graph) { \(pattern.subject) \(pattern.predicate) \(pattern.object) } }" } if let r = try? client.execute(query) { if case .bindings(_, let rows) = r { return AnyIterator(rows.makeIterator()) } } return AnyIterator([].makeIterator()) } public func quads(matching pattern: QuadPattern) throws -> AnyIterator<Quad> { var s = pattern.subject var p = pattern.predicate var o = pattern.object var g = pattern.graph if case .variable = s { s = .variable("s", binding: true) } if case .variable = p { p = .variable("p", binding: true) } if case .variable = o { o = .variable("o", binding: true) } if case .variable = g { g = .variable("g", binding: true) } let query: String if case .bound(defaultGraph) = g { query = "SELECT * WHERE { \(s) \(p) \(o) }" } else if case .bound(_) = g { query = "SELECT * WHERE { GRAPH \(g) { \(s) \(p) \(o) } }" // TODO: pull default graph also } else { query = """ SELECT * WHERE { { GRAPH \(g) { \(s) \(p) \(o) } } UNION { \(s) \(p) \(o) } } """ } if let r = try? client.execute(query) { if case .bindings(_, let rows) = r { let quads = rows.compactMap { (row) -> Quad? in var subj: Term var pred: Term var obj: Term var graph: Term if case .bound(let t) = s { subj = t } else if let s = row["s"] { subj = s } else { return nil } if case .bound(let t) = p { pred = t } else if let p = row["p"] { pred = p } else { return nil } if case .bound(let t) = o { obj = t } else if let o = row["o"] { obj = o } else { return nil } if case .bound(let t) = g { graph = t } else { graph = row["g"] ?? defaultGraph } return Quad(subject: subj, predicate: pred, object: obj, graph: graph) } return AnyIterator(quads.makeIterator()) } } return AnyIterator([].makeIterator()) } public func countQuads(matching pattern: QuadPattern) throws -> Int { var s = pattern.subject var p = pattern.predicate var o = pattern.object var g = pattern.graph if case .variable = s { s = .variable("s", binding: true) } if case .variable = p { p = .variable("p", binding: true) } if case .variable = o { o = .variable("o", binding: true) } if case .variable = g { g = .variable("g", binding: true) } let query: String if case .bound(defaultGraph) = g { query = "SELECT (COUNT(*) AS ?count) WHERE { \(s) \(p) \(o) }" } else if case .bound(_) = g { query = "SELECT (COUNT(*) AS ?count) WHERE { GRAPH \(g) { \(s) \(p) \(o) } }" // TODO: pull default graph also } else { query = """ SELECT (COUNT(*) AS ?count) WHERE { { GRAPH \(g) { \(s) \(p) \(o) } } UNION { \(s) \(p) \(o) } } """ } if let r = try? client.execute(query) { if case .bindings(_, let rows) = r { guard let row = rows.first, let count = row["count"] else { throw QueryError.evaluationError("Failed to get count of matching quads from endpoint") } return Int(count.numericValue) } } throw QueryError.evaluationError("Failed to get count of matching quads from endpoint") } public func effectiveVersion(matching pattern: QuadPattern) throws -> Version? { return nil } } extension SPARQLClientQuadStore : BGPQuadStoreProtocol { public func results(matching triples: [TriplePattern], in graph: Term) throws -> AnyIterator<SPARQLResultSolution<Term>> { let ser = SPARQLSerializer(prettyPrint: true) let bgp = try ser.serialize(.bgp(triples)) let query = "SELECT * WHERE { \(bgp) }" print("Evaluating BGP against \(client):\n\(query)") if let r = try? client.execute(query) { if case .bindings(_, let rows) = r { return AnyIterator(rows.makeIterator()) } } return AnyIterator([].makeIterator()) } } extension SPARQLClientQuadStore: CustomStringConvertible { public var description: String { return "SPARQLClientQuadStore <\(client.endpoint)>\n" } }
10c86c80d2f731d7c435c4d030879db8
36.814815
126
0.466577
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Pods/Down/Source/AST/Nodes/List.swift
mit
1
// // List.swift // Down // // Created by John Nguyen on 09.04.19. // import Foundation import libcmark public class List: BaseNode { public enum ListType: CustomDebugStringConvertible { case bullet case ordered(start: Int) public var debugDescription: String { switch self { case .bullet: return "Bullet" case .ordered(let start): return "Ordered (start: \(start)" } } init?(cmarkNode: CMarkNode) { switch cmarkNode.listType { case CMARK_BULLET_LIST: self = .bullet case CMARK_ORDERED_LIST: self = .ordered(start: cmarkNode.listStart) default: return nil } } } /////////////////////////////////////////////////////////////////////////// /// The type of the list, either bullet or ordered. public lazy var listType: ListType = { guard let type = ListType(cmarkNode: cmarkNode) else { assertionFailure("Unsupported or missing list type. Defaulting to .bullet.") return .bullet } return type }() /// The number of items in the list. public lazy var numberOfItems: Int = children.count } // MARK: - Debug extension List: CustomDebugStringConvertible { public var debugDescription: String { return "List - type: \(listType)" } }
02cf463b15977e1570a9fe746fb124fa
24.210526
88
0.542102
false
false
false
false
wanglei8441226/FightingFish
refs/heads/master
FightingFish/FightingFish/Classes/Home/HomeViewController.swift
mit
1
// // HomeViewController.swift // FightingFish // // Created by 王磊 on 2017/3/6. // Copyright © 2017年 王磊. All rights reserved. // import UIKit fileprivate var titleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK: - 懒加载属性 fileprivate lazy var pageTitleView: PageTitleView = {[weak self] in let pageFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: titleViewH) let pageTitleView = PageTitleView(frame: pageFrame, titles: ["推荐", "手游", "娱乐", "游戏","趣玩"]) pageTitleView.delegate = self return pageTitleView }() fileprivate lazy var pageContentView: PageContentView = { [weak self] in let pageY :CGFloat = kStatusBarH + kNavigationBarH + titleViewH let pageH:CGFloat = kScreenH - pageY let pageContentFrame = CGRect(x: 0, y: pageY, width: kScreenW, height: pageH) var childers = [UIViewController]() for _ in 0..<5{ let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childers.append(vc) } let content = PageContentView(frame: pageContentFrame, childControllers: childers, parentController: self) return content }() // MARK: - 父类方法 override func viewDidLoad() { super.viewDidLoad() // 1.初始化UI customUI() } } // MARK: - View相关 extension HomeViewController{ fileprivate func customUI(){ // 0.不需要自动偏移 automaticallyAdjustsScrollViewInsets = false // 1.设置导航栏按钮 setUpNavigationBar() // 2.添加pageTitleView view.addSubview(pageTitleView) // 3.添加pageContentView view.addSubview(pageContentView) } fileprivate func setUpNavigationBar(){ // 1.设置左侧的BarButtonItem navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2.设置右侧的BarButtonItem let size = CGSize(width: 40, height: 40) let history = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let scan = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size) let search = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size) navigationItem.rightBarButtonItems = [search, scan, history ] } } // MARK: - pageTitleDelegate extension HomeViewController: PageTitleViewDelegate{ func pageTitleViewScrollLine(_ titleView: PageTitleView, seletedInde index: Int) { print(index) pageContentView.pageContenViewScrollIndex(index) } }
81a552ba4af29967165db976f997b514
36.148649
156
0.662059
false
false
false
false
bitboylabs/selluv-ios
refs/heads/master
selluv-ios/selluv-ios/Classes/Base/Extension/String.swift
mit
1
// // String.swift // selluv-ios // // Created by 조백근 on 2016. 12. 29.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import Foundation import UIKit extension String { private struct AssociatedKey { static var indexTagKey = "String.Associated.indexTagKey" } public var indexTag: Int { get { if let value = objc_getAssociatedObject(self, &AssociatedKey.indexTagKey) as? Int { return value } return 0 } set { objc_setAssociatedObject(self, &AssociatedKey.indexTagKey, newValue, .OBJC_ASSOCIATION_RETAIN) } } var isAlphanumeric: Bool { return range(of: "^[a-zA-Z0-9!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?~`]+$", options: .regularExpression) != nil } var hangul: String { get { let hangle = [ ["ㄱ","ㄲ","ㄴ","ㄷ","ㄸ","ㄹ","ㅁ","ㅂ","ㅃ","ㅅ","ㅆ","ㅇ","ㅈ","ㅉ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"], ["ㅏ","ㅐ","ㅑ","ㅒ","ㅓ","ㅔ","ㅕ","ㅖ","ㅗ","ㅘ","ㅙ","ㅚ","ㅛ","ㅜ","ㅝ","ㅞ","ㅟ","ㅠ","ㅡ","ㅢ","ㅣ"], ["","ㄱ","ㄲ","ㄳ","ㄴ","ㄵ","ㄶ","ㄷ","ㄹ","ㄺ","ㄻ","ㄼ","ㄽ","ㄾ","ㄿ","ㅀ","ㅁ","ㅂ","ㅄ","ㅅ","ㅆ","ㅇ","ㅈ","ㅊ","ㅋ","ㅌ","ㅍ","ㅎ"] ] return characters.reduce("") { result, char in if case let code = Int(String(char).unicodeScalars.reduce(0){$0.0 + $0.1.value}) - 44032, code > -1 && code < 11172 { let cho = code / 21 / 28, jung = code % (21 * 28) / 28, jong = code % 28; return result + hangle[0][cho] + hangle[1][jung] + hangle[2][jong] } return result + String(char) } } } public static func decimalAmountWithForm(value: Float, pointCount: Int) -> String { let point = (pointCount > 0) ? Int(Array(1...pointCount).map{_ in 10}.reduce(10, *)) : 1 //pointCount 만큽 10의 제곱승을 만들어서 살려둘 자리수 만큼 곱하고 라운드 후 다시 나눈다. let amount = round(value * Float(point)) / Float(point) //반올림 let commaValue = NumberFormatter.localizedString(from: NSNumber(value: amount), number: NumberFormatter.Style.decimal) return commaValue } public static func removeFormAmount(value: String) -> String { let formatter = NumberFormatter() formatter.locale = NSLocale.current formatter.numberStyle = NumberFormatter.Style.decimal formatter.decimalSeparator = "," let amount = formatter.number(from: value) ?? 0 let famount = amount.floatValue return famount.cleanValue } }
50fb4f62b7a7bfc58ac0f8b4412a44a7
36.970588
155
0.520139
false
false
false
false
Chaosspeeder/YourGoals
refs/heads/master
YourGoals/UI/Views/Progress Indicators/ProgressIndicatorView.swift
lgpl-3.0
1
// // ProgressIndicatorView.swift // YourGoals // // Created by André Claaßen on 27.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import UIKit import PNChart enum ProgressIndicatorViewMode { case normal case mini } /// a circle progress indicator class ProgressIndicatorView: UIView { var viewMode = ProgressIndicatorViewMode.normal var progressView:PieProgressView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { self.backgroundColor = UIColor.clear self.progressView = PieProgressView(frame: self.bounds) self.addSubview(progressView) } func setProgress(progress:Double, progressIndicator:ProgressIndicator) { let color = calculateColor(fromIndicator: progressIndicator) self.progressView.progressTintColor = color self.progressView.trackTintColor = color self.progressView.fillColor = color.withAlphaComponent(0.3) self.progressView.progress = CGFloat(progress) } /// show the progress of the goal as a colored circle /// - Parameters: /// - goal: the goal /// - date: calculation of progress for this date /// - manager: a manager to retrieve actual data from the core data sotre /// - Throws: core data exception func setProgress(forGoal goal:Goal, forDate date: Date, withBackburned backburnedGoals:Bool, manager: GoalsStorageManager) throws { let calculator = GoalProgressCalculator(manager: manager) let progress = try calculator.calculateProgress(forGoal: goal, forDate: date, withBackburned: backburnedGoals) self.setProgress(progress: progress.progress, progressIndicator: progress.indicator) } /// convert the progress indicator to a traffic color /// /// - Parameter progressIndicator: the progress indicator /// - Returns: a color represnetation the state of the progress func calculateColor(fromIndicator progressIndicator: ProgressIndicator) -> UIColor { switch progressIndicator { case .met: return UIColor.green case .ahead: return UIColor.blue case .onTrack: return UIColor.green case .lagging: return UIColor.orange case .behind: return UIColor.red case .notStarted: return UIColor.lightGray } } override func layoutSubviews() { super.layoutSubviews() } }
31d3e7db8f98268334fcc52034c6c23c
29.852273
135
0.648987
false
false
false
false
HeMet/LSSTools
refs/heads/master
Sources/ifconvert/Driver.swift
mit
1
// // Driver.swift // LSS // // Created by Evgeniy Gubin on 05.02.17. // // import Foundation class Driver { let fileManager: FileManagerProtocol = FileManager.default; let converter = ItemFilterConverter() func run(args: [String]) throws { guard args.count > 1 else { print("ifconvert <input file> [output file]") return; } let inputFile = args[1]; let outputFile = (args.count > 2) ? args[2] : inputFile.replacingExtension(with: "lss") let input = try fileManager.readString(file: inputFile) let output = try converter.convert(itemFilter: input) try fileManager.write(string: output, to: outputFile) } }
4a481e6e1359434965aed8af2fdc0520
24.344828
95
0.602721
false
false
false
false
xmartlabs/Opera
refs/heads/master
Example/Example/Controllers/RepositoryIssuesController.swift
mit
1
// RepositoryIssuesController.swift // Example-iOS ( https://github.com/xmartlabs/Example-iOS ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import OperaSwift import RxSwift import RxCocoa class IssuesFilter { enum State: Int, CustomStringConvertible { case open case closed case all var description: String { switch self { case .open: return "open" case .closed: return "closed" case .all: return "all" } } } enum Sort: Int, CustomStringConvertible { case created case updated case comments var description: String { switch self { case .created: return "created" case .updated: return "updated" case .comments: return "comments" } } } enum Direction: Int, CustomStringConvertible { case ascendant case descendant var description: String { switch self { case .ascendant: return "asc" case .descendant: return "desc" } } } var state = State.open var sortBy = Sort.created var sortDirection = Direction.descendant var issueCreator: String? var userMentioned: String? } extension IssuesFilter: FilterType { var parameters: [String: AnyObject]? { var baseParams = ["state": "\(state)", "sort": "\(sortBy)", "direction": "\(sortDirection)"] if let issueCreator = issueCreator, !issueCreator.isEmpty { baseParams["creator"] = issueCreator } if let userMentioned = userMentioned, !userMentioned.isEmpty { baseParams["mentioned"] = userMentioned } return baseParams as [String : AnyObject]? } } class RepositoryIssuesController: RepositoryBaseController { @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! let refreshControl = UIRefreshControl() var disposeBag = DisposeBag() fileprivate var filter = Variable<IssuesFilter>(IssuesFilter()) lazy var viewModel: PaginationViewModel<PaginationRequest<Issue>> = { [unowned self] in return PaginationViewModel(paginationRequest: PaginationRequest(route: GithubAPI.Repository.GetIssues(owner: self.owner, repo: self.name), filter: self.filter.value)) }() override func viewDidLoad() { super.viewDidLoad() tableView.keyboardDismissMode = .onDrag tableView.addSubview(self.refreshControl) emptyStateLabel.text = "No issues found" let refreshControl = self.refreshControl rx.sentMessage(#selector(RepositoryForksController.viewWillAppear(_:))) .map { _ in false } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) tableView.rx.reachedBottom .bind(to: viewModel.loadNextPageTrigger) .disposed(by: disposeBag) viewModel.loading .drive(activityIndicatorView.rx.isAnimating) .disposed(by: disposeBag) Driver.combineLatest(viewModel.elements.asDriver(), viewModel.firstPageLoading) { elements, loading in return loading ? [] : elements } .asDriver() .drive(tableView.rx.items(cellIdentifier:"Cell")) { _, issue, cell in cell.textLabel?.text = issue.title cell.detailTextLabel?.text = " #\(issue.number)" } .disposed(by: disposeBag) refreshControl.rx.valueChanged .filter { refreshControl.isRefreshing } .map { true } .bind(to: viewModel.refreshTrigger) .disposed(by: disposeBag) viewModel.loading .filter { !$0 && refreshControl.isRefreshing } .drive(onNext: { _ in refreshControl.endRefreshing() }) .disposed(by: disposeBag) filter .asObservable() .map { $0 } .bind(to: viewModel.filterTrigger) .disposed(by: disposeBag) viewModel.emptyState .drive(onNext: { [weak self] emptyState in self?.emptyStateLabel.isHidden = !emptyState }) .disposed(by: disposeBag) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let vc = (segue.destination as? UINavigationController)?.topViewController as? RepositoryIssueFilterController else { return } vc.filter = filter } }
a10167332876717e78e3cb0f4b4d703a
32.136905
174
0.649362
false
false
false
false
CodaFi/swift
refs/heads/master
test/Serialization/comments-hidden.swift
apache-2.0
7
// Test the case when we compile normally // // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %s // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.normal.txt // RUN: %FileCheck %s -check-prefix=NORMAL < %t.normal.txt // RUN: %FileCheck %s -check-prefix=NORMAL-NEGATIVE < %t.normal.txt // Test the case when we compile with -enable-testing // // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -enable-testing -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc %s // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -source-filename %s -I %t > %t.testing.txt // RUN: %FileCheck %s -check-prefix=TESTING < %t.testing.txt // RUN: %FileCheck %s -check-prefix=TESTING-NEGATIVE < %t.testing.txt // Test the case when we have .swiftsourceinfo // // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -enable-testing -module-name comments -emit-module -emit-module-path %t/comments.swiftmodule -emit-module-doc -emit-module-doc-path %t/comments.swiftdoc -emit-module-source-info-path %t/comments.swiftsourceinfo %s // RUN: %target-swift-ide-test -print-module-comments -module-to-print=comments -enable-swiftsourceinfo -source-filename %s -I %t > %t.testing.txt // RUN: %FileCheck %s -check-prefix=SOURCE-LOC < %t.testing.txt /// PublicClass Documentation public class PublicClass { /// Public Function Documentation public func f_public() { } /// Public Init Documentation public init(_ name: String) {} /// Public Subscript Documentation public subscript(_ name: String) -> Int { return 0 } /// Internal Function Documentation NotForNormal internal func f_internal() { } /// Private Function Documentation NotForNormal NotForTesting private func f_private() { } /// Public Filter Function Documentation NotForNormal NotForTesting public func __UnderscoredPublic() {} /// Public Filter Init Documentation NotForNormal NotForTesting public init(__label name: String) {} /// Public Filter Subscript Documentation NotForNormal NotForFiltering public subscript(__label name: String) -> Int { return 0 } /// Public Filter Init Documentation NotForNormal NotForTesting public init(label __name: String) {} /// Public Filter Subscript Documentation NotForNormal NotForTesting public subscript(label __name: String) -> Int { return 0 } /// SPI Function Documentation NotForNormal NotForTesting @_spi(SPI) public func f_spi() { } } public extension PublicClass { /// Public Filter Operator Documentation NotForNormal NotForTesting static func -=(__lhs: inout PublicClass, __rhs: PublicClass) {} } /// InternalClass Documentation NotForNormal internal class InternalClass { /// Internal Function Documentation NotForNormal internal func f_internal() { } /// Private Function Documentation NotForNormal NotForTesting private func f_private() { } } /// PrivateClass Documentation NotForNormal NotForTesting private class PrivateClass { /// Private Function Documentation NotForNormal NotForTesting private func f_private() { } } /// SPI Documentation NotForNormal NotForTesting @_spi(SPI) public class SPIClass { /// SPI Function Documentation NotForNormal NotForTesting public func f_spi() { } } /// SPI Extension Documentation NotForNormal NotForTesting @_spi(SPI) public extension PublicClass { } // NORMAL-NEGATIVE-NOT: NotForNormal // NORMAL-NEGATIVE-NOT: NotForTesting // NORMAL: PublicClass Documentation // NORMAL: Public Function Documentation // NORMAL: Public Init Documentation // NORMAL: Public Subscript Documentation // TESTING-NEGATIVE-NOT: NotForTesting // TESTING: PublicClass Documentation // TESTING: Public Function Documentation // TESTING: Public Init Documentation // TESTING: Public Subscript Documentation // TESTING: Internal Function Documentation // TESTING: InternalClass Documentation // TESTING: Internal Function Documentation // SOURCE-LOC: comments-hidden.swift:37:15: Func/PublicClass.__UnderscoredPublic RawComment=none BriefComment=none DocCommentAsXML=none // SOURCE-LOC: comments-hidden.swift:39:10: Constructor/PublicClass.init RawComment=none BriefComment=none DocCommentAsXML=none // SOURCE-LOC: comments-hidden.swift:41:10: Subscript/PublicClass.subscript RawComment=none BriefComment=none DocCommentAsXML=none // SOURCE-LOC: comments-hidden.swift:43:10: Constructor/PublicClass.init RawComment=none BriefComment=none DocCommentAsXML=none // SOURCE-LOC: comments-hidden.swift:45:10: Subscript/PublicClass.subscript RawComment=none BriefComment=none DocCommentAsXML=none // SOURCE-LOC: comments-hidden.swift:52:15: Func/-= RawComment=none BriefComment=none DocCommentAsXML=none
b1ad9b8f7a5db48f6098054490060f4d
48.16
244
0.763019
false
true
false
false
googlearchive/science-journal-ios
refs/heads/master
ScienceJournal/SensorData/GetTrialSensorDumpOperation.swift
apache-2.0
1
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import third_party_sciencejournal_ios_ScienceJournalProtos /// An operation that fetches data for a single trial sensor and converts it into a sensor data /// dump proto. class GetTrialSensorDumpOperation: GSJOperation { private let sensorDataManager: SensorDataManager private let trialID: String private let sensorID: String /// When the operation completes successfully this will contain the sensor data dump. var dump: GSJScalarSensorDataDump? /// Designated initializer. /// /// - Parameters: /// - sensorDataManager: A sensor data manager. /// - trialID: A trial ID. /// - sensorID: A sensor ID. init(sensorDataManager: SensorDataManager, trialID: String, sensorID: String) { self.sensorDataManager = sensorDataManager self.trialID = trialID self.sensorID = sensorID } override func execute() { sensorDataManager.fetchSensorData( forSensorID: sensorID, trialID: trialID, completion: { (dataPoints) in guard let dataPoints = dataPoints, dataPoints.count > 0 else { self.finish(withErrors: [SensorDataExportError.failedToFetchDatabaseSensorData(self.trialID, self.sensorID)]) return } var rows = [GSJScalarSensorDataRow]() for dataPoint in dataPoints { let row = GSJScalarSensorDataRow() row.timestampMillis = dataPoint.x row.value = dataPoint.y rows.append(row) } let sensorDump = GSJScalarSensorDataDump() sensorDump.tag = self.sensorID sensorDump.trialId = self.trialID sensorDump.rowsArray = NSMutableArray(array: rows) self.dump = sensorDump self.finish() }) } }
3585dff919b7b3a7851a53c8b964d7e3
32.026667
95
0.660073
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/ViewControllers/ViewControllerTransitions/PinTransitioningDelegate.swift
mit
1
// // PinTransitioningDelegate.swift // breadwallet // // Created by Adrian Corscadden on 2017-05-05. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit private let duration: TimeInterval = 0.4 class PinTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { var shouldShowMaskView = true func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return PresentPinAnimator(shouldShowMaskView: shouldShowMaskView) } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DismissPinAnimator() } } class PresentPinAnimator: NSObject, UIViewControllerAnimatedTransitioning { init(shouldShowMaskView: Bool) { self.shouldShowMaskView = shouldShowMaskView } private let shouldShowMaskView: Bool func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let duration = transitionDuration(using: transitionContext) let container = transitionContext.containerView guard let toView = transitionContext.view(forKey: .to) else { return } guard let toVc = transitionContext.viewController(forKey: .to) as? ContentBoxPresenter else { return } let blurView = toVc.blurView blurView.frame = container.frame blurView.effect = nil container.addSubview(blurView) let fromFrame = container.frame let maskView = UIView(frame: CGRect(x: 0, y: fromFrame.height, width: fromFrame.width, height: 40.0)) maskView.backgroundColor = .whiteTint if shouldShowMaskView { container.addSubview(maskView) } let scaleFactor: CGFloat = 0.1 let deltaX = toVc.contentBox.frame.width * (1-scaleFactor) let deltaY = toVc.contentBox.frame.height * (1-scaleFactor) let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) toVc.contentBox.transform = scale.translatedBy(x: -deltaX, y: deltaY/2.0) let finalToViewFrame = toView.frame toView.frame = toView.frame.offsetBy(dx: 0, dy: toView.frame.height) container.addSubview(toView) UIView.spring(duration, animations: { maskView.frame = CGRect(x: 0, y: fromFrame.height - 30.0, width: fromFrame.width, height: 40.0) blurView.effect = toVc.effect toView.frame = finalToViewFrame toVc.contentBox.transform = .identity }, completion: { _ in maskView.removeFromSuperview() transitionContext.completeTransition(true) }) } } class DismissPinAnimator: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let duration = transitionDuration(using: transitionContext) guard let fromView = transitionContext.view(forKey: .from) else { assert(false, "Missing from view"); return } guard let fromVc = transitionContext.viewController(forKey: .from) as? ContentBoxPresenter else { return } UIView.animate(withDuration: duration, animations: { fromVc.blurView.effect = nil fromView.frame = fromView.frame.offsetBy(dx: 0, dy: fromView.frame.height) let scaleFactor: CGFloat = 0.1 let deltaX = fromVc.contentBox.frame.width * (1-scaleFactor) let deltaY = fromVc.contentBox.frame.height * (1-scaleFactor) let scale = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor) fromVc.contentBox.transform = scale.translatedBy(x: -deltaX, y: deltaY/2.0) }, completion: { _ in transitionContext.completeTransition(true) }) } }
a902fc4b0a780712ab501cbc6a312d2a
39.637255
170
0.701809
false
false
false
false
omiz/CarBooking
refs/heads/master
CarBooking/AppDelegate.swift
mit
1
// // AppDelegate.swift // CarBooking // // Created by Omar Allaham on 10/18/17. // Copyright © 2017 Omar Allaham. All rights reserved. // import UIKit import Reachability import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? let reachability = Reachability() var internetAlert: UIAlertController? var tabBarController: TabBarController? { return window?.rootViewController as? TabBarController } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UNUserNotificationCenter.current().delegate = self ThemeManager.apply() setupReachability() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { guard response.notification.request.content.categoryIdentifier.starts(with: Booking.notificationId) else { return completionHandler() } UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber - 1 let userInfo = response.notification.request.content.userInfo guard let id = userInfo["id"] as? Int else { return completionHandler() } goToBookingDetail(with: id) completionHandler() } func goToBookingDetail(with id: Int) { let item = tabBarController?.viewControllers?.enumerated().first(where: { guard let controller = $0.element as? UINavigationController else { return false } return controller.viewControllers.first is BookedVehiclesViewController }) (item?.element as? UINavigationController)?.popToRootViewController(animated: true) let index = item?.offset ?? 0 let controller = item?.element.childViewControllers.first as? BookedVehiclesViewController tabBarController?.selectedIndex = index let booking = controller?.dataSource.enumerated().first(where: { $0.element.id == id }) if let booking = booking { controller?.showDetail(for: booking.element.id) } } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let identifier = Bundle.main.bundleIdentifier ?? "" switch shortcutItem.type { case identifier + ".allVehicles": tabBarController?.showAllVehiclesTab() case identifier + ".myBooking": tabBarController?.showMyBookingsTab() case identifier + ".contacts": tabBarController?.showContactsTab() default: break } completionHandler(true) } func setupReachability() { guard let reachability = reachability else { return } NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability) try? reachability.startNotifier() } @objc func reachabilityChanged(_ notification: Notification) { guard let reachability = notification.object as? Reachability else { return } switch reachability.connection { case .wifi: reachableInternet() case .cellular: reachableInternet() case .none: alertNoInternet() } } func alertNoInternet() { let alert = UIAlertController.init(title: "Alert".localized, message: "Internet is lost.\nPlease check your internet connection!".localized, preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Ok".localized, style: .default, handler: nil)) window?.rootViewController?.present(alert, animated: true, completion: { self.internetAlert = alert }) } func reachableInternet() { internetAlert?.dismiss(animated: true) } }
2287571bc6bfb4ca081382f15e21253e
38.777778
285
0.66077
false
false
false
false
andrewcar/hoods
refs/heads/master
Project/hoods/hoods/HoodView.swift
mit
1
// // HoodView.swift // hoods // // Created by Andrew Carvajal on 9/22/17. // Copyright © 2017 YugeTech. All rights reserved. // import UIKit class HoodView: UIView { var closedHoodConstraints = [NSLayoutConstraint]() var openHoodConstraints = [NSLayoutConstraint]() let primaryLabel = UILabel() let secondaryLabel = UILabel() let weatherLabel = UILabel() var composeView = ComposeView() var button = UIButton() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white let labels = [primaryLabel, secondaryLabel, weatherLabel] for label in labels { label.translatesAutoresizingMaskIntoConstraints = false label.adjustsFontSizeToFitWidth = true label.numberOfLines = 0 } primaryLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 100) primaryLabel.textAlignment = .center primaryLabel.textColor = UIColor(red: 142/255, green: 68/255, blue: 173/255, alpha: 1) primaryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 150), for: .vertical) secondaryLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 50) secondaryLabel.textAlignment = .right secondaryLabel.textColor = UIColor(red: 46/255, green: 204/255, blue: 113/255, alpha: 1) secondaryLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 151), for: .vertical) weatherLabel.font = UIFont(name: Fonts.HelveticaNeue.bold, size: 50) weatherLabel.textAlignment = .left weatherLabel.textColor = .peterRiver weatherLabel.text = "🤷🏻‍♂️" composeView = ComposeView(frame: CGRect.zero) composeView.translatesAutoresizingMaskIntoConstraints = false composeView.textView.text = "blah blah blah" button.translatesAutoresizingMaskIntoConstraints = false addSubview(primaryLabel) addSubview(secondaryLabel) addSubview(weatherLabel) addSubview(composeView) addSubview(button) activateClosedConstraints() } func activateClosedConstraints() { NSLayoutConstraint.deactivate(closedHoodConstraints) NSLayoutConstraint.deactivate(openHoodConstraints) closedHoodConstraints = [ primaryLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), primaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5), primaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5), primaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.6), secondaryLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0), secondaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: 20), secondaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -20), secondaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2), weatherLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0), weatherLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 20), weatherLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: -20), weatherLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2), composeView.topAnchor.constraint(equalTo: weatherLabel.bottomAnchor, constant: Frames.si.padding), composeView.leftAnchor.constraint(equalTo: leftAnchor, constant: Frames.si.padding), composeView.rightAnchor.constraint(equalTo: rightAnchor, constant: -Frames.si.padding), composeView.heightAnchor.constraint(equalToConstant: Frames.si.buttonSize.height + 8), button.topAnchor.constraint(equalTo: topAnchor), button.leftAnchor.constraint(equalTo: leftAnchor), button.rightAnchor.constraint(equalTo: rightAnchor), button.bottomAnchor.constraint(equalTo: bottomAnchor), ] NSLayoutConstraint.activate(closedHoodConstraints) } func activateOpenConstraints() { NSLayoutConstraint.deactivate(closedHoodConstraints) NSLayoutConstraint.deactivate(openHoodConstraints) openHoodConstraints = [ primaryLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor), primaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 5), primaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -5), primaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.6), secondaryLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0), secondaryLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: 20), secondaryLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor, constant: -20), secondaryLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2), weatherLabel.topAnchor.constraint(equalTo: primaryLabel.bottomAnchor, constant: 0), weatherLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor, constant: 20), weatherLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor, constant: -20), weatherLabel.heightAnchor.constraint(equalToConstant: Frames.si.hoodViewClosedSize.height * 0.2), composeView.topAnchor.constraint(equalTo: weatherLabel.bottomAnchor, constant: Frames.si.padding), composeView.leftAnchor.constraint(equalTo: leftAnchor, constant: Frames.si.padding), composeView.rightAnchor.constraint(equalTo: rightAnchor, constant: -Frames.si.padding), composeView.heightAnchor.constraint(equalToConstant: Frames.si.buttonSize.height + 8), button.topAnchor.constraint(equalTo: topAnchor), button.leftAnchor.constraint(equalTo: leftAnchor), button.rightAnchor.constraint(equalTo: rightAnchor), button.bottomAnchor.constraint(equalTo: bottomAnchor), ] NSLayoutConstraint.activate(openHoodConstraints) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
75e87368c00960d110118ba01e8e44b1
49.151079
111
0.6966
false
false
false
false
kickstarter/ios-oss
refs/heads/main
KsApi/models/lenses/User.NewsletterSubscriptionsLenses.swift
apache-2.0
1
import Prelude extension User.NewsletterSubscriptions { public enum lens { public static let arts = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.arts }, set: { User.NewsletterSubscriptions( arts: $0, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let games = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.games }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $0, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let happening = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.happening }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $0, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let invent = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.invent }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $0, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let promo = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.promo }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $0, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let weekly = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.weekly }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $0, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let films = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.films }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $0, publishing: $1.publishing, alumni: $1.alumni, music: $1.music ) } ) public static let publishing = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.publishing }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $0, alumni: $1.alumni, music: $1.music ) } ) public static let alumni = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.alumni }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $0, music: $1.music ) } ) public static let music = Lens<User.NewsletterSubscriptions, Bool?>( view: { $0.music }, set: { User.NewsletterSubscriptions( arts: $1.arts, games: $1.games, happening: $1.happening, invent: $1.invent, promo: $1.promo, weekly: $1.weekly, films: $1.films, publishing: $1.publishing, alumni: $1.alumni, music: $0 ) } ) } }
546563dedf5409a4e7dce2acafa83da7
25.266667
77
0.529303
false
false
false
false
SwiftGFX/SwiftMath
refs/heads/master
Sources/Vector3+nosimd.swift
bsd-2-clause
1
// // Vector3f+nosimd.swift // SwiftMath // // Created by Andrey Volodin on 07.10.16. // // #if NOSIMD #if (os(OSX) || os(iOS) || os(tvOS) || os(watchOS)) import Darwin #elseif os(Linux) || os(Android) import Glibc #endif @frozen public struct Vector3f { public var x: Float = 0.0 public var y: Float = 0.0 public var z: Float = 0.0 public var r: Float { get { return x } set { x = newValue } } public var g: Float { get { return y } set { y = newValue } } public var b: Float { get { return z } set { z = newValue } } public var s: Float { get { return x } set { x = newValue } } public var t: Float { get { return y } set { y = newValue } } public var p: Float { get { return z } set { z = newValue } } public subscript(x: Int) -> Float { get { if x == 0 { return self.x } if x == 1 { return self.y } if x == 2 { return self.z } fatalError("Index outside of bounds") } set { if x == 0 { self.x = newValue; return } if x == 1 { self.y = newValue; return } if x == 2 { self.z = newValue; return } fatalError("Index outside of bounds") } } public init() {} public init(_ x: Float, _ y: Float, _ z: Float) { self.x = x self.y = y self.z = z } public init(_ scalar: Float) { self.init(scalar, scalar, scalar) } public init(x: Float, y: Float, z: Float) { self.init(x, y, z) } } extension Vector3f { public var lengthSquared: Float { return x * x + y * y + z * z } public var length: Float { return sqrt(self.lengthSquared) } public func dot(_ v: Vector3f) -> Float { return x * v.x + y * v.y + z * v.z } public func cross(_ v: Vector3f) -> Vector3f { return Vector3f(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x) } public var normalized: Vector3f { let lengthSquared = self.lengthSquared if lengthSquared ~= 0 || lengthSquared ~= 1 { return self } return self / sqrt(lengthSquared) } public func interpolated(with v: Vector3f, by t: Float) -> Vector3f { return self + (v - self) * t } public static prefix func -(v: Vector3f) -> Vector3f { return Vector3f(-v.x, -v.y, -v.z) } public static func +(lhs: Vector3f, rhs: Vector3f) -> Vector3f { return Vector3f(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z) } public static func -(lhs: Vector3f, rhs: Vector3f) -> Vector3f { return Vector3f(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) } public static func *(lhs: Vector3f, rhs: Vector3f) -> Vector3f { return Vector3f(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z) } public static func *(lhs: Vector3f, rhs: Float) -> Vector3f { return Vector3f(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs) } public static func /(lhs: Vector3f, rhs: Vector3f) -> Vector3f { return Vector3f(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z) } public static func /(lhs: Vector3f, rhs: Float) -> Vector3f { return Vector3f(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs) } public static func ~=(lhs: Vector3f, rhs: Vector3f) -> Bool { return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z } public static func *(lhs: Vector3f, rhs: Matrix3x3f) -> Vector3f { return Vector3f( lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31, lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32, lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33 ) } public static func *(lhs: Matrix3x3f, rhs: Vector3f) -> Vector3f { return rhs * lhs } } extension Vector3f: Equatable { public static func ==(lhs: Vector3f, rhs: Vector3f) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } } #endif
29e88b54976feace11e6c5a3d7fe0eb1
27.368056
80
0.521175
false
false
false
false
kevinhankens/runalysis
refs/heads/master
Runalysis/RockerStepper.swift
mit
1
// // RockerStepper.swift // Runalysis // // Created by Kevin Hankens on 7/14/14. // Copyright (c) 2014 Kevin Hankens. All rights reserved. // import Foundation import UIKit /*! * @class RockerStepper * * This is a custom implementation of a UIStepper which provides defaults * as well as custom formatting for the value. */ class RockerStepper: UIStepper { /*! * Constructor. * * @param CGRect frame */ override init(frame: CGRect) { super.init(frame: frame) minimumValue = 0.0 maximumValue = 100.0 stepValue = 0.25 autorepeat = true } required init(coder aDecoder: NSCoder) { //fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) } /*! * Gets a custom label based upon the internal value. * * @param Double miles * * @return String */ class func getLabel(miles:Double)->String { var mval = Int(miles) var dval = Int(round((miles - Double(mval)) * 100)) var dtext = "\(dval)" if dval < 10 { dtext = "0\(dval)" } //var numerator = Int(4.0 * rval) // //var fraction = "" //switch numerator { //case 1.0: // fraction = "¼" //case 2.0: // fraction = "½" //case 3.0: // fraction = "¾" //default: // fraction = "" //} return "\(Int(miles)).\(dtext)" } }
2dd2fa2465422b6bb4cc2cacbc2bab69
21.367647
73
0.520053
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Controllers/Preferences/ChangeAppIcon/ChangeAppIconCell.swift
mit
1
// // ChangeAppIconCell.swift // Rocket.Chat // // Created by Artur Rymarz on 08.02.2018. // Copyright © 2018 Rocket.Chat. All rights reserved. // import UIKit final class ChangeAppIconCell: UICollectionViewCell { @IBOutlet private weak var iconImageView: UIImageView! { didSet { iconImageView.isAccessibilityElement = true } } @IBOutlet private weak var checkImageView: UIImageView! @IBOutlet private weak var checkImageViewBackground: UIView! func setIcon(name: (String, String), selected: Bool) { iconImageView.image = UIImage(named: name.0) iconImageView.accessibilityLabel = VOLocalizedString(name.1) if selected { iconImageView.layer.borderColor = UIColor.RCBlue().cgColor iconImageView.layer.borderWidth = 3 iconImageView.accessibilityTraits = .selected checkImageView.image = checkImageView.image?.imageWithTint(UIColor.RCBlue()) checkImageView.isHidden = false checkImageViewBackground.isHidden = false } else { iconImageView.layer.borderColor = UIColor.RCLightGray().cgColor iconImageView.layer.borderWidth = 1 iconImageView.accessibilityTraits = .none checkImageView.isHidden = true checkImageViewBackground.isHidden = true } } }
e46eef6e44080d2d0c8be9077a780975
31.023256
88
0.668119
false
false
false
false
shamanskyh/FluidQ
refs/heads/master
FluidQ/Magic Sheet/InstrumentGroup.swift
mit
1
// // InstrumentGroup.swift // FluidQ // // Created by Harry Shamansky on 11/16/15. // Copyright © 2015 Harry Shamansky. All rights reserved. // import UIKit class InstrumentGroup: NSObject { var instruments: [[Instrument]] { didSet { var lowestChannel: Int? for row in instruments { for instrument in row { if let channel = instrument.channel where channel < lowestChannel || lowestChannel == nil { lowestChannel = channel } } } if let lowest = lowestChannel { startingChannelNumber = lowest } else { startingChannelNumber = Int.max } } } var purpose: String? var startingChannelNumber: Int = Int.max init(withInstruments instruments: [Instrument], purpose: String?) { var yPositions: [Double] = [] var groupedInstruments: [[Instrument]] = [] let filteredInstruments = instruments.filter({ $0.location != nil }) for i in 0..<filteredInstruments.count { if yPositions.count == 0 { yPositions.append(filteredInstruments[i].location!.y) groupedInstruments.append([filteredInstruments[i]]) } else { var foundMatch = false for j in 0..<yPositions.count { if abs(filteredInstruments[i].location!.y - yPositions[j]) < kMagicSheetRowThreshold { groupedInstruments[j].append(filteredInstruments[i]) foundMatch = true } } if !foundMatch { yPositions.append(filteredInstruments[i].location!.y) groupedInstruments.append([filteredInstruments[i]]) } } } // sort instruments by channel within row for i in 0..<groupedInstruments.count { groupedInstruments[i] = groupedInstruments[i].sort({ $0.channel < $1.channel }) } // create tuples to easily sort rows from highest to lowest (since iOS origin is top-left) var tempRows: [(Double, [Instrument])] = [] for i in 0..<yPositions.count { tempRows.append((yPositions[i], groupedInstruments[i])) } tempRows.sortInPlace({ $0.0 > $1.0 }) self.instruments = [] self.purpose = purpose super.init() // add the instruments tempRows.forEach({ self.instruments.append($0.1) }) } }
3f16136d8cd501061c1d96acb482d5f6
33.441558
111
0.53356
false
false
false
false
dasdom/Swiftandpainless
refs/heads/master
SwiftAndPainlessPlayground.playground/Pages/Classes - Basics.xcplaygroundpage/Contents.swift
mit
1
import Foundation /*: [⬅️](@previous) [➡️](@next) # Classes: Basics */ class ToDo { var name: String = "er" let dueDate: NSDate let locationName: String init(name: String, date: NSDate, locationName: String) { self.name = name dueDate = date self.locationName = locationName } } let todo = ToDo(name: "Give talk", date: NSDate(), locationName: "Köln") print(todo) /*: Classes don't have automatic initializers and they also don't print nicely by their own. */
deec4b739381e57a2ac2a1d747be0c91
20.391304
89
0.660569
false
false
false
false
Brightify/ReactantUI
refs/heads/master
Sources/Live/Debug/DebugAlertController.swift
mit
1
// // DebugAlertController.swift // ReactantUI // // Created by Tadeas Kriz on 4/25/17. // Copyright © 2017 Brightify. All rights reserved. // import UIKit class DebugAlertController: UIAlertController { override var canBecomeFirstResponder: Bool { return true } override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand(input: "d", modifierFlags: .command, action: #selector(close), discoverabilityTitle: "Close Debug Menu") ] } @objc func close() { dismiss(animated: true) } static func create(manager: ReactantLiveUIManager, window: UIWindow) -> DebugAlertController { let controller = DebugAlertController(title: "Debug menu", message: "Reactant Live UI", preferredStyle: .actionSheet) controller.popoverPresentationController?.sourceView = window controller.popoverPresentationController?.sourceRect = window.bounds let hasMultipleThemes = manager.workers.contains { $0.context.globalContext.applicationDescription.themes.count > 1 } let hasMultipleWorkers = manager.workers.count > 1 if hasMultipleThemes { let switchTheme = UIAlertAction(title: "Switch theme ..", style: .default) { [weak window] _ in guard let controller = window?.rootViewController else { return } if hasMultipleWorkers { manager.presentWorkerSelection(in: controller) { selection in guard case .worker(let worker) = selection else { return } worker.presentThemeSelection(in: controller) } } else if let worker = manager.workers.first { worker.presentThemeSelection(in: controller) } } controller.addAction(switchTheme) } let reloadFiles = UIAlertAction(title: "Reload files\(hasMultipleWorkers ? " .." : "")", style: .default) { [weak window] _ in guard let controller = window?.rootViewController else { return } if hasMultipleWorkers { manager.presentWorkerSelection(in: controller, allowAll: true) { selection in switch selection { case .all: manager.reloadFiles() case .worker(let worker): worker.reloadFiles() } } } else if let worker = manager.workers.first { worker.reloadFiles() } } controller.addAction(reloadFiles) let preview = UIAlertAction(title: "Preview ..", style: .default) { [weak window] _ in guard let controller = window?.rootViewController else { return } if hasMultipleWorkers { manager.presentWorkerSelection(in: controller) { selection in guard case .worker(let worker) = selection else { return } worker.presentPreview(in: controller) } } else if let worker = manager.workers.first { worker.presentPreview(in: controller) } } controller.addAction(preview) controller.addAction(UIAlertAction(title: "Close menu", style: UIAlertAction.Style.cancel)) return controller } }
8d0d423be8a9a508ff0cd81250a6fa59
37.712644
134
0.594715
false
false
false
false
miraving/GPSGrabber
refs/heads/master
GPSGrabber/AppDelegate.swift
mit
1
// // AppDelegate.swift // GPSGrabber // // Created by Vitalii Obertynskyi on 10/27/16. // Copyright © 2016 Vitalii Obertynskyi. All rights reserved. // import UIKit import GoogleMaps import AWSCore import AWSCognito @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var dataManager = DataManager() var reachability: AWSKSReachability! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // google GMSServices.provideAPIKey("AIzaSyCqdO8rNETPFysAp18baxr8EckWAYc33SA") // amazon let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .euCentral1, identityPoolId:"eu-central-1:cea63a1d-de3f-4dca-bf03-af4c80162a3d") let configuration = AWSServiceConfiguration(region: .euCentral1, credentialsProvider:credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration reachabilitySetup() // internal settings set registerSettingBundle() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { dataManager.saveContext() } func applicationWillEnterForeground(_ application: UIApplication) { registerSettingBundle() } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { dataManager.saveContext() } func registerSettingBundle() { let pathStr = Bundle.main.bundlePath let settingsBundlePath = pathStr.appending("/Settings.bundle") let finalPath = settingsBundlePath.appending("/Root.plist") let settingsDict = NSDictionary(contentsOfFile: finalPath) let prefSpecifierArray = settingsDict?.object(forKey: "PreferenceSpecifiers") as! NSArray var defaults:[String:AnyObject] = [:] for item in prefSpecifierArray { if let dict = item as? [String: AnyObject] { if let key = dict["Key"] as! String! { let defaultValue = dict["DefaultValue"] as? NSNumber defaults[key] = defaultValue } } } UserDefaults.standard.register(defaults: defaults) } func reachabilitySetup() { self.reachability = AWSKSReachability.toInternet() self.reachability.onReachabilityChanged = { reachabile in if self.reachability.reachable == true { self.dataManager.uploadCache() } } } }
ff6ee3f192f9d991977592639a96de0c
31.627907
156
0.659301
false
false
false
false
YinSiQian/SQAutoScrollView
refs/heads/master
SQAutoScrollView/Source/SQDotView.swift
mit
1
// // SQDotView.swift // SQAutoScrollView // // Created by ysq on 2017/10/11. // Copyright © 2017年 ysq. All rights reserved. // import UIKit public enum SQDotState { case normal case selected } public class SQDotView: UIView { private var normalColor: UIColor? { willSet { guard newValue != nil else { return } backgroundColor = newValue! } } private var selectedColor: UIColor? { willSet { guard newValue != nil else { return } backgroundColor = newValue! } } public var isSelected: Bool = false { didSet { assert(selectedColor != nil || normalColor != nil, "please set color value") if isSelected { backgroundColor = selectedColor! } else { backgroundColor = normalColor! } } } public var style: SQPageControlStyle = .round { didSet { switch style { case .round: layer.cornerRadius = bounds.size.width / 2 case .rectangle: layer.cornerRadius = 0 } } } override public init(frame: CGRect) { super.init(frame: frame) } public func set(fillColor: UIColor, state: SQDotState) { switch state { case .normal: self.normalColor = fillColor case .selected: self.selectedColor = fillColor } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
0a9ebc234022e62a213965d56d3d7e22
21.363636
88
0.507549
false
false
false
false
material-foundation/github-comment
refs/heads/develop
Sources/GitHub/HunkCorrelation.swift
apache-2.0
1
/* Copyright 2018-present the Material Foundation authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /** Returns a GitHub pull request comment "position" for a given hunk in a given list of hunks. Context: One might hope you could post comments to GitHub pull requests given a file and line range. Alas, GitHub instead requires that you post comments to the pull request diff's hunks. For example, if a pull request made changes to lines 20-50 on file A, and you want to post a comment to line 25 of that file, you need to post a comment to "6" (line 20 is line "1" of the hunk). From the docs: https://developer.github.com/v3/pulls/comments/#create-a-comment > The position value equals the number of lines down from the first "@@" hunk header in the > file you want to add a comment. The line just below the "@@" line is position 1, the next > line is position 2, and so on. The position in the diff continues to increase through lines > of whitespace and additional hunks until the beginning of a new file. */ public func githubPosition(for hunk: Hunk, in hunks: [Hunk]) -> Int? { // Our hunk ranges line up like so: // hunks.beforeRange = original code // hunks.afterRange = pull request changes // hunk.beforeRange = pull request changes // hunk.afterRange = after suggested changes guard let index = hunks.index(where: { $0.afterRange.overlaps(hunk.beforeRange) }) else { return nil } // Position is counted by number of lines in the hunk content, so we start by counting the number // of lines in all of the preceeding hunks. let numberOfPrecedingHunkLines = hunks[0..<index].map { $0.contents.count }.reduce(0, +) // Each hunk's header (including the current one) has as an implicit line let numberOfHunksHeaders = index + 1 // The position should be the last line of code we intend to change in the index'd hunk. // First, count how many lines our hunk intends to change: let linesChanged = hunk.contents.index(where: { !$0.starts(with: "-") }) ?? hunk.contents.count let lastLineChanged = hunk.beforeRange.lowerBound + linesChanged // We now know the line number. Now we need to calculate the position. var numberOfLinesToCount = lastLineChanged - hunks[index].afterRange.lowerBound for (hunkPosition, line) in hunks[index].contents.enumerated() { if line.hasPrefix("-") { // Ignore removed lines continue } numberOfLinesToCount = numberOfLinesToCount - 1 if numberOfLinesToCount == 0 { return numberOfPrecedingHunkLines + numberOfHunksHeaders + hunkPosition } } return nil }
7e6cdbd5844639fb775c04b4480039fa
44.882353
99
0.737821
false
false
false
false
davirdgs/ABC4
refs/heads/master
MN4/Level.swift
gpl-3.0
1
// // Level.swift // MN4 // // Created by Pedro Rodrigues Grijó on 8/24/15. // Copyright (c) 2015 Pedro Rodrigues Grijó. All rights reserved. /** * To obtain a level, call setLevel and then getLevelWords */ import Foundation class Level { fileprivate var dataBase: [Category] fileprivate var rightCategoryId: UInt32 // Category Id of the 3 correct words fileprivate var wrongCategoryId: UInt32 // Category Id of the incorrect word fileprivate var wrongWord: Word // Incorrect word choice fileprivate var levelWords: [Word] // Words of the current level init() { let langId = Locale.preferredLanguages[0] //print(langId) // Gets the dataBase if(langId == "pt-BR" || langId == "pt-PT") { self.dataBase = WordDataBase.getDataBase() } else if(langId == "es-BR" || langId == "es-ES" || langId == "es-419" || langId == "es-MX") { self.dataBase = WordDataBaseSpanish.getDataBase() } else { self.dataBase = WordDataBaseEnglish.getDataBase() } self.rightCategoryId = 0 self.wrongCategoryId = 0 self.wrongWord = Word(word: "", difficulty: "") self.levelWords = [Word]() } // MARK: - Setters // Models a level func setLevel() { setCategoryIds() setLevelWords() randomizeLevelWords() } fileprivate func setCategoryIds() { // Randomly chooses the category Ids of the right and wrong words self.rightCategoryId = arc4random_uniform(UInt32(dataBase.count)) self.wrongCategoryId = arc4random_uniform(UInt32(dataBase.count)) // Loops until an acceptable wrong category Id is generated while wrongCategoryId == rightCategoryId { self.wrongCategoryId = arc4random_uniform(UInt32(dataBase.count)) } } fileprivate func setLevelWords() { var wrongWordIndex: Int var rightWordIndexes: [Int] = [Int](repeating: 0, count: 3) // Generates random indexes to get the words from the database wrongWordIndex = Int(arc4random_uniform(UInt32(dataBase[Int(wrongCategoryId)].words.count))) rightWordIndexes[0] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count))) rightWordIndexes[1] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count))) rightWordIndexes[2] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count))) // Checks for duplicates while rightWordIndexes[1] == rightWordIndexes[0] { rightWordIndexes[1] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count))) } while rightWordIndexes[2] == rightWordIndexes[1] || rightWordIndexes[2] == rightWordIndexes[0] { rightWordIndexes[2] = Int(arc4random_uniform(UInt32(dataBase[Int(rightCategoryId)].words.count))) } // Gets the words from the database and appends them into the levelWords array self.wrongWord = dataBase[Int(wrongCategoryId)].words[wrongWordIndex] self.levelWords.append(self.wrongWord) self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[0]]) self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[1]]) self.levelWords.append(dataBase[Int(rightCategoryId)].words[rightWordIndexes[2]]) } // MARK: - Getters func getCategoryIds()->[UInt32] { return [rightCategoryId, wrongCategoryId] } func getLevelWords()->[Word] { return levelWords } func getWrongWord()->Word { return wrongWord } // MARK: - Other Methods // Fisher-Yates/Knuth Shuffle fileprivate func randomizeLevelWords() { let size: Int = self.levelWords.count for i in 0...(size - 1) {//(var i=0; i<size; i += 1) { let j = i + Int(arc4random_uniform(UInt32(size-i))) if(j<size && !(j==i)) { swap(&levelWords[i], &levelWords[j]) } } } // func printLevelWords() { // println(self.levelWords) // } }
bdae3e6fe416d82d4b648caf9e5f3574
31.338346
109
0.617531
false
false
false
false
OSzhou/MyTestDemo
refs/heads/master
17_SwiftTestCode/TestCode/CustomAlbum/Source/Scene/Picker/HEPhotoPickerViewController.swift
apache-2.0
1
// // HEPhotoPickerViewController.swift // SwiftPhotoSelector // // Created by heyode on 2018/9/19. // Copyright (c) 2018 heyode <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Photos //屏宽 let kScreenWidth = UIScreen.main.bounds.size.width //屏高 let kScreenHeight = UIScreen.main.bounds.size.height @objc public protocol HEPhotoPickerViewControllerDelegate { /// 选择照片完成后调用的代理 /// /// - Parameters: /// - picker: 选择图片的控制器 /// - selectedImages: 选择的图片数组(如果是视频,就取视频第一帧作为图片保存) /// - selectedModel: 选择的数据模型 func pickerController(_ picker:UIViewController, didFinishPicking selectedImages:[UIImage],selectedModel:[HEPhotoAsset]) /// 选择照片取消后调用的方法 /// /// - Parameter picker: 选择图片的控制器 @objc optional func pickerControllerDidCancel(_ picker:UIViewController) } public class HEPhotoPickerViewController: HEBaseViewController { // MARK : - Public /// 选择器配置 public var pickerOptions : HEPickerOptions! /// 选择完成后的相关代理 public var delegate : HEPhotoPickerViewControllerDelegate? // MARK : - Private /// 图片列表的数据模型 private var models : [HEPhotoAsset]! /// 选中的数据模型 private var selectedModels = [HEPhotoAsset](){ didSet{ if let first = selectedModels.first{ // 记录上一次选中模型集合中的数据类型 preSelecetdType = first.asset.mediaType } } } /// 选中的图片模型(若有视频,则取它第一帧作为图片保存) private lazy var selectedImages = [UIImage]() /// 用于处理选中的数组 private lazy var todoArray = [HEPhotoAsset]() /// 相册请求项 private let photosOptions = PHFetchOptions() /// 过场动画 private var animator = HEPhotoBrowserAnimator() ///  相册原有数据 private var smartAlbums :PHFetchResult<PHAssetCollection>! /// 整理过后的相册 private var albumModels : [HEAlbum]! /// 所有展示的多媒体数据集合 private var phAssets : PHFetchResult<PHAsset>! /// 相册按钮 private var titleBtn : UIButton! /// titleBtn展开的tableView的上一个选中的IndexPath private var preSelectedTableViewIndex = IndexPath.init(row: 0, section: 0 ) /// titleBtn展开的tableView的上一个选中的con private var preSelectedTableViewContentOffset = CGPoint.zero /// 待刷新的IndexPath(imageOrVideo模式下更新cell可用状态专用) private var willUpadateIndex = Set<IndexPath>() /// 当选中数组为空时,记录上一次选中模型集合中的数据类型(imageOrVideo模式下更新cell可用状态专用) private var preSelecetdType : PHAssetMediaType! /// 图片视图 private lazy var collectionView : UICollectionView = { let cellW = (self.view.frame.width - 3) / 4.0 let layout = UICollectionViewFlowLayout.init() layout.itemSize = CGSize.init(width: cellW, height: cellW) layout.minimumLineSpacing = 1 layout.minimumInteritemSpacing = 1 var height = CGFloat(0) if UIDevice.isContansiPhoneX(){ height = kScreenHeight - 88 }else{ height = kScreenHeight - 64 } let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.width, height:height), collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 34, right: 0) collectionView.delegate = self collectionView.dataSource = self collectionView.register(HEPhotoPickerCell.classForCoder(), forCellWithReuseIdentifier: HEPhotoPickerCell.className) return collectionView }() // MARK:- 初始化 /// 初始化方法 /// /// - Parameters: /// - delegate: 控制器的代理 /// - options: 配置项 public init(delegate: HEPhotoPickerViewControllerDelegate,options:HEPickerOptions = HEPickerOptions() ) { super.init(nibName: nil, bundle: nil) self.delegate = delegate self.pickerOptions = options } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- 控制器生命周期和设置UI public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) edgesForExtendedLayout = [] } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } public override func viewDidLoad() { super.viewDidLoad() animator.pushDelegate = self navigationController?.delegate = self configPickerOption() requestAndFetchAssets() } private func requestAndFetchAssets() { if HETool.canAccessPhotoLib() { self.getAllPhotos() } else { HETool.requestAuthorizationForPhotoAccess(authorized:self.getAllPhotos, rejected: HETool.openIphoneSetting) } } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } func configUI() { view.addSubview(collectionView) let btn = HEAlbumTitleView.init(type: .custom) titleBtn = btn if let title = albumModels.first?.title{ btn.setTitle(title, for: .normal) } btn.addTarget(self, action: #selector(HEPhotoPickerViewController.titleViewClick(_:)), for: .touchUpInside) navigationItem.titleView = btn let rightBtn = HESeletecedButton.init(type: .custom) rightBtn.setTitle(pickerOptions.selectDoneButtonTitle) rightBtn.addTarget(self, action: #selector(nextBtnClick), for: .touchUpInside) let right = UIBarButtonItem.init(customView: rightBtn) navigationItem.rightBarButtonItem = right rightBtn.isEnabled = false } override public func configNavigationBar() { super.configNavigationBar() navigationItem.leftBarButtonItem = setLeftBtn() } func setLeftBtn() -> UIBarButtonItem{ let leftBtn = UIButton.init(type: .custom) leftBtn.setTitle(pickerOptions.cancelButtonTitle, for: .normal) leftBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside) leftBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) leftBtn.setTitleColor(UIColor.gray, for: .normal) let left = UIBarButtonItem.init(customView: leftBtn) return left } /// 将给定类型模型设为不可点击状态 /// /// - Parameter type: 给定媒体数据类型 func setCellDisableEnable(with type:PHAssetMediaType){ for item in models{ if item.asset.mediaType == type{ item.isEnable = false } } collectionView.reloadData() } func updateNextBtnTitle() { let rightBtn = navigationItem.rightBarButtonItem?.customView as! HESeletecedButton rightBtn.isEnabled = selectedModels.count > 0 if selectedModels.count > 0 { rightBtn.setTitle(String.init(format: "%@(%d)",pickerOptions.selectDoneButtonTitle, selectedModels.count)) }else{ rightBtn.setTitle(pickerOptions.selectDoneButtonTitle) } } /// 数据源重置后更新UI func updateUI(){ updateNextBtnTitle() setCellState(selectedIndex: nil, isUpdateSelecetd: true) } // MARK: - 更新cell /// 更新cell的选中状态 /// /// - Parameters: /// - selectedIndex: 选中的索引 /// - selectedBtn: 选择按钮 func updateSelectedCell(selectedIndex:Int,selectedBtn:UIButton) { let model = self.models[selectedIndex] if selectedBtn.isSelected { switch model.asset.mediaType { case .image: let selectedImageCount = self.selectedModels.count{$0.asset.mediaType == .image} guard selectedImageCount < self.pickerOptions.maxCountOfImage else{ let title = String.init(format: pickerOptions.maxPhotoWaringTips, self.pickerOptions.maxCountOfImage) presentAlert(title: title) selectedBtn.isSelected = false return } case .video: let selectedVideoCount = self.selectedModels.count{$0.asset.mediaType == .video} guard selectedVideoCount < self.pickerOptions.maxCountOfVideo else{ let title = String.init(format: pickerOptions.maxVideoWaringTips, self.pickerOptions.maxCountOfVideo) presentAlert(title: title) selectedBtn.isSelected = false return } default: break } selectedBtn.isSelected = true self.selectedModels.append(model) }else{// 切勿使用index去匹配 self.selectedModels.removeAll(where: {$0.asset.localIdentifier == model.asset.localIdentifier}) selectedBtn.isSelected = false } models[selectedIndex].isSelected = selectedBtn.isSelected updateNextBtnTitle() // 根据当前用户选中的个数,将所有未选中的cell重置给定可用状态 setCellState(selectedIndex: selectedIndex) } /// 设置cell的可用和选中状态 /// /// - Parameters: /// - selectedIndex:当前选中的cell索引 /// - isUpdateSelecetd: 是否更新选中状态 func setCellState(selectedIndex:Int?,isUpdateSelecetd:Bool = false){ // 初始化将要刷新的索引集合 willUpadateIndex = Set<IndexPath>() let selectedCount = selectedModels.count let optionMaxCount = pickerOptions.maxCountOfImage + pickerOptions.maxCountOfVideo // 尽量将所有需要更新状态的操作都放在这个循环里面,节约开销 for item in models{ if isUpdateSelecetd == true{// 整个数据源重置,要重设选中状态 // item.isSelected = selectedModels.contains(where: {$0.asset.localIdentifier == item.asset.localIdentifier}) if let selectItem = selectedModels.first(where: {$0.asset.localIdentifier == item.asset.localIdentifier}) { item.isSelected = true item.selecteIndex = selectItem.selecteIndex if let selIndex = selectedModels.firstIndex(of: selectItem) { selectedModels.remove(at: selIndex) selectedModels.insert(item, at: selIndex) } } } // 如果未选中的话,并且是imageOrVideo,就需要更新cell的可用状态 // 根据当前用户选中的个数,将所有未选中的cell重置给定可用状态 if item.isSelected == false && pickerOptions.mediaType == .imageOrVideo{ // 选中的数量小于允许选中的最大数,就可用 if selectedCount < optionMaxCount && item.isEnable == false{ // 选中的数量小于允许选中的最大数,就可用 item.isEnable = true // 将待刷新的索引加入到数组 willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0)) }else if selectedCount >= optionMaxCount && item.isEnable == true{//选中的数量大于或等于最大数,就不可用 item.isEnable = false // 将待刷新的索引加入到数组 willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0)) } if selectedModels.count > 0{ if selectedModels.first?.asset.mediaType == .image{ // 用户选中的是图片的话,就把视频类型的cell都设置为不可选中 if item.asset.mediaType == .video{ item.isEnable = false if let i = selectedIndex,item.index != i{// 点击是自动刷新,所以要排除 // 将待刷新的索引加入到数组 willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0)) } } }else if selectedModels.first?.asset.mediaType == .video{ if item.asset.mediaType == .image{ item.isEnable = false if let i = selectedIndex,item.index != i{// 点击是自动刷新,所以要排除 willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0)) } } } } } if selectedModels.count <= 0 && pickerOptions.mediaType == .imageOrVideo{//是imageOrVideo状态下,取消所有选择,要找出哪些cell需要刷新可用状态 item.isEnable = true // 将待刷新的索引加入到数组 willUpadateIndex.insert(IndexPath.init(row: item.index, section: 0)) } } for (i, item) in selectedModels.enumerated() { item.selecteIndex = i + 1 } // if isUpdateSelecetd {// 整个数据源重置,必须刷新所有cell collectionView.reloadData() // }else{ // // collectionView.reloadItems(at: Array.init(willUpadateIndex) ) // } } // MARK:- 初始化配置项 func configPickerOption() { switch pickerOptions.mediaType { case .imageAndVideo: pickerOptions.singlePicture = false pickerOptions.singleVideo = false case .imageOrVideo: pickerOptions.singlePicture = false case .image: pickerOptions.maxCountOfVideo = 0 case .video: pickerOptions.maxCountOfImage = 0 } if pickerOptions.singleVideo { pickerOptions.maxCountOfVideo = 0 } if pickerOptions.singlePicture{ pickerOptions.maxCountOfImage = 0 } if let models = pickerOptions.defaultSelections{ selectedModels = models } } func isSinglePicture(model:HEPhotoAsset) ->Bool{ return model.asset.mediaType == .image && pickerOptions.singlePicture == true } func isSingleVideo(model:HEPhotoAsset) ->Bool{ return model.asset.mediaType == .video && pickerOptions.singleVideo == true } /// 如果当前模型是单选模式隐藏多选按钮 /// /// - Parameter model: 当前模型 func checkIsSingle(model:HEPhotoAsset){ if isSinglePicture(model: model) || isSingleVideo(model: model) { model.isEnableSelected = false } } // MARK:- UI Actions @objc func titleViewClick(_ sender:UIButton){ sender.isSelected = true let popViewFrame : CGRect! popViewFrame = CGRect.init(x: 0, y: (navigationController?.navigationBar.frame.maxY)!, width: kScreenWidth, height: kScreenHeight/2) let listView = HEAlbumListView.showOnKeyWidows(rect: popViewFrame, assetCollections: albumModels, cellClick: { [weak self](list,ablum,selecedIndex) in self?.preSelectedTableViewIndex = selecedIndex // self?.preSelectedTableViewContentOffset = list.tableView.contentOffset self?.titleBtn.setTitle(ablum.title, for: .normal) self?.titleBtn.sizeToFit() self?.fetchPhotoModels(photos: ablum.fetchResult) self?.updateUI() },dismiss:{ sender.isSelected = false }) listView.tableView.selectRow(at: preSelectedTableViewIndex, animated: false, scrollPosition:.middle) } @objc func nextBtnClick(){ todoArray = selectedModels getImages() } @objc func goBack(){ navigationController?.dismiss(animated: true, completion: nil) delegate?.pickerControllerDidCancel?(self) } // MARK:- 获取全部图片 private func getAllPhotos() { switch pickerOptions.mediaType{ case .image: photosOptions.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.image.rawValue) case .video: photosOptions.predicate = NSPredicate.init(format: "mediaType == %ld", PHAssetMediaType.video.rawValue) default: break } photosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: pickerOptions.ascendingOfCreationDateSort)] phAssets = PHAsset.fetchAssets(with: photosOptions) fetchPhotoModels(photos: phAssets) getAllAlbums() // 注册相册库的通知(要写在getAllPhoto后面) PHPhotoLibrary.shared().register(self) configUI() if selectedModels.count > 0{ updateUI() } } func getAllAlbums(){ smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) fetchAlbumsListModels(albums: smartAlbums) } private func fetchPhotoModels(photos:PHFetchResult<PHAsset>){ var models = [HEPhotoAsset]() photos.enumerateObjects {[weak self] (asset, index, ff) in let model = HEPhotoAsset.init(asset: asset) self?.checkIsSingle(model: model) model.index = index models.append(model) } self.models = models self.collectionView.reloadData() /*models = [HEPhotoAsset]() let queue = DispatchQueue.global() let group = DispatchGroup() photos.enumerateObjects { [weak self] (asset, index, ff) in group.enter() let item = DispatchWorkItem { HETool.wb_RequestImageData(asset, options: nil) { (imageData, flag) in if !flag { let model = HEPhotoAsset.init(asset: asset) self?.checkIsSingle(model: model) model.index = index models.append(model) } group.leave() } } queue.async(group: group, execute: item) } group.notify(queue: DispatchQueue.main) { self.collectionView.reloadData() }*/ } private func fetchAlbumsListModels(albums:PHFetchResult<PHAssetCollection>){ albumModels = [HEAlbum]() albums.enumerateObjects { [weak self] (collection, index, stop) in let asset = PHAsset.fetchAssets(in: collection, options: self!.photosOptions) let album = HEAlbum.init(result: asset, title: collection.localizedTitle) if asset.count > 0 && collection.localizedTitle != "最近删除" && collection.localizedTitle != "Recently Deleted"{ self?.albumModels.append(album) } } } func getImages(){ let option = PHImageRequestOptions() option.deliveryMode = .highQualityFormat if todoArray.count == 0 { delegate?.pickerController(self, didFinishPicking: selectedImages,selectedModel: selectedModels) dismiss(animated: true, completion: nil) } if todoArray.count > 0 { HETool.heRequestImage(for: (todoArray.first?.asset)!, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill) {[weak self] (image, _) in DispatchQueue.main.async { self?.todoArray.removeFirst() self?.selectedImages.append(image ?? UIImage()) self?.getImages() } } } } } extension HEPhotoPickerViewController: PHPhotoLibraryChangeObserver{ open func photoLibraryDidChange(_ changeInstance: PHChange) { DispatchQueue.main.sync { if let changeDetails = changeInstance.changeDetails(for: phAssets){ phAssets = changeDetails.fetchResultAfterChanges fetchPhotoModels(photos: phAssets) } // Update the cached fetch results, and reload the table sections to match. if let changeDetails = changeInstance.changeDetails(for: smartAlbums) { smartAlbums = changeDetails.fetchResultAfterChanges fetchAlbumsListModels(albums: smartAlbums) if let title = albumModels.first?.title{ titleBtn.setTitle(title, for: .normal) titleBtn.sizeToFit() } } } } } extension HEPhotoPickerViewController : UICollectionViewDelegate,UICollectionViewDataSource{ public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return models.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier:HEPhotoPickerCell.className , for: indexPath) as! HEPhotoPickerCell let model = models[indexPath.row] cell.model = model cell.pickerOptions = self.pickerOptions cell.checkBtnnClickClosure = {[unowned self] (selectedBtn) in self.updateSelectedCell(selectedIndex: indexPath.row, selectedBtn: selectedBtn) } return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { animator.selIndex = indexPath let size = CGSize.init(width: kScreenWidth, height: kScreenWidth) HETool.heRequestImage(for: phAssets[indexPath.row] , targetSize: size, contentMode: .aspectFill) { (image, nil) in let photoDetail = HEPhotoBrowserViewController() photoDetail.delegate = self.delegate photoDetail.pickerOptions = self.pickerOptions photoDetail.imageIndex = indexPath photoDetail.models = self.models photoDetail.selectedModels = self.selectedModels photoDetail.canScroll = !self.pickerOptions.singlePicture photoDetail.selectedCloser = { selectedIndex in self.models[selectedIndex].isSelected = true self.selectedModels.append(self.models[selectedIndex]) self.updateUI() } photoDetail.unSelectedCloser = { selectedIndex in self.models[selectedIndex].isSelected = false self.selectedModels.removeAll{$0 == self.models[selectedIndex]} self.updateUI() } photoDetail.clickBottomCellCloser = { selectedIndex in collectionView.scrollToItem(at: IndexPath.init(item: selectedIndex, section: 0), at: .centeredVertically, animated: false) } self.animator.popDelegate = photoDetail self.navigationController?.pushViewController(photoDetail, animated: true) } } } extension HEPhotoPickerViewController : UINavigationControllerDelegate{ public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { animator.operation = operation return animator } } extension HEPhotoPickerViewController: HEPhotoBrowserAnimatorPushDelegate{ public func imageViewRectOfAnimatorStart(at indexPath: IndexPath) -> CGRect { // 获取指定cell的laout let cellLayout = collectionView.layoutAttributesForItem(at: indexPath) let homeFrame = UIApplication.shared.keyWindow?.convert(cellLayout?.frame ?? CGRect.zero, from: collectionView) ?? CGRect.zero //返回具体的尺寸 return homeFrame } public func imageViewRectOfAnimatorEnd(at indexPath: IndexPath) -> CGRect { //取出cell let cell = (collectionView.cellForItem(at: indexPath))! as! HEPhotoPickerCell //取出cell中显示的图片 let image = cell.imageView.image let x: CGFloat = 0 let width: CGFloat = kScreenWidth let height: CGFloat = width / (image!.size.width) * (image!.size.height) var y: CGFloat = 0 if height < kScreenHeight { y = (kScreenHeight - height) * 0.5 } //计算方法后的图片的frame return CGRect(x: x, y: y, width: width, height: height) } }
354df3add572269bf32b572c811e7268
38.578864
254
0.61284
false
false
false
false
blomma/stray
refs/heads/master
stray/Event+CloudKitStack.swift
gpl-3.0
1
import Foundation import CloudKit extension Event: CloudKitStackEntity { var recordType: String { return Event.entityName } var recordName: String { return "\(recordType).\(id)" } var recordZoneName: String { return Event.entityName } func record() -> CKRecord { let id = recordID() let record = CKRecord(recordType: recordType, recordID: id) record["startDate"] = startDate as CKRecordValue if let stopDate = stopDate { record["stopDate"] = stopDate as CKRecordValue } if let tag = tag { record["tag"] = tag as CKRecordValue } return record } }
2a23e4677f1e494093f2b35db48f79db
29.105263
79
0.715035
false
false
false
false
leizh007/HiPDA
refs/heads/master
HiPDA/HiPDA/Sections/Message/UnReadMessagesCountManager.swift
mit
1
// // MessageManager.swift // HiPDA // // Created by leizh007 on 2017/6/27. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation import RxSwift class UnReadMessagesCountManager { private let disposeBag = DisposeBag() static let shared = UnReadMessagesCountManager() private init() { observeEventBus() } fileprivate func observeEventBus() { EventBus.shared.activeAccount.asObservable() .subscribe(onNext: { loginResult in guard let loginResult = loginResult, case .success(_) = loginResult else { return } // 去请求一下首页,获取一下未读消息的数量 NetworkUtilities.html(from: "/forum/index.php") }) .disposed(by: disposeBag) } static func handleUnReadMessagesCount(from html: String) { guard let threadMessagesCount = try? HtmlParser.messageCount(of: "帖子消息", from: html), let pmMessagesCount = try? HtmlParser.messageCount(of: "私人消息", from: html), let friendMessagesCount = try? HtmlParser.messageCount(of: "好友消息", from: html) else { return } let model = UnReadMessagesCountModel(threadMessagesCount: threadMessagesCount, privateMessagesCount: pmMessagesCount, friendMessagesCount: friendMessagesCount) EventBus.shared.dispatch(UnReadMessagesCountAction(model: model)) } }
31e1e314382b2604b58126eb8a670bc4
36.3
106
0.616622
false
false
false
false
liufengting/FTChatMessageDemoProject
refs/heads/master
FTChatMessage/FTChatMessageModel.swift
mit
1
// // FTChatMessageModel.swift // FTChatMessage // // Created by liufengting on 16/2/28. // Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved. // import UIKit // MARK: - FTChatMessageDeliverStatus enum FTChatMessageDeliverStatus { case sending case succeeded case failed } // MARK: - FTChatMessageModel class FTChatMessageModel: NSObject { var targetId : String! var isUserSelf : Bool = false; var messageText : String! var messageTimeStamp : String! var messageType : FTChatMessageType = .text var messageSender : FTChatMessageUserModel! var messageExtraData : NSDictionary? var messageDeliverStatus : FTChatMessageDeliverStatus = FTChatMessageDeliverStatus.succeeded // MARK: - convenience init convenience init(data : String? ,time : String?, from : FTChatMessageUserModel, type : FTChatMessageType){ self.init() self.transformMessage(data,time : time,extraDic: nil,from: from,type: type) } convenience init(data : String?,time : String?, extraDic : NSDictionary?, from : FTChatMessageUserModel, type : FTChatMessageType){ self.init() self.transformMessage(data,time : time,extraDic: extraDic,from: from,type: type) } // MARK: - transformMessage fileprivate func transformMessage(_ data : String? ,time : String?, extraDic : NSDictionary?, from : FTChatMessageUserModel, type : FTChatMessageType){ messageType = type messageText = data messageTimeStamp = time messageSender = from isUserSelf = from.isUserSelf if (extraDic != nil) { messageExtraData = extraDic; } } } class FTChatMessageImageModel: FTChatMessageModel { var image : UIImage! var imageUrl : String! }
29bfd67bf3f6faf241d43276cc87c5db
27.59375
155
0.680874
false
false
false
false
inket/stts
refs/heads/master
stts/EditorTableView/EditorTableViewController.swift
mit
1
// // EditorTableViewController.swift // stts // import Cocoa class EditorTableViewController: NSObject, SwitchableTableViewController { let contentView: NSStackView let scrollView: CustomScrollView let bottomBar: BottomBar let tableView = NSTableView() let allServices: [BaseService] = BaseService.all().sorted() let allServicesWithoutSubServices: [BaseService] = BaseService.allWithoutSubServices().sorted() var filteredServices: [BaseService] var selectedServices: [BaseService] = Preferences.shared.selectedServices var selectionChanged = false let settingsView = SettingsView() var hidden: Bool = true var savedScrollPosition: CGPoint = .zero var selectedCategory: ServiceCategory? { didSet { // Save the scroll position between screens let scrollToPosition: CGPoint? if selectedCategory != nil && oldValue == nil { savedScrollPosition = CGPoint(x: 0, y: tableView.visibleRect.minY) scrollToPosition = .zero } else if selectedCategory == nil && oldValue != nil { scrollToPosition = savedScrollPosition } else { scrollToPosition = nil } // Adjust UI bottomBar.openedCategory(selectedCategory, backCallback: { [weak self] in self?.selectedCategory = nil }) guard let category = selectedCategory else { // Show the unfiltered services filteredServices = allServicesWithoutSubServices tableView.reloadData() if let scrollPosition = scrollToPosition { tableView.scroll(scrollPosition) } return } // Find the sub services var subServices = allServices.filter { // Can't check superclass matches without mirror Mirror(reflecting: $0).superclassMirror?.subjectType == category.subServiceSuperclass // Exclude the category so that we can add it at the top && $0 != category as? BaseService }.sorted() // Add the category as the top item (category as? BaseService).flatMap { subServices.insert($0, at: 0) } filteredServices = subServices tableView.reloadData() if let scrollPosition = scrollToPosition { tableView.scroll(scrollPosition) } } } var isSearching: Bool { settingsView.searchField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) != "" } private var cachedTableViewWidth: CGFloat = 0 private var cachedMaxNameWidth: CGFloat? private var maxNameWidth: CGFloat? { if cachedTableViewWidth != tableView.frame.width || cachedMaxNameWidth == nil { cachedTableViewWidth = tableView.frame.width cachedMaxNameWidth = EditorTableCell.maxNameWidth(for: tableView) return cachedMaxNameWidth! } return cachedMaxNameWidth } init(contentView: NSStackView, scrollView: CustomScrollView, bottomBar: BottomBar) { self.contentView = contentView self.scrollView = scrollView self.filteredServices = allServicesWithoutSubServices self.bottomBar = bottomBar super.init() setup() } func setup() { tableView.frame = scrollView.bounds let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "editorColumnIdentifier")) column.width = 200 tableView.addTableColumn(column) tableView.autoresizesSubviews = true tableView.wantsLayer = true tableView.layer?.cornerRadius = 6 tableView.headerView = nil tableView.gridStyleMask = NSTableView.GridLineStyle.init(rawValue: 0) tableView.dataSource = self tableView.delegate = self tableView.selectionHighlightStyle = .none tableView.backgroundColor = NSColor.clear if #available(OSX 11.0, *) { tableView.style = .fullWidth } settingsView.isHidden = true settingsView.searchCallback = { [weak self] searchString in guard let strongSelf = self, let allServices = strongSelf.allServices as? [Service], let allServicesWithoutSubServices = strongSelf.allServicesWithoutSubServices as? [Service] else { return } if searchString.trimmingCharacters(in: .whitespacesAndNewlines) == "" { strongSelf.filteredServices = allServicesWithoutSubServices } else { // Can't filter array with NSPredicate without making Service inherit KVO from NSObject, therefore // we create an array of service names that we can run the predicate on let allServiceNames = allServices.compactMap { $0.name } as NSArray let predicate = NSPredicate(format: "SELF LIKE[cd] %@", argumentArray: ["*\(searchString)*"]) guard let filteredServiceNames = allServiceNames.filtered(using: predicate) as? [String] else { return } strongSelf.filteredServices = allServices.filter { filteredServiceNames.contains($0.name) } } if strongSelf.selectedCategory != nil { strongSelf.selectedCategory = nil } strongSelf.tableView.reloadData() } settingsView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(settingsView) NSLayoutConstraint.activate([ settingsView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), settingsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), settingsView.topAnchor.constraint(equalTo: contentView.topAnchor), settingsView.heightAnchor.constraint(equalToConstant: 170) ]) } func willShow() { self.selectionChanged = false scrollView.topConstraint?.constant = settingsView.frame.size.height scrollView.documentView = tableView settingsView.isHidden = false // We should be using NSWindow's makeFirstResponder: instead of the search field's selectText:, // but in this case, makeFirstResponder is causing a bug where the search field "gets focused" twice // (focus ring animation) the first time it's drawn. settingsView.searchField.selectText(nil) resizeViews() } func resizeViews() { tableView.frame = scrollView.bounds tableView.tableColumns.first?.width = tableView.frame.size.width scrollView.frame.size.height = 400 (NSApp.delegate as? AppDelegate)?.popupController.resizePopup( height: scrollView.frame.size.height + 30 // bottomBar.frame.size.height ) } func willOpenPopup() { resizeViews() } func didOpenPopup() { settingsView.searchField.window?.makeFirstResponder(settingsView.searchField) } func willHide() { settingsView.isHidden = true } @objc func deselectCategory() { selectedCategory = nil } } extension EditorTableViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return filteredServices.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { return nil } func tableViewSelectionDidChange(_ notification: Notification) { guard tableView.selectedRow != -1 else { return } // We're only interested in selections of categories guard selectedCategory == nil, let category = filteredServices[tableView.selectedRow] as? ServiceCategory else { return } // Change the selected category selectedCategory = category } } extension EditorTableViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { guard let maxNameWidth = maxNameWidth, let service = filteredServices[row] as? Service else { return EditorTableCell.defaultHeight } return EditorTableCell.estimatedHeight(for: service, maxWidth: maxNameWidth) } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let identifier = tableColumn?.identifier ?? NSUserInterfaceItemIdentifier(rawValue: "identifier") let cell = tableView.makeView(withIdentifier: identifier, owner: self) ?? EditorTableCell() guard let view = cell as? EditorTableCell else { return nil } guard let service = filteredServices[row] as? Service else { return nil } if isSearching || selectedCategory != nil { view.type = .service } else { view.type = (service is ServiceCategory) ? .category : .service } switch view.type { case .service: view.textField?.stringValue = service.name view.selected = selectedServices.contains(service) view.toggleCallback = { [weak self] in guard let strongSelf = self else { return } strongSelf.selectionChanged = true if view.selected { self?.selectedServices.append(service) } else { if let index = self?.selectedServices.firstIndex(of: service) { self?.selectedServices.remove(at: index) } } Preferences.shared.selectedServices = strongSelf.selectedServices } case .category: view.textField?.stringValue = (service as? ServiceCategory)?.categoryName ?? service.name view.selected = false view.toggleCallback = {} } return view } func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "rowView") let cell = tableView.makeView(withIdentifier: cellIdentifier, owner: self) ?? ServiceTableRowView() guard let view = cell as? ServiceTableRowView else { return nil } view.showSeparator = row + 1 < filteredServices.count return view } }
6e9f027b87b24955e56f4264500d43dd
35.356401
120
0.636052
false
false
false
false
narner/AudioKit
refs/heads/master
Playgrounds/AudioKitPlaygrounds/Playgrounds/Basics.playground/Pages/Playgrounds to Production.xcplaygroundpage/Contents.swift
mit
1
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: ## Playgrounds to Production //: //: The intention of most of the AudioKit Playgrounds is to highlight a particular //: concept. To keep things clear, we have kept the amount of code to a minimum. //: But the flipside of that decision is that code from playgrounds will look a little //: different from production. In general, to see best practices, you can check out //: the AudioKit examples project, but here in this playground we'll highlight some //: important ways playground code differs from production code. //: //: In production, you would only import AudioKit, not AudioKitPlaygrounds import AudioKitPlaygrounds import AudioKit //: ### Memory management //: //: In a playground, you don't have to worry about whether a node is retained, so you can //: just write: let oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() //: But if you did the same type of thing in a project: class BadAudioEngine { init() { let oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() } } //: It wouldn't work because the oscillator node would be lost right after the init //: method completed. Instead, make sure it is declared as an instance variable: class AudioEngine { var oscillator: AKOscillator init() { oscillator = AKOscillator() AudioKit.output = oscillator AudioKit.start() } } //: ### Error Handling //: //: In AudioKit playgrounds, failable initializers are just one line: let file = try AKAudioFile() var player = try AKAudioPlayer(file: file) //: In production code, this would need to be wrapped in a do-catch block do { let file = try AKAudioFile(readFileName: "drumloop.wav") player = try AKAudioPlayer(file: file) } catch { AKLog("File Not Found") } //: --- //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
4f98e054e8ac9e96a6a286c9a0e4e79c
31.213115
89
0.698219
false
false
false
false
tensorflow/swift-apis
refs/heads/main
Sources/TensorFlow/Epochs/Algorithms.swift
apache-2.0
1
//===--- Algorithms.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // RUN: %empty-directory(%t) // RUN: %target-build-swift -g -Onone -DUSE_STDLIBUNITTEST %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test #if USE_STDLIBUNITTEST import Swift import StdlibUnittest #endif //===--- Rotate -----------------------------------------------------------===// //===----------------------------------------------------------------------===// /// Provides customization points for `MutableCollection` algorithms. /// /// If incorporated into the standard library, these requirements would just be /// part of `MutableCollection`. In the meantime, you can declare conformance /// of a collection to `MutableCollectionAlgorithms` to get these customization /// points to be used from other algorithms defined on /// `MutableCollectionAlgorithms`. public protocol MutableCollectionAlgorithms: MutableCollection where SubSequence: MutableCollectionAlgorithms { /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult mutating func rotate(shiftingToStart middle: Index) -> Index } // Conformances of common collection types to MutableCollectionAlgorithms. // If rotate was a requirement of MutableCollection, these would not be needed. extension Array: MutableCollectionAlgorithms {} extension ArraySlice: MutableCollectionAlgorithms {} extension Slice: MutableCollectionAlgorithms where Base: MutableCollection {} extension MutableCollection { /// Swaps the elements of the two given subranges, up to the upper bound of /// the smaller subrange. The returned indices are the ends of the two ranges /// that were actually swapped. /// /// Input: /// [a b c d e f g h i j k l m n o p] /// ^^^^^^^ ^^^^^^^^^^^^^ /// lhs rhs /// /// Output: /// [i j k l e f g h a b c d m n o p] /// ^ ^ /// p q /// /// - Precondition: !lhs.isEmpty && !rhs.isEmpty /// - Postcondition: For returned indices `(p, q)`: /// - distance(from: lhs.lowerBound, to: p) == /// distance(from: rhs.lowerBound, to: q) /// - p == lhs.upperBound || q == rhs.upperBound @inline(__always) internal mutating func _swapNonemptySubrangePrefixes( _ lhs: Range<Index>, _ rhs: Range<Index> ) -> (Index, Index) { assert(!lhs.isEmpty) assert(!rhs.isEmpty) var p = lhs.lowerBound var q = rhs.lowerBound repeat { swapAt(p, q) formIndex(after: &p) formIndex(after: &q) } while p != lhs.upperBound && q != rhs.upperBound return (p, q) } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotate(shiftingToStart middle: Index) -> Index { var m = middle var s = startIndex let e = endIndex // Handle the trivial cases if s == m { return e } if m == e { return s } // We have two regions of possibly-unequal length that need to be // exchanged. The return value of this method is going to be the // position following that of the element that is currently last // (element j). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e // var ret = e // start with a known incorrect result. while true { // Exchange the leading elements of each region (up to the // length of the shorter region). // // [a b c d e f g|h i j] or [a b c|d e f g h i j] // ^^^^^ ^^^^^ ^^^^^ ^^^^^ // [h i j d e f g|a b c] or [d e f|a b c g h i j] // ^ ^ ^ ^ ^ ^ ^ ^ // s s1 m m1/e s s1/m m1 e // let (s1, m1) = _swapNonemptySubrangePrefixes(s..<m, m..<e) if m1 == e { // Left-hand case: we have moved element j into position. if // we haven't already, we can capture the return value which // is in s1. // // Note: the STL breaks the loop into two just to avoid this // comparison once the return value is known. I'm not sure // it's a worthwhile optimization, though. if ret == e { ret = s1 } // If both regions were the same size, we're done. if s1 == m { break } } // Now we have a smaller problem that is also a rotation, so we // can adjust our bounds and repeat. // // h i j[d e f g|a b c] or d e f[a b c|g h i j] // ^ ^ ^ ^ ^ ^ // s m e s m e s = s1 if s == m { m = m1 } } return ret } } extension MutableCollection where Self: BidirectionalCollection { /// Reverses the elements of the collection, moving from each end until /// `limit` is reached from either direction. The returned indices are the /// start and end of the range of unreversed elements. /// /// Input: /// [a b c d e f g h i j k l m n o p] /// ^ /// limit /// Output: /// [p o n m e f g h i j k l d c b a] /// ^ ^ /// f l /// /// - Postcondition: For returned indices `(f, l)`: /// `f == limit || l == limit` @inline(__always) @discardableResult internal mutating func _reverseUntil(_ limit: Index) -> (Index, Index) { var f = startIndex var l = endIndex while f != limit && l != limit { formIndex(before: &l) swapAt(f, l) formIndex(after: &f) } return (f, l) } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotate(shiftingToStart middle: Index) -> Index { // FIXME: this algorithm should be benchmarked on arrays against // the forward Collection algorithm above to prove that it's // actually faster. The other one sometimes does more swaps, but // has better locality properties. Similarly, we've omitted a // specialization of rotate for RandomAccessCollection that uses // cycles per section 11.4 in "From Mathematics to Generic // Programming" by A. Stepanov because it has *much* worse // locality properties than either of the other implementations. // Benchmarks should be performed for that algorithm too, just to // be sure. self[..<middle].reverse() self[middle...].reverse() let (p, q) = _reverseUntil(middle) self[p..<q].reverse() return middle == p ? q : p } } /// Returns the greatest common denominator for `m` and `n`. internal func _gcd(_ m: Int, _ n: Int) -> Int { var (m, n) = (m, n) while n != 0 { let t = m % n m = n n = t } return m } extension MutableCollection where Self: RandomAccessCollection { /// Rotates elements through a cycle, using `sourceForIndex` to generate /// the source index for each movement. @inline(__always) internal mutating func _rotateCycle( start: Index, sourceOffsetForIndex: (Index) -> Int ) { let tmp = self[start] var i = start var j = index(start, offsetBy: sourceOffsetForIndex(start)) while j != start { self[i] = self[j] i = j j = index(j, offsetBy: sourceOffsetForIndex(j)) } self[i] = tmp } /// Rotates the elements of the collection so that the element /// at `middle` ends up first. /// /// - Returns: The new index of the element that was first /// pre-rotation. /// - Complexity: O(*n*) @discardableResult public mutating func rotateRandomAccess( shiftingToStart middle: Index ) -> Index { if middle == startIndex { return endIndex } if middle == endIndex { return startIndex } // The distance to move an element that is moving -> let plus = distance(from: startIndex, to: middle) // The distance to move an element that is moving <- let minus = distance(from: endIndex, to: middle) // The new pivot point, aka the destination for the first element let pivot = index(startIndex, offsetBy: -minus) // If the difference moving forward and backward are relative primes, // the entire rotation will be completed in one cycle. Otherwise, repeat // cycle, moving the start point forward with each cycle. let cycles = _gcd(numericCast(plus), -numericCast(minus)) for cycle in 1...cycles { _rotateCycle( start: index(startIndex, offsetBy: numericCast(cycle)), sourceOffsetForIndex: { $0 < pivot ? plus : minus }) } return pivot } } //===--- Concatenation ----------------------------------------------------===// //===----------------------------------------------------------------------===// // Concatenation improves on a flattened array or other collection by // allowing random-access traversal if the underlying collections are // random-access. /// A concatenation of two sequences with the same element type. public struct Concatenation<Base1: Sequence, Base2: Sequence>: Sequence where Base1.Element == Base2.Element { let _base1: Base1 let _base2: Base2 init(_base1: Base1, base2: Base2) { self._base1 = _base1 self._base2 = base2 } public struct Iterator: IteratorProtocol { var _iterator1: Base1.Iterator var _iterator2: Base2.Iterator init(_ concatenation: Concatenation) { _iterator1 = concatenation._base1.makeIterator() _iterator2 = concatenation._base2.makeIterator() } public mutating func next() -> Base1.Element? { return _iterator1.next() ?? _iterator2.next() } } public func makeIterator() -> Iterator { Iterator(self) } } extension Concatenation: Collection where Base1: Collection, Base2: Collection { /// A position in a `Concatenation`. public struct Index: Comparable { internal enum _Representation: Equatable { case first(Base1.Index) case second(Base2.Index) } /// Creates a new index into the first underlying collection. internal init(first i: Base1.Index) { _position = .first(i) } /// Creates a new index into the second underlying collection. internal init(second i: Base2.Index) { _position = .second(i) } internal let _position: _Representation public static func < (lhs: Index, rhs: Index) -> Bool { switch (lhs._position, rhs._position) { case (.first, .second): return true case (.second, .first): return false case let (.first(l), .first(r)): return l < r case let (.second(l), .second(r)): return l < r } } } public var startIndex: Index { // If `_base1` is empty, then `_base2.startIndex` is either a valid position // of an element or equal to `_base2.endIndex`. return _base1.isEmpty ? Index(second: _base2.startIndex) : Index(first: _base1.startIndex) } public var endIndex: Index { return Index(second: _base2.endIndex) } public subscript(i: Index) -> Base1.Element { switch i._position { case let .first(i): return _base1[i] case let .second(i): return _base2[i] } } public func index(after i: Index) -> Index { switch i._position { case let .first(i): assert(i != _base1.endIndex) let next = _base1.index(after: i) return next == _base1.endIndex ? Index(second: _base2.startIndex) : Index(first: next) case let .second(i): return Index(second: _base2.index(after: i)) } } } extension Concatenation: BidirectionalCollection where Base1: BidirectionalCollection, Base2: BidirectionalCollection { public func index(before i: Index) -> Index { assert(i != startIndex, "Can't advance before startIndex") switch i._position { case let .first(i): return Index(first: _base1.index(before: i)) case let .second(i): return i == _base2.startIndex ? Index(first: _base1.index(before: _base1.endIndex)) : Index(second: _base2.index(before: i)) } } } extension Concatenation: RandomAccessCollection where Base1: RandomAccessCollection, Base2: RandomAccessCollection { public func index(_ i: Index, offsetBy n: Int) -> Index { if n == 0 { return i } return n > 0 ? _offsetForward(i, by: n) : _offsetBackward(i, by: -n) } internal func _offsetForward( _ i: Index, by n: Int ) -> Index { switch i._position { case let .first(i): let d: Int = _base1.distance(from: i, to: _base1.endIndex) if n < d { return Index(first: _base1.index(i, offsetBy: numericCast(n))) } else { return Index( second: _base2.index(_base2.startIndex, offsetBy: numericCast(n - d))) } case let .second(i): return Index(second: _base2.index(i, offsetBy: numericCast(n))) } } internal func _offsetBackward( _ i: Index, by n: Int ) -> Index { switch i._position { case let .first(i): return Index(first: _base1.index(i, offsetBy: -numericCast(n))) case let .second(i): let d: Int = _base2.distance(from: _base2.startIndex, to: i) if n <= d { return Index(second: _base2.index(i, offsetBy: -numericCast(n))) } else { return Index( first: _base1.index(_base1.endIndex, offsetBy: -numericCast(n - d))) } } } } /// Returns a new collection that presents a view onto the elements of the /// first collection and then the elements of the second collection. func concatenate<S1: Sequence, S2: Sequence>( _ first: S1, _ second: S2 ) -> Concatenation<S1, S2> where S1.Element == S2.Element { return Concatenation(_base1: first, base2: second) } extension Sequence { func followed<S: Sequence>(by other: S) -> Concatenation<Self, S> where Element == S.Element { return concatenate(self, other) } } //===--- RotatedCollection ------------------------------------------------===// //===----------------------------------------------------------------------===// /// A rotated view onto a collection. public struct RotatedCollection<Base: Collection>: Collection { let _base: Base let _indices: Concatenation<Base.Indices, Base.Indices> init(_base: Base, shiftingToStart i: Base.Index) { self._base = _base self._indices = concatenate(_base.indices[i...], _base.indices[..<i]) } /// A position in a rotated collection. public struct Index: Comparable { internal let _index: Concatenation<Base.Indices, Base.Indices>.Index public static func < (lhs: Index, rhs: Index) -> Bool { return lhs._index < rhs._index } } public var startIndex: Index { return Index(_index: _indices.startIndex) } public var endIndex: Index { return Index(_index: _indices.endIndex) } public subscript(i: Index) -> Base.SubSequence.Element { return _base[_indices[i._index]] } public func index(after i: Index) -> Index { return Index(_index: _indices.index(after: i._index)) } public func index(_ i: Index, offsetBy n: Int) -> Index { return Index(_index: _indices.index(i._index, offsetBy: n)) } public func distance(from start: Index, to end: Index) -> Int { return _indices.distance(from: start._index, to: end._index) } /// The shifted position of the base collection's `startIndex`. public var shiftedStartIndex: Index { return Index( _index: Concatenation<Base.Indices, Base.Indices>.Index( second: _indices._base2.startIndex) ) } public func rotated(shiftingToStart i: Index) -> RotatedCollection<Base> { return RotatedCollection(_base: _base, shiftingToStart: _indices[i._index]) } } extension RotatedCollection: BidirectionalCollection where Base: BidirectionalCollection { public func index(before i: Index) -> Index { return Index(_index: _indices.index(before: i._index)) } } extension RotatedCollection: RandomAccessCollection where Base: RandomAccessCollection {} extension Collection { /// Returns a view of this collection with the elements reordered such the /// element at the given position ends up first. /// /// The subsequence of the collection up to `i` is shifted to after the /// subsequence starting at `i`. The order of the elements within each /// partition is otherwise unchanged. /// /// let a = [10, 20, 30, 40, 50, 60, 70] /// let r = a.rotated(shiftingToStart: 3) /// // r.elementsEqual([40, 50, 60, 70, 10, 20, 30]) /// /// - Parameter i: The position in the collection that should be first in the /// result. `i` must be a valid index of the collection. /// - Returns: A rotated view on the elements of this collection, such that /// the element at `i` is first. func rotated(shiftingToStart i: Index) -> RotatedCollection<Self> { return RotatedCollection(_base: self, shiftingToStart: i) } } //===--- Stable Partition -------------------------------------------------===// //===----------------------------------------------------------------------===// extension MutableCollectionAlgorithms { /// Moves all elements satisfying `isSuffixElement` into a suffix of the /// collection, preserving their relative order, and returns the start of the /// resulting suffix. /// /// - Complexity: O(n) where n is the number of elements. @discardableResult mutating func stablePartition( isSuffixElement: (Element) throws -> Bool ) rethrows -> Index { return try stablePartition(count: count, isSuffixElement: isSuffixElement) } /// Moves all elements satisfying `isSuffixElement` into a suffix of the /// collection, preserving their relative order, and returns the start of the /// resulting suffix. /// /// - Complexity: O(n) where n is the number of elements. /// - Precondition: `n == self.count` fileprivate mutating func stablePartition( count n: Int, isSuffixElement: (Element) throws -> Bool ) rethrows -> Index { if n == 0 { return startIndex } if n == 1 { return try isSuffixElement(self[startIndex]) ? startIndex : endIndex } let h = n / 2 let i = index(startIndex, offsetBy: h) let j = try self[..<i].stablePartition( count: h, isSuffixElement: isSuffixElement) let k = try self[i...].stablePartition( count: n - h, isSuffixElement: isSuffixElement) return self[j..<k].rotate(shiftingToStart: i) } } extension Collection { func stablyPartitioned( isSuffixElement p: (Element) -> Bool ) -> [Element] { var a = Array(self) a.stablePartition(isSuffixElement: p) return a } } extension LazyCollectionProtocol where Element == Elements.Element, Elements: Collection { func stablyPartitioned( isSuffixElement p: (Element) -> Bool ) -> LazyCollection<[Element]> { return elements.stablyPartitioned(isSuffixElement: p).lazy } } extension Collection { /// Returns the index of the first element in the collection /// that matches the predicate. /// /// The collection must already be partitioned according to the /// predicate, as if `self.partition(by: predicate)` had already /// been called. /// /// - Efficiency: At most log(N) invocations of `predicate`, where /// N is the length of `self`. At most log(N) index offsetting /// operations if `self` conforms to `RandomAccessCollection`; /// at most N such operations otherwise. func partitionPoint( where predicate: (Element) throws -> Bool ) rethrows -> Index { var n = distance(from: startIndex, to: endIndex) var l = startIndex while n > 0 { let half = n / 2 let mid = index(l, offsetBy: half) if try predicate(self[mid]) { n = half } else { l = index(after: mid) n -= half + 1 } } return l } }
7c79318fe598643e275202e1d67bc291
31.862559
80
0.606384
false
false
false
false
shelleyweiss/softsurvey
refs/heads/master
SoftSurvey/SoftQuestion.swift
artistic-2.0
1
// // SoftQuestion.swift // SoftSurvey // // Created by shelley weiss on 3/4/15. // Copyright (c) 2015 shelley weiss. All rights reserved. // import UIKit class SoftQuestion { let value: Int! let question: String! var response: String? = nil //let content: String private enum Answer { case Single(NSArray) case Multiple(String) case FreeText(String, String -> String) } //private var answerStack = [Answer]() var optionalAnswers: [String]! = [] //var isAnswered: Bool = false init(value: Int, text: String)//answers: [String]) { self.question = text self.value = value optionalAnswers.append( "") } convenience init() { //Rule 2: Calling another initializer in same class self.init( value:-2 , text: "Nothing" ) } func pushAnswer(answer: String ) { if optionalAnswers.count <= 4 { self.optionalAnswers.append(answer) } } func ask(index : Int) -> String { var result = "" if !optionalAnswers.isEmpty { result = optionalAnswers[index] } return result } /*private func popAnswer()->Answer { return answerStack.removeLast() } func pushMultiple(answer: String ) { answerStack.append(Answer.Multiple(answer)) } func pushSingle(answer: NSDictionary ) { answerStack.append(Answer.Single(answer)) } func pushFreeText(index: Int) { if (isAnswered) { } }*/ private func evaluate(answers: [Answer]) -> ( result: NSDictionary?, remainingAnswers: [Answer] ) { if !answers.isEmpty { var remainingAnswers = answers let answer = remainingAnswers.removeLast() switch answer{ case .Single (let a ): println("Single") case .Multiple: println("Multiple") case .FreeText: println("FreeText") } } return ( nil, answers) } private func performOperation(operation: Answer) { switch operation { case .Single: println("Single") case .Multiple: println("Multiple") case .FreeText: println("FreeText") } } }
775d29268277ea25f4c1630e2c4ff2df
19.061069
101
0.493338
false
false
false
false
andrucuna/ios
refs/heads/master
Swiftris/Swiftris/GameScene.swift
gpl-2.0
1
// // GameScene.swift // Swiftris // // Created by Andrés Ruiz on 9/24/14. // Copyright (c) 2014 Andrés Ruiz. All rights reserved. // import SpriteKit // We simply define the point size of each block sprite - in our case 20.0 x 20.0 - the lower of the // available resolution options for each block image. We also declare a layer position which will give us an // offset from the edge of the screen. let BlockSize:CGFloat = 20.0 // This variable will represent the slowest speed at which our shapes will travel. let TickLengthLevelOne = NSTimeInterval(600) class GameScene: SKScene { // #2 let gameLayer = SKNode() let shapeLayer = SKNode() let LayerPosition = CGPoint(x: 6, y: -6) // In tick, its type is (() -> ())? which means that it's a closure which takes no parameters and // returns nothing. Its question mark indicates that it is optional and therefore may be nil. var tick: (() ->())? var tickLengthMillis = TickLengthLevelOne var lastTick: NSDate? var textureCache = Dictionary<String, SKTexture>() required init( coder aDecoder: (NSCoder!) ) { fatalError( "NSCoder not supported" ) } override init( size: CGSize ) { super.init( size: size ) anchorPoint = CGPoint( x: 0, y: 1.0 ) let background = SKSpriteNode( imageNamed: "background" ) background.position = CGPoint( x: 0, y: 0 ) background.anchorPoint = CGPoint( x: 0, y: 1.0 ) addChild( background ) addChild(gameLayer) let gameBoardTexture = SKTexture(imageNamed: "gameboard") let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(BlockSize * CGFloat(NumColumns), BlockSize * CGFloat(NumRows))) gameBoard.anchorPoint = CGPoint(x:0, y:1.0) gameBoard.position = LayerPosition shapeLayer.position = LayerPosition shapeLayer.addChild(gameBoard) gameLayer.addChild(shapeLayer) // We set up a looping sound playback action of our theme song. runAction(SKAction.repeatActionForever(SKAction.playSoundFileNamed("theme.mp3", waitForCompletion: true))) } // We added a method which GameViewController may use to play any sound file on demand. func playSound(sound:String) { runAction(SKAction.playSoundFileNamed(sound, waitForCompletion: false)) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ // If lastTick is missing, we are in a paused state, not reporting elapsed ticks to anyone, // therefore we simply return. if lastTick == nil { return } var timePassed = lastTick!.timeIntervalSinceNow * -1000.0 if timePassed > tickLengthMillis { lastTick = NSDate.date() tick?() } } // We provide accessor methods to let external classes stop and start the ticking process. func startTicking() { lastTick = NSDate.date() } func stopTicking() { lastTick = nil } // The math here looks funky but just know that each sprite will be anchored at its center, therefore we // need to find its center coordinate before placing it in our shapeLayer object. func pointForColumn(column: Int, row: Int) -> CGPoint { let x: CGFloat = LayerPosition.x + (CGFloat(column) * BlockSize) + (BlockSize / 2) let y: CGFloat = LayerPosition.y - ((CGFloat(row) * BlockSize) + (BlockSize / 2)) return CGPointMake(x, y) } func addPreviewShapeToScene(shape:Shape, completion:() -> ()) { for (idx, block) in enumerate(shape.blocks) { // We've created a method which will add a shape for the first time to the scene as a preview // shape. We use a dictionary to store copies of re-usable SKTexture objects since each shape // will require multiple copies of the same image. var texture = textureCache[block.spriteName] if texture == nil { texture = SKTexture(imageNamed: block.spriteName) textureCache[block.spriteName] = texture } let sprite = SKSpriteNode(texture: texture) // We use our convenient pointForColumn(Int, Int) method to place each block's sprite in the // proper location. We start it at row - 2, such that the preview piece animates smoothly into // place from a higher location. sprite.position = pointForColumn(block.column, row:block.row - 2) shapeLayer.addChild(sprite) block.sprite = sprite // Animation sprite.alpha = 0 // We introduce SKAction objects which are responsible for visually manipulating SKNode objects. // Each block will fade and move into place as it appears as part of the next piece. It will // move two rows down and fade from complete transparency to 70% opacity. let moveAction = SKAction.moveTo(pointForColumn(block.column, row: block.row), duration: NSTimeInterval(0.2)) moveAction.timingMode = .EaseOut let fadeInAction = SKAction.fadeAlphaTo(0.7, duration: 0.4) fadeInAction.timingMode = .EaseOut sprite.runAction(SKAction.group([moveAction, fadeInAction])) } runAction(SKAction.waitForDuration(0.4), completion: completion) } func movePreviewShape(shape:Shape, completion:() -> ()) { for (idx, block) in enumerate(shape.blocks) { let sprite = block.sprite! let moveTo = pointForColumn(block.column, row:block.row) let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.2) moveToAction.timingMode = .EaseOut sprite.runAction( SKAction.group([moveToAction, SKAction.fadeAlphaTo(1.0, duration: 0.2)]), completion:nil) } runAction(SKAction.waitForDuration(0.2), completion: completion) } func redrawShape(shape:Shape, completion:() -> ()) { for (idx, block) in enumerate(shape.blocks) { let sprite = block.sprite! let moveTo = pointForColumn(block.column, row:block.row) let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: 0.05) moveToAction.timingMode = .EaseOut sprite.runAction(moveToAction, completion: nil) } runAction(SKAction.waitForDuration(0.05), completion: completion) } // You can see that we take in precisely the tuple data which Swiftris returns each time a line is // removed. This will ensure that GameViewController need only pass those elements to GameScene in order // for them to animate properly. func animateCollapsingLines(linesToRemove: Array<Array<Block>>, fallenBlocks: Array<Array<Block>>, completion:() -> ()) { var longestDuration: NSTimeInterval = 0 // We also established a longestDuration variable which will determine precisely how long we should // wait before calling the completion closure. for (columnIdx, column) in enumerate(fallenBlocks) { for (blockIdx, block) in enumerate(column) { let newPosition = pointForColumn(block.column, row: block.row) let sprite = block.sprite! // We wrote code which will produce this pleasing effect for eye balls to enjoy. Based on // the block and column indices, we introduce a directly proportional delay. let delay = (NSTimeInterval(columnIdx) * 0.05) + (NSTimeInterval(blockIdx) * 0.05) let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / BlockSize) * 0.1) let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), moveAction])) longestDuration = max(longestDuration, duration + delay) } } for (rowIdx, row) in enumerate(linesToRemove) { for (blockIdx, block) in enumerate(row) { // We make their blocks shoot off the screen like explosive debris. In order to accomplish // this we will employ UIBezierPath. Our arch requires a radius and we've chosen to generate // one randomly in order to introduce a natural variance among the explosive paths. // Furthermore, we've randomized whether the block flies left or right. let randomRadius = CGFloat(UInt(arc4random_uniform(400) + 100)) let goLeft = arc4random_uniform(100) % 2 == 0 var point = pointForColumn(block.column, row: block.row) point = CGPointMake(point.x + (goLeft ? -randomRadius : randomRadius), point.y) let randomDuration = NSTimeInterval(arc4random_uniform(2)) + 0.5 // We choose beginning and starting angles, these are clearly in radians // When going left, we begin at 0 radians and end at π. When going right, we go from π to // 2π. Math FTW! var startAngle = CGFloat(M_PI) var endAngle = startAngle * 2 if goLeft { endAngle = startAngle startAngle = 0 } let archPath = UIBezierPath(arcCenter: point, radius: randomRadius, startAngle: startAngle, endAngle: endAngle, clockwise: goLeft) let archAction = SKAction.followPath(archPath.CGPath, asOffset: false, orientToPath: true, duration: randomDuration) archAction.timingMode = .EaseIn let sprite = block.sprite! // We place the block sprite above the others such that they animate above the other blocks // and begin the sequence of actions which concludes with the sprite being removed from the // scene. sprite.zPosition = 100 sprite.runAction( SKAction.sequence( [SKAction.group([archAction, SKAction.fadeOutWithDuration(NSTimeInterval(randomDuration))]), SKAction.removeFromParent()])) } } // We run the completion action after a duration matching the time it will take to drop the last // block to its new resting place. runAction(SKAction.waitForDuration(longestDuration), completion:completion) } }
e15e3283b7d09287f97266f75bbabeda
44.040984
146
0.612739
false
false
false
false
ruddfawcett/Notepad
refs/heads/master
Notepad/Storage.swift
mit
1
// // Storage.swift // Notepad // // Created by Rudd Fawcett on 10/14/16. // Copyright © 2016 Rudd Fawcett. All rights reserved. // #if os(iOS) import UIKit #elseif os(macOS) import AppKit #endif public class Storage: NSTextStorage { /// The Theme for the Notepad. public var theme: Theme? { didSet { let wholeRange = NSRange(location: 0, length: (self.string as NSString).length) self.beginEditing() self.applyStyles(wholeRange) self.edited(.editedAttributes, range: wholeRange, changeInLength: 0) self.endEditing() } } /// The underlying text storage implementation. var backingStore = NSTextStorage() override public var string: String { get { return backingStore.string } } override public init() { super.init() } override public init(attributedString attrStr: NSAttributedString) { super.init(attributedString:attrStr) backingStore.setAttributedString(attrStr) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required public init(itemProviderData data: Data, typeIdentifier: String) throws { fatalError("init(itemProviderData:typeIdentifier:) has not been implemented") } #if os(macOS) required public init?(pasteboardPropertyList propertyList: Any, ofType type: String) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } required public init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } #endif /// Finds attributes within a given range on a String. /// /// - parameter location: How far into the String to look. /// - parameter range: The range to find attributes for. /// /// - returns: The attributes on a String within a certain range. override public func attributes(at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> [NSAttributedString.Key : Any] { return backingStore.attributes(at: location, longestEffectiveRange: range, in: rangeLimit) } /// Replaces edited characters within a certain range with a new string. /// /// - parameter range: The range to replace. /// - parameter str: The new string to replace the range with. override public func replaceCharacters(in range: NSRange, with str: String) { self.beginEditing() backingStore.replaceCharacters(in: range, with: str) let len = (str as NSString).length let change = len - range.length self.edited([.editedCharacters, .editedAttributes], range: range, changeInLength: change) self.endEditing() } /// Sets the attributes on a string for a particular range. /// /// - parameter attrs: The attributes to add to the string for the range. /// - parameter range: The range in which to add attributes. public override func setAttributes(_ attrs: [NSAttributedString.Key : Any]?, range: NSRange) { self.beginEditing() backingStore.setAttributes(attrs, range: range) self.edited(.editedAttributes, range: range, changeInLength: 0) self.endEditing() } /// Retrieves the attributes of a string for a particular range. /// /// - parameter at: The location to begin with. /// - parameter range: The range in which to retrieve attributes. public override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key : Any] { return backingStore.attributes(at: location, effectiveRange: range) } /// Processes any edits made to the text in the editor. override public func processEditing() { let backingString = backingStore.string if let nsRange = backingString.range(from: NSMakeRange(NSMaxRange(editedRange), 0)) { let indexRange = backingString.lineRange(for: nsRange) let extendedRange: NSRange = NSUnionRange(editedRange, backingString.nsRange(from: indexRange)) applyStyles(extendedRange) } super.processEditing() } /// Applies styles to a range on the backingString. /// /// - parameter range: The range in which to apply styles. func applyStyles(_ range: NSRange) { guard let theme = self.theme else { return } let backingString = backingStore.string backingStore.setAttributes(theme.body.attributes, range: range) for (style) in theme.styles { style.regex.enumerateMatches(in: backingString, options: .withoutAnchoringBounds, range: range, using: { (match, flags, stop) in guard let match = match else { return } backingStore.addAttributes(style.attributes, range: match.range(at: 0)) }) } } }
590a8fe9694517f26a7ab57beef2bf60
36.932331
159
0.661447
false
false
false
false
tomboates/BrilliantSDK
refs/heads/master
Pod/Classes/NPSScoreViewController.swift
mit
1
// // NSPScoreViewController.swift // Pods // // Created by Phillip Connaughton on 1/24/16. // // import Foundation protocol NPSScoreViewControllerDelegate: class{ func closePressed(_ state: SurveyViewControllerState) func npsScorePressed(_ npsScore: Int) } class NPSScoreViewController : UIViewController { @IBOutlet var closeButton: UIButton! @IBOutlet var questionLabel: UILabel! @IBOutlet var button0: UIButton! @IBOutlet var button1: UIButton! @IBOutlet var button2: UIButton! @IBOutlet var button3: UIButton! @IBOutlet var button4: UIButton! @IBOutlet var button5: UIButton! @IBOutlet var button6: UIButton! @IBOutlet var button7: UIButton! @IBOutlet var button8: UIButton! @IBOutlet var button9: UIButton! @IBOutlet var button10: UIButton! @IBOutlet weak var notLikelyBtn: UILabel! @IBOutlet weak var likelyBtn: UILabel! @IBOutlet var labelWidthConstraint: NSLayoutConstraint! internal weak var delegate : NPSScoreViewControllerDelegate? override func viewDidLoad() { let image = UIImage(named: "brilliant-icon-close", in:Brilliant.imageBundle(), compatibleWith: nil) self.closeButton.setImage(image, for: UIControlState()) self.closeButton.imageEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 25, right: 25) self.questionLabel.textColor = Brilliant.sharedInstance().mainLabelColor() self.questionLabel.font = Brilliant.sharedInstance().mainLabelFont() if (Brilliant.sharedInstance().appName != nil) { self.questionLabel.text = String(format: "How likely is it that you will recommend %@ to a friend or colleague?", Brilliant.sharedInstance().appName!) } else { self.questionLabel.text = "How likely is it that you will recommend this app to a friend or colleague?" } self.button0.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button1.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button2.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button3.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button4.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button5.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button6.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button7.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button8.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button9.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button10.tintColor = Brilliant.sharedInstance().npsButtonColor() self.button0.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button1.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button2.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button3.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button4.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button5.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button6.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button7.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button8.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button9.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.button10.titleLabel!.font = Brilliant.sharedInstance().npsButtonFont() self.notLikelyBtn.font = Brilliant.sharedInstance().levelLabelFont() self.likelyBtn.font = Brilliant.sharedInstance().levelLabelFont() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // self.updateConstraints() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { (completion) in // self.updateConstraints() } } func updateConstraints() { let size = UIDeviceHelper.deviceWidth() switch size { case .small: self.labelWidthConstraint.constant = 280 break case .medium: self.labelWidthConstraint.constant = 300 break case .large: self.labelWidthConstraint.constant = 420 break } } @IBAction func closePressed(_ sender: AnyObject) { Brilliant.sharedInstance().completedSurvey!.dismissAction = "x_npsscreen" self.delegate?.closePressed(.ratingScreen) } @IBAction func zeroPressed(_ sender: AnyObject) { self.npsNumberResponse(0) } @IBAction func onePressed(_ sender: AnyObject) { self.npsNumberResponse(1) } @IBAction func twoPressed(_ sender: AnyObject) { self.npsNumberResponse(2) } @IBAction func threePressed(_ sender: AnyObject) { self.npsNumberResponse(3) } @IBAction func fourPressed(_ sender: AnyObject) { self.npsNumberResponse(4) } @IBAction func fivePressed(_ sender: AnyObject) { self.npsNumberResponse(5) } @IBAction func sixPressed(_ sender: AnyObject) { self.npsNumberResponse(6) } @IBAction func sevenPressed(_ sender: AnyObject) { self.npsNumberResponse(7) } @IBAction func eightPressed(_ sender: AnyObject) { self.npsNumberResponse(8) } @IBAction func ninePressed(_ sender: AnyObject) { self.npsNumberResponse(9) } @IBAction func tenPressed(_ sender: AnyObject) { self.npsNumberResponse(10) } func npsNumberResponse(_ npsNumber: Int) { Brilliant.sharedInstance().completedSurvey!.npsRating = npsNumber self.delegate?.npsScorePressed(npsNumber) } }
9f8df59c99410f5d9017bc129212b310
35.350877
162
0.670367
false
false
false
false
daltoniam/JSONJoy-Swift
refs/heads/master
Source/JSONJoy.swift
apache-2.0
1
////////////////////////////////////////////////////////////////////////////////////////////////// // // JSONJoy.swift // // Created by Dalton Cherry on 9/17/14. // Copyright (c) 2014 Vluxe. All rights reserved. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation public protocol JSONBasicType {} extension String: JSONBasicType {} extension Int: JSONBasicType {} extension UInt: JSONBasicType {} extension Double: JSONBasicType {} extension Float: JSONBasicType {} extension NSNumber: JSONBasicType {} extension Bool: JSONBasicType {} public enum JSONError: Error { case wrongType } open class JSONLoader { var value: Any? /** Converts any raw object like a String or Data into a JSONJoy object */ public init(_ raw: Any, isSub: Bool = false) { var rawObject: Any = raw if let str = rawObject as? String, !isSub { rawObject = str.data(using: String.Encoding.utf8)! as Any } if let data = rawObject as? Data { var response: Any? do { try response = JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) rawObject = response! } catch let error as NSError { value = error return } } if let array = rawObject as? NSArray { var collect = [JSONLoader]() for val: Any in array { collect.append(JSONLoader(val, isSub: true)) } value = collect as Any? } else if let dict = rawObject as? NSDictionary { var collect = Dictionary<String,JSONLoader>() for (key,val) in dict { collect[key as! String] = JSONLoader(val as AnyObject, isSub: true) } value = collect as Any? } else { value = rawObject } } /** get typed `Array` of `JSONJoy` and have it throw if it doesn't work */ public func get<T: JSONJoy>() throws -> [T] { guard let a = getOptionalArray() else { throw JSONError.wrongType } return try a.reduce([T]()) { $0 + [try T($1)] } } /** get typed `Array` and have it throw if it doesn't work */ open func get<T: JSONBasicType>() throws -> [T] { guard let a = getOptionalArray() else { throw JSONError.wrongType } return try a.reduce([T]()) { $0 + [try $1.get()] } } /** get any type and have it throw if it doesn't work */ open func get<T>() throws -> T { if let val = value as? Error { throw val } guard let val = value as? T else {throw JSONError.wrongType} return val } /** get any type as an optional */ open func getOptional<T>() -> T? { do { return try get() } catch { return nil } } /** get an array */ open func getOptionalArray() -> [JSONLoader]? { return value as? [JSONLoader] } /** get typed `Array` of `JSONJoy` as an optional */ public func getOptional<T: JSONJoy>() -> [T]? { guard let a = getOptionalArray() else { return nil } do { return try a.reduce([T]()) { $0 + [try T($1)] } } catch { return nil } } /** get typed `Array` of `JSONJoy` as an optional */ public func getOptional<T: JSONBasicType>() -> [T]? { guard let a = getOptionalArray() else { return nil } do { return try a.reduce([T]()) { $0 + [try $1.get()] } } catch { return nil } } /** Array access support */ open subscript(index: Int) -> JSONLoader { get { if let array = value as? NSArray { if array.count > index { return array[index] as! JSONLoader } } return JSONLoader(createError("index: \(index) is greater than array or this is not an Array type.")) } } /** Dictionary access support */ open subscript(key: String) -> JSONLoader { get { if let dict = value as? NSDictionary { if let value: Any = dict[key] { return value as! JSONLoader } } return JSONLoader(createError("key: \(key) does not exist or this is not a Dictionary type")) } } /** Simple helper method to create an error */ func createError(_ text: String) -> Error { return NSError(domain: "JSONJoy", code: 1002, userInfo: [NSLocalizedDescriptionKey: text]) as Error } } /** Implement this protocol on all objects you want to use JSONJoy with */ public protocol JSONJoy { init(_ decoder: JSONLoader) throws } extension JSONLoader: CustomStringConvertible { public var description: String { if let value = value { return String(describing: value) } else { return String(describing: value) } } } extension JSONLoader: CustomDebugStringConvertible { public var debugDescription: String { if let value = value { return String(reflecting: value) } else { return String(reflecting: value) } } }
1b95adcf505da81b6202c639fac39392
27.898396
116
0.523131
false
false
false
false
jacobwhite/firefox-ios
refs/heads/master
Shared/UserAgent.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 AVFoundation import UIKit open class UserAgent { private static var defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! private static func clientUserAgent(prefix: String) -> String { return "\(prefix)/\(AppInfo.appVersion)b\(AppInfo.buildNumber) (\(DeviceInfo.deviceModel()); iPhone OS \(UIDevice.current.systemVersion)) (\(AppInfo.displayName))" } open static var syncUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Sync") } open static var tokenServerClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-Token") } open static var fxaUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS-FxA") } open static var defaultClientUserAgent: String { return clientUserAgent(prefix: "Firefox-iOS") } /** * Use this if you know that a value must have been computed before your * code runs, or you don't mind failure. */ open static func cachedUserAgent(checkiOSVersion: Bool = true, checkFirefoxVersion: Bool = true, checkFirefoxBuildNumber: Bool = true) -> String? { let currentiOSVersion = UIDevice.current.systemVersion let lastiOSVersion = defaults.string(forKey: "LastDeviceSystemVersionNumber") let currentFirefoxBuildNumber = AppInfo.buildNumber let currentFirefoxVersion = AppInfo.appVersion let lastFirefoxVersion = defaults.string(forKey: "LastFirefoxVersionNumber") let lastFirefoxBuildNumber = defaults.string(forKey: "LastFirefoxBuildNumber") if let firefoxUA = defaults.string(forKey: "UserAgent") { if (!checkiOSVersion || (lastiOSVersion == currentiOSVersion)) && (!checkFirefoxVersion || (lastFirefoxVersion == currentFirefoxVersion) && (!checkFirefoxBuildNumber || (lastFirefoxBuildNumber == currentFirefoxBuildNumber))) { return firefoxUA } } return nil } /** * This will typically return quickly, but can require creation of a UIWebView. * As a result, it must be called on the UI thread. */ open static func defaultUserAgent() -> String { assert(Thread.current.isMainThread, "This method must be called on the main thread.") if let firefoxUA = UserAgent.cachedUserAgent(checkiOSVersion: true) { return firefoxUA } let webView = UIWebView() let appVersion = AppInfo.appVersion let buildNumber = AppInfo.buildNumber let currentiOSVersion = UIDevice.current.systemVersion defaults.set(currentiOSVersion, forKey: "LastDeviceSystemVersionNumber") defaults.set(appVersion, forKey: "LastFirefoxVersionNumber") defaults.set(buildNumber, forKey: "LastFirefoxBuildNumber") let userAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")! // Extract the WebKit version and use it as the Safari version. let webKitVersionRegex = try! NSRegularExpression(pattern: "AppleWebKit/([^ ]+) ", options: []) let match = webKitVersionRegex.firstMatch(in: userAgent, options: [], range: NSRange(location: 0, length: userAgent.count)) if match == nil { print("Error: Unable to determine WebKit version in UA.") return userAgent // Fall back to Safari's. } let webKitVersion = (userAgent as NSString).substring(with: match!.range(at: 1)) // Insert "FxiOS/<version>" before the Mobile/ section. let mobileRange = (userAgent as NSString).range(of: "Mobile/") if mobileRange.location == NSNotFound { print("Error: Unable to find Mobile section in UA.") return userAgent // Fall back to Safari's. } let mutableUA = NSMutableString(string: userAgent) mutableUA.insert("FxiOS/\(appVersion)b\(AppInfo.buildNumber) ", at: mobileRange.location) let firefoxUA = "\(mutableUA) Safari/\(webKitVersion)" defaults.set(firefoxUA, forKey: "UserAgent") return firefoxUA } open static func desktopUserAgent() -> String { let userAgent = NSMutableString(string: defaultUserAgent()) // Spoof platform section let platformRegex = try! NSRegularExpression(pattern: "\\([^\\)]+\\)", options: []) guard let platformMatch = platformRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to determine platform in UA.") return String(userAgent) } userAgent.replaceCharacters(in: platformMatch.range, with: "(Macintosh; Intel Mac OS X 10_11_1)") // Strip mobile section let mobileRegex = try! NSRegularExpression(pattern: " FxiOS/[^ ]+ Mobile/[^ ]+", options: []) guard let mobileMatch = mobileRegex.firstMatch(in: userAgent as String, options: [], range: NSRange(location: 0, length: userAgent.length)) else { print("Error: Unable to find Mobile section in UA.") return String(userAgent) } userAgent.replaceCharacters(in: mobileMatch.range, with: "") return String(userAgent) } }
6bbea07fa94cedb387a401420e958b8d
41.450382
171
0.654738
false
false
false
false
Harshvk/CarsGalleryApp
refs/heads/master
ListToGridApp/ListCell.swift
mit
1
// // ListCell.swift // ListToGridApp // // Created by appinventiv on 13/02/17. // Copyright © 2017 appinventiv. All rights reserved. // import UIKit class ListCell: UICollectionViewCell { @IBOutlet weak var carPic: UIImageView! @IBOutlet weak var carName: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { self.backgroundColor = nil } func configureCell(withCar car: CarModel){ carPic.image = UIImage(named: car.image) carName.text = car.name carPic.layer.borderWidth = 1 carPic.layer.borderColor = UIColor.darkGray.cgColor } } class ProductsListFlowLayout: UICollectionViewFlowLayout { override init() { super.init() setupLayout() } /** Init method - parameter aDecoder: aDecoder - returns: self */ required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayout() } /** Sets up the layout for the collectionView. 0 distance between each cell, and vertical layout */ func setupLayout() { minimumInteritemSpacing = 0 minimumLineSpacing = 1 scrollDirection = .vertical } func itemWidth() -> CGFloat { return collectionView!.frame.width } override var itemSize: CGSize { set { self.itemSize = CGSize(width: itemWidth(), height: 89) } get { return CGSize(width: itemWidth(), height: 89) } } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { return collectionView!.contentOffset } }
fb96d40c6e51b62c05b9a81d1ca4eb26
20.104651
107
0.590634
false
false
false
false
fxdemolisher/newscats
refs/heads/master
ios/NewsCats/BridgeMethodWrapper.swift
apache-2.0
1
import React /** * Defines various kind of wrapped performers we support with our BridgeMethodWrapper. */ enum BridgeMethodWrappedPerformer { // A call from JS to native, without a return value or callback. case oneWay((RCTBridge, [Any]) throws -> Void) // A call from JS to native, providing a callback function to call on completion. // NOTE(gennadiy): The completion callback is expected to accept two parameters: error and result, in node.js style. case callback((RCTBridge, [Any], @escaping (Any?, Any?) -> Void) throws -> Void) // A call from JS to native, expecting a returned promise. case promise((RCTBridge, [Any], @escaping RCTPromiseResolveBlock, @escaping RCTPromiseRejectBlock) throws -> Void) } /** * A simple wrapper around swift functions and closures that can be exposed over an RN bridge. */ class BridgeMethodWrapper : NSObject, RCTBridgeMethod { private let name: String private let performer: BridgeMethodWrappedPerformer init(name: String, _ performer: BridgeMethodWrappedPerformer) { self.name = name self.performer = performer } public var jsMethodName: UnsafePointer<Int8>! { return UnsafePointer<Int8>(name) } public var functionType: RCTFunctionType { switch performer { case .promise: return .promise default: return .normal } } /** * Called by the RN bridge to invoke the native function wrapped by this instance. */ public func invoke(with bridge: RCTBridge!, module: Any!, arguments: [Any]!) -> Any! { switch performer { // One way calls are simple passthroughs, with void returns. case let .oneWay(closure): try! closure(bridge, arguments) return Void() // Callback wrappers pass all except the last parameter to the native code, and wrap the last parameter // in a swift completion closure. The native code being executed should use that closure to communicate // results back to JS. By convention the resulting call should contains two arguments: error and result. case let .callback(closure): let closureArgs = Array<Any>(arguments.prefix(upTo: arguments.count - 1)) let callbackClosure = { (error: Any?, result: Any?) -> Void in let callbackId = arguments.last as! NSNumber let errorActual = error ?? NSNull() let resultActual = result ?? NSNull() bridge.enqueueCallback(callbackId, args: [errorActual, resultActual]) } try! closure(bridge, closureArgs, callbackClosure) return Void() case let .promise(closure): let closureArgs = Array<Any>(arguments.prefix(upTo: arguments.count - 2)) let resolveBlockCallbackId = arguments[arguments.count - 2] as! NSNumber let resolveBlock: RCTPromiseResolveBlock = { value in bridge.enqueueCallback(resolveBlockCallbackId, args: [value ?? ""]) } let rejectBlockCallbackId = arguments[arguments.count - 1] as! NSNumber let rejectBlock: RCTPromiseRejectBlock = { tag, message, error in bridge.enqueueCallback(rejectBlockCallbackId, args: [tag!, message!, error!]) } do { try closure(bridge, closureArgs, resolveBlock, rejectBlock) } catch let error { rejectBlock("bridgeError", "Failed to call bridge function", error) } return Void() } } }
bf156546cf9cf6674525799ffda2e274
42.177778
120
0.594184
false
false
false
false
apurushottam/IPhone-Learning-Codes
refs/heads/master
Project 7-Easy Browser/Project 7-Easy Browser/WebsitesTableViewController.swift
apache-2.0
1
// // WebsitesTableViewController.swift // Project 7-Easy Browser // // Created by Ashutosh Purushottam on 9/28/15. // Copyright © 2015 Vivid Designs. All rights reserved. // import UIKit class WebsitesTableViewController: UITableViewController { var websites = ["apple.com", "hackingwithswift.com", "youtube.com"] override func viewDidLoad() { super.viewDidLoad() tableView.separatorStyle = .SingleLine } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return websites.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("WebsiteCell")! cell.textLabel?.text = websites[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // present new controller here let callingUrl = websites[indexPath.row] let newController = storyboard?.instantiateViewControllerWithIdentifier("WebViewController") as! ViewController newController.webUrl = callingUrl navigationController?.pushViewController(newController, animated: true) } }
e765465328bb41f04623ab2674a86212
29.636364
119
0.698071
false
false
false
false
AlexZd/SwiftUtils
refs/heads/master
Pod/Utils/UIView+Helpers/UIView+Helpers.swift
mit
1
// // UIView+Helpers.swift // // Created by Alex Zdorovets on 6/18/15. // Copyright (c) 2015 Alex Zdorovets. All rights reserved. // import UIKit extension UIView { public static func loadNib<T>() -> T { return Bundle.main.loadNibNamed(self.className, owner: self, options: nil)!.first as! T } /** Returns UIView's class name. */ public class var className: String { return NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last! } /** Returns UIView's nib. */ public class var nib: UINib { return UINib(nibName: self.className, bundle: nil) } /** Get value of height constraint of UIView*/ public var heightOfContstraint: CGFloat { let cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.height && $0.isMember(of: NSLayoutConstraint.self)}).first! return cnst.constant } /** Returns entity from it's nib. Nib should have same name as class name. */ public class func getFromNib() -> Any { return Bundle.main.loadNibNamed(self.className, owner: self, options: nil)!.first! } /** Changes UIView width constraint and updates for superview */ public func setWidth(width: CGFloat, update: Bool) { var cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.width && $0.isMember(of: NSLayoutConstraint.self)}).first if cnst == nil { if #available(iOS 9, *) { self.widthAnchor.constraint(equalToConstant: width).isActive = true } else { cnst = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) self.addConstraint(cnst!) } } cnst?.constant = width if update { self.updateConstraints() } } /** Changes UIView height constraint and updates for superview */ public func setHeight(height: CGFloat, update: Bool) { var cnst = constraints.filter({$0.firstAttribute == NSLayoutConstraint.Attribute.height && $0.isMember(of: NSLayoutConstraint.self)}).first if cnst == nil { if #available(iOS 9, *) { self.heightAnchor.constraint(equalToConstant: height).isActive = true } else { cnst = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height) self.addConstraint(cnst!) } } cnst?.constant = height if update { self.updateConstraints() } } /** Adds constraints to superview */ public func setEdgeConstaints(edges: UIEdgeInsets, update: Bool) { guard let superview = self.superview else { return } self.translatesAutoresizingMaskIntoConstraints = false let leading = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: superview, attribute: .leading, multiplier: 1, constant: edges.left) let trailing = NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: superview, attribute: .trailing, multiplier: 1, constant: -1 * edges.right) let top = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: superview, attribute: .top, multiplier: 1, constant: edges.top) let bottom = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: superview, attribute: .bottom, multiplier: 1, constant: -1 * edges.bottom) superview.addConstraints([top, leading, trailing, bottom]) if update { superview.updateConstraints() } } /** Perform shake animation for UIView*/ public func shake() { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 20, -20, 10, 0]; animation.keyTimes = [0, NSNumber(value: (1 / 6.0)), NSNumber(value: (3 / 6.0)), NSNumber(value: (5 / 6.0)), 1] animation.duration = 0.3 animation.timingFunction = CAMediaTimingFunction(name: .easeOut) animation.isAdditive = true self.layer.add(animation, forKey: "shake") } /** Screenshot of current view */ public var screenshot: UIImage { UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } public func addSubview(_ view: UIView, top: CGFloat?, left: CGFloat?, bottom: CGFloat?, right: CGFloat?) { self.addSubview(view) if let top = top { view.topAnchor.constraint(equalTo: self.topAnchor, constant: top).isActive = true } if let left = left { view.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: left).isActive = true } if let bottom = bottom { view.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: bottom * -1).isActive = true } if let right = right { view.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: right * -1).isActive = true } } }
f51cd5a1d24be48851e79cd8154819a2
43.434426
178
0.636414
false
false
false
false
renatogg/iOSTamagochi
refs/heads/master
Tamagochi/ViewController.swift
cc0-1.0
1
// // ViewController.swift // Tamagochi // // Created by Renato Gasoto on 5/9/16. // Copyright © 2016 Renato Gasoto. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var monsterImg: MonsterImg! @IBOutlet weak var heartImg: DragImg! @IBOutlet weak var foodImg: DragImg! @IBOutlet var lifes: Array<UIView>! var musicPlayer: AVAudioPlayer! var sfxBite: AVAudioPlayer! var sfxHeart: AVAudioPlayer! var sfxDeath: AVAudioPlayer! var sfxSkull: AVAudioPlayer! let DIM_ALPHA: CGFloat = 0.2 //Opacity of disabled items / Lost Lifes let OPAQUE: CGFloat = 1.0 var penalties = 0 var timer: NSTimer! var monsterHappy = true var currentItem: UInt32 = 0 override func viewDidLoad() { super.viewDidLoad() foodImg.dropTarget = monsterImg heartImg.dropTarget = monsterImg foodImg.alpha = DIM_ALPHA foodImg.userInteractionEnabled = false heartImg.alpha = DIM_ALPHA heartImg.userInteractionEnabled = false loadAudios() for life in lifes{ life.alpha = DIM_ALPHA } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.itemDroppedOnCharacter(_:)), name: "onTargetDropped", object: nil) startTimer() } func loadAudios(){ do{ try musicPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cave-music", ofType: "mp3")!)) try sfxSkull = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("skull", ofType: "wav")!)) try sfxBite = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bite", ofType: "wav")!)) try sfxHeart = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("heart", ofType: "wav")!)) try sfxDeath = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("death", ofType: "wav")!)) musicPlayer.prepareToPlay() sfxSkull.prepareToPlay() sfxBite.prepareToPlay() sfxHeart.prepareToPlay() sfxDeath.prepareToPlay() musicPlayer.play() }catch let err as NSError{ print (err.debugDescription) } } func itemDroppedOnCharacter(notif: AnyObject){ monsterHappy = true foodImg.alpha = DIM_ALPHA foodImg.userInteractionEnabled = false heartImg.alpha = DIM_ALPHA heartImg.userInteractionEnabled = false startTimer() if currentItem == 0{ sfxHeart.play() }else{ sfxBite.play() } } func startTimer(){ if timer != nil{ timer.invalidate() } timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: #selector(ViewController.changeGameState), userInfo: nil, repeats: true) } func changeGameState(){ if !monsterHappy { penalties += 1 sfxSkull.play() for i in 0..<penalties{ lifes[i].alpha = OPAQUE } for i in penalties..<lifes.endIndex{ lifes[i].alpha = DIM_ALPHA } if penalties == lifes.endIndex{ gameOver() } } if penalties < lifes.endIndex { let rand = arc4random_uniform(2) if rand == 0{ foodImg.alpha = DIM_ALPHA foodImg.userInteractionEnabled = false heartImg.alpha = OPAQUE heartImg.userInteractionEnabled = true } else{ foodImg.alpha = OPAQUE foodImg.userInteractionEnabled = true heartImg.alpha = DIM_ALPHA heartImg.userInteractionEnabled = false } currentItem = rand monsterHappy = false } } func gameOver(){ timer.invalidate() foodImg.alpha = DIM_ALPHA foodImg.userInteractionEnabled = false heartImg.alpha = DIM_ALPHA heartImg.userInteractionEnabled = false monsterImg.playAnimation(true) sfxDeath.play() musicPlayer.stop() } }
619162340a2ffe1f40429b039c451cd2
31.119718
172
0.585836
false
false
false
false
steve228uk/PeachKit
refs/heads/master
ImageMessage.swift
mit
1
// // ImageMessage.swift // Peach // // Created by Stephen Radford on 17/01/2016. // Copyright © 2016 Cocoon Development Ltd. All rights reserved. // import Foundation import Alamofire import SwiftyJSON public class ImageMessage: Message { public required init() { } /// Source URL of any image public var src: String? /// Width of any image public var width: Int? /// Height of any image public var height: Int? /** Fetch the image related to the message - parameter callback: Callback with NSImage */ public func getImage(callback: (NSImage) -> Void) { if let url = src { Alamofire.request(.GET, url) .responseData { response in if response.result.isSuccess { if let img = NSImage(data: response.result.value!) { callback(img) } } } } } /** Fetch the image data related to the message - parameter callback: Callback with NSImage */ public func getImageData(callback: (NSData) -> Void) { if let url = src { Alamofire.request(.GET, url) .responseData { response in if response.result.isSuccess { callback(response.result.value!) } } } } // MARK: - Message Protocol public var type: MessageType = .Image public static func messageFromJson(json: JSON) -> Message { let msg = ImageMessage() if let stringWidth = json["width"].string { msg.width = Int(stringWidth) } else { msg.width = json["width"].int } if let stringHeight = json["height"].string { msg.height = Int(stringHeight) } else { msg.height = json["height"].int } msg.src = json["src"].string return msg } public var dictionary: [String:AnyObject] { get { return [ "type": type.stringValue.lowercaseString, "width": (width != nil) ? width! : 0, "height": (height != nil) ? height! : 0, "src": (src != nil) ? src! : "" ] } } }
ad849f35d7a3a85243641dbb4a47f1fb
24.860215
76
0.493344
false
false
false
false
grpc/grpc-swift
refs/heads/main
Sources/GRPCSampleData/GRPCSwiftCertificate.swift
apache-2.0
1
/* * Copyright 2022, 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. */ //----------------------------------------------------------------------------- // THIS FILE WAS GENERATED WITH make-sample-certs.py // // DO NOT UPDATE MANUALLY //----------------------------------------------------------------------------- #if canImport(NIOSSL) import struct Foundation.Date import NIOSSL /// Wraps `NIOSSLCertificate` to provide the certificate common name and expiry date. public struct SampleCertificate { public var certificate: NIOSSLCertificate public var commonName: String public var notAfter: Date public static let ca = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(caCert.utf8), format: .pem), commonName: "some-ca", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let otherCA = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(otherCACert.utf8), format: .pem), commonName: "some-other-ca", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let server = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(serverCert.utf8), format: .pem), commonName: "localhost", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let exampleServer = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(exampleServerCert.utf8), format: .pem), commonName: "example.com", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let serverSignedByOtherCA = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(serverSignedByOtherCACert.utf8), format: .pem), commonName: "localhost", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let client = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(clientCert.utf8), format: .pem), commonName: "localhost", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let clientSignedByOtherCA = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(clientSignedByOtherCACert.utf8), format: .pem), commonName: "localhost", notAfter: Date(timeIntervalSince1970: 1699960773) ) public static let exampleServerWithExplicitCurve = SampleCertificate( certificate: try! NIOSSLCertificate(bytes: .init(serverExplicitCurveCert.utf8), format: .pem), commonName: "localhost", notAfter: Date(timeIntervalSince1970: 1699960773) ) } extension SampleCertificate { /// Returns whether the certificate has expired. public var isExpired: Bool { return self.notAfter < Date() } } /// Provides convenience methods to make `NIOSSLPrivateKey`s for corresponding `GRPCSwiftCertificate`s. public struct SamplePrivateKey { private init() {} public static let server = try! NIOSSLPrivateKey(bytes: .init(serverKey.utf8), format: .pem) public static let exampleServer = try! NIOSSLPrivateKey( bytes: .init(exampleServerKey.utf8), format: .pem ) public static let client = try! NIOSSLPrivateKey(bytes: .init(clientKey.utf8), format: .pem) public static let exampleServerWithExplicitCurve = try! NIOSSLPrivateKey( bytes: .init(serverExplicitCurveKey.utf8), format: .pem ) } // MARK: - Certificates and private keys private let caCert = """ -----BEGIN CERTIFICATE----- MIICoDCCAYgCCQCf2sGvEIOvlDANBgkqhkiG9w0BAQsFADASMRAwDgYDVQQDDAdz b21lLWNhMB4XDTIyMTExNDExMTkzM1oXDTIzMTExNDExMTkzM1owEjEQMA4GA1UE AwwHc29tZS1jYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOjCRRWS ezh/izFLT4g8lAjVUGbjckCnJRPfwgWDAC1adTDi4QhzONVlmYUzUkx6VPCcVVou vc/WM8hHC6cRDdf/ubGRZondGw6bzaO2yqc8K6BNSvqFnkuQHRpPoSc/RKHe+qTT glhygm3GlAUaNl0hJpXWlLqOoIb0mn8emF7afbyyWariPPQyzY2rywPLPXipitmW Jw7GxVC+Q2yx5GQxPvutCdtkAsrS1AsYxpvpW+kHmtj0Dj40N7yhTz1cw2QtCD2i CQuk9oRwtIiJi54USy/r6oq5NOlwqHyq+DGDt5XZx1RKvGJTn3ujHPEJVipoTkdX /K+RpqQxJNGhyO8CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAjKgbr1hwRMUwEYLe AAf0ODw0iRfch9QG6qYTOFjuC3KyDKdzf52OGm49Ep4gVmgMPLcA3YGtUXd8dJSf WYZ0pSJYeLVJiEkkV/0gwpc+vK2OxZe1XBPbW3JN+wmRBxi3MiL7bbSvDlYIj7Dv 8c1vs8SxE4VuSkFRrcrVV0V95xs01X1/M9aa8z9Lf59ecKytaLvKysorDrCN8nC3 zlMDehPCLH9y4UlBqp8ClUpKk/5/P8HXr40ZGq+5TFrR80YABPSVX7krRMcxIhfu IFIT2yhjkxMQWj8SCDUZxamBElAXY9KHSlEv3y+teRQABBVNxslHXqLKfKTF3q4S tUVJuA== -----END CERTIFICATE----- """ private let otherCACert = """ -----BEGIN CERTIFICATE----- MIICrDCCAZQCCQDQxWAzi9Y9LTANBgkqhkiG9w0BAQsFADAYMRYwFAYDVQQDDA1z b21lLW90aGVyLWNhMB4XDTIyMTExNDExMTkzM1oXDTIzMTExNDExMTkzM1owGDEW MBQGA1UEAwwNc29tZS1vdGhlci1jYTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC AQoCggEBANOr3vaYLkfnqk0lREo0VJD/rnUGQ6BiVtKiou0uksb9gX4oHdKlnqyi dvFuwaJHIzjBhdWD2EqgWwuBTB3y/UybD/ZvkojnLD+QNMnbgG5aCnO03gVlVBOf JggEtAEM31C7Fi6X7Gr/QwRI721+kqNSB48Rj3BT93cDW73aSeL6IZ8jlvefWYR7 1UI3bP+4WG58PSJOhUs2edaOn0G5wRZ5LyK6A77noll90cP+CVNlqLj8HRapqhf1 XZhGwwaEYxNV1oDroxq9mcM+6E8LdWCsdE3N4Dx6pdL0lOjwvhevZ2ct/fb31NYE fMstojwKf9Of5/J4kZaC1mp44IwPS00CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEA iUuX1YYdVwqamg13eji1I9/8eMP5demBnXjM7DYP3JqDhClTYNnN8aB+o1YW51ce 3V1FtN/f3g3YMgYB4YSOb241G9uXGCz5CwcYeBCJbUT/PdNZOrTW1EzA+gAy8GxS yMbK+ZrXy+7mJr79sumIO2WGk//eznvgrmlKq+eZtVf/TDTYs5TdbqI4sqoN+qPQ WyuBXEkU2D259VvZ+GLljVr7JCysciALKDk3QAb6cfjhFh3aOqb40m5i4Jg6g2G6 iFS1kE3KjaWhYYn66BRVOYzfT25RkFBxxJh2Pg6DQOyVUWsWJ+VrstpQlcGMElmq /LaIwNYfuUNcKb90L+M6vg== -----END CERTIFICATE----- """ private let serverCert = """ -----BEGIN CERTIFICATE----- MIICmjCCAYICAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe Fw0yMjExMTQxMTE5MzNaFw0yMzExMTQxMTE5MzNaMBQxEjAQBgNVBAMMCWxvY2Fs aG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANEQLRL2oOHPHN7K ozmP8Ks8CcndChJrunNTJAWCiMA/HFEVVfylnQpPyc/t+W2yD+d+PsJknu2hI1O5 o53SBsEDm1taHaCJt9ur5NKpEphzOI7VuwkgcoGqmY0Hz7GmBmbG06Z6ne8EZfg5 a/rjxhW3GyOmIT3s9xWiU3MW7VX0PDlVmkZzVYtcSp9+AXQMDpvLK48INu1mUC6u 1nbEzj6KuFwpU5+V1cRLHer+I9HVA7qBcgsIDDEdUDG0/l0MivAyDbNHGHDZcsfj jwTMsGRcd+IONItHyYb72+JBEKv3/qFAe4XIeR6iJQP4OxZ4CoxeUFgkVQwqBNd+ 1JYDuvECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEASoyiLe/ak0nH5Bl7RvwAsO+Y J2kA/oIUCpFEmsqDxK9Nt4eGIvknGzWsfTsVM4jXQo1MYCE7XrjpG9H6fubeQvxG b+eU3VaHztflxLouzBIM6LnzoXnt2/rjQWIMbWZri2Gwl4incvVDLOv3jm5VD1Uw OePLd+DvD/NzQ4nWdqCqhZAjopEPUpOT7fP8OkJVjGddvAn/0KyXkg3tutmUMB9m 8KctofAp1fKmd056Lgj+j6DIFDxxWEiihTO1ae8FlS4X/teeGSEVGv5M4baWRrcD 29V9XNIbMiwCNa7DJlPpxkjHdT4KifwPDHJ92RfK54SU1k0i8LD9KByuV4av9w== -----END CERTIFICATE----- """ private let serverSignedByOtherCACert = """ -----BEGIN CERTIFICATE----- MIICoDCCAYgCAQEwDQYJKoZIhvcNAQELBQAwGDEWMBQGA1UEAwwNc29tZS1vdGhl ci1jYTAeFw0yMjExMTQxMTE5MzNaFw0yMzExMTQxMTE5MzNaMBQxEjAQBgNVBAMM CWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANEQLRL2 oOHPHN7KozmP8Ks8CcndChJrunNTJAWCiMA/HFEVVfylnQpPyc/t+W2yD+d+PsJk nu2hI1O5o53SBsEDm1taHaCJt9ur5NKpEphzOI7VuwkgcoGqmY0Hz7GmBmbG06Z6 ne8EZfg5a/rjxhW3GyOmIT3s9xWiU3MW7VX0PDlVmkZzVYtcSp9+AXQMDpvLK48I Nu1mUC6u1nbEzj6KuFwpU5+V1cRLHer+I9HVA7qBcgsIDDEdUDG0/l0MivAyDbNH GHDZcsfjjwTMsGRcd+IONItHyYb72+JBEKv3/qFAe4XIeR6iJQP4OxZ4CoxeUFgk VQwqBNd+1JYDuvECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAZN5RQsfPP09YIfYo UGu9m5+lpzYhE0S2+szysTg2IpWug0ZK4xhnqQYd9cGRks+U6hiLPdiyHCwOykf6 OplIp5fMxPWZipREb9nA33Ra1G9vpB/tZxQJxDTvUeCH88SQOszdZk79+zWyVkaF +TCa3jDXb/vT20+wKxpPUjse5w2j0VOh21KaP82EMyOY/ZvhbMC60QyHnFDvJAEV sle77vbdLjYELpYUpf9N+TxFDZ2B4dY/edprLZGt3LcUUFv/WB8FxZdWcjdZML2F TMqicbP7H27+V1HF1rFUJWKzDNh4Wg6bY6lQNTZeHUyLwf/WlUraXTKYpqSH8FQ1 703RGQ== -----END CERTIFICATE----- """ private let serverKey = """ -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA0RAtEvag4c8c3sqjOY/wqzwJyd0KEmu6c1MkBYKIwD8cURVV /KWdCk/Jz+35bbIP534+wmSe7aEjU7mjndIGwQObW1odoIm326vk0qkSmHM4jtW7 CSBygaqZjQfPsaYGZsbTpnqd7wRl+Dlr+uPGFbcbI6YhPez3FaJTcxbtVfQ8OVWa RnNVi1xKn34BdAwOm8srjwg27WZQLq7WdsTOPoq4XClTn5XVxEsd6v4j0dUDuoFy CwgMMR1QMbT+XQyK8DINs0cYcNlyx+OPBMywZFx34g40i0fJhvvb4kEQq/f+oUB7 hch5HqIlA/g7FngKjF5QWCRVDCoE137UlgO68QIDAQABAoIBAEumodjh2/e6PYU1 KHl0567e69/bF4Dw8Kg4pqlDwf5nF/UTVmk0+K25j5qpT3/tVin7mfQ3+vacP69V VqqOTJldl8Mnyd7E1v4rpoLAYZU+5HFzT9oOnsDjHetVr0dmf5yDSCVO64WJPuji xnskHxLOjoiI3jCNZh+y/KWB32IhdofSwBccw852JM2qC5l8vgE+sfjOeWXDiPRI YLlVRlxZFv7N2kn+EDnPEQ8m2OGYKvNzU0d9nz05NdkRXzMh9zegTTL4EQhTaMf0 2AXy2ekKFVvWouV4y8QW1shz5Tun2y4ZQJnwiCyldED9sMxaziQxfdJ6N7f4+K5c Sh4+Ct0CgYEA7bGvY02jQfHcDPOjZ/xkXb98lr1uLGTSvwK3zw+rI0+nrUJwH6fB nSaXyWk059OqHTKPpa/d8DxFL2LP6vbvfTWCv9mnn61WWWDmP0Eo/k93XgWkmclb vQGfXV2wtCTnhz+iUSSJA8f8jZhCtOD6xa8pLsaYrGD6oR5wzfs0nysCgYEA4SoC /JWDMkw4mndI2vQ8GqDzBFtJCMr/dva7YGCGtbimDzxuOI68vW/y4X8Izg2i1hVz iKRYCI9KzRdQrQ7masZF2d4DeaqPeA72JN4hoUOw0TZjP8yD4ECifUt786ZNvV1n NlEhNb55zD73Cl6v0OJZkEfp1MC5ZQwLw7bMYFMCgYEAvNu5Z0WAuhzZotDSvQSl GnfTHlJU/6D8chhOw47Hg77+k4N+Yyh/hcXsRHP7PVfIinpp+FPMG91He2cfnKmn j+y8foMJ1K19NnbvesLjN20cgvAo4KhE4+AuJ5kRlZDdBXFiHubQltiHqlmYZu97 USbjqe7Rz+UePnZZWtCF9xECgYEAjGODZTVbjdrUWAsT0+EAMKI1o3u/N8pKKkSA ZAELPPaaI1nMZ1sn9v179HkeZks+QjkxxfqiIQQm4WUuGhj2NZDWMJcql4tu1K6P bkFJuqDX+Dnu+/JqL0Jdjb2o1SvVwMIh/k3rZPUUP/LqWP7cpGLc8QbFlq9raMNv +mFZYJ0CgYEA5IQzp7SymcKgQqwcq5no2YOr76AykSCjOnLYYrotFqbxGJ19Cnol Z74Habxjv89Kc7bfIwbz/AolkhAS2y0CYwSJL4wZIUb8W2mroSmaHhsk3A4DMPBB wgSsdiBpixQqNDUAvnHc3FIyAGdpA73TJQrGY2F6QyQ9re3a/R8Dc3k= -----END RSA PRIVATE KEY----- """ private let exampleServerCert = """ -----BEGIN CERTIFICATE----- MIICnDCCAYQCAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe Fw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBYxFDASBgNVBAMMC2V4YW1w bGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5UPdc3MERjIj rKNMcsCJEPJtzFZG7T99rDaENxl5hF5TdlCuMfKQMyf4rmUk2KdQXduWDmP/9keO Btc3Hw9xm7mHn7UPbK0kHjlncqTCnjZzVQ2j0stg4Q0WjGeS0aB8k1AHPiBaOnvJ LYcBJrA8mZK+inEE0gWEJsODTM+bKb3+5I69qVoHAkU2tXTDV9g1YKfP4H3rufEg 622AR1yAo8UxaGjY3amWps6XF/9R2iaSDAPLH1dCBw/YWrIH51n75S+n/H3Rz0+H /aT9Eze0M2F2Nj1cU8fVcbDNR0smssgXVmE2mvQ+OvbO0H7VTS1HK2q2aPOPkRWh yhFnOvPnbQIDAQABMA0GCSqGSIb3DQEBCwUAA4IBAQAWk5KHkWVsbXqz6/MnwxD5 fn7JrBR77Vz3mxQO9NDKN/vczNMJf5cli6thrB5VPprl5LFXWwQ+LUQhP+XprigQ 8owU1gMNqDzxVHn7By2lnAehLcWYxDoGc8xgTuf2aEjFAyW9xB67YP/kDx9uNFwY z+zWc6eMVr6dtKcsHcrIEoxLPBO9kuC/wlNY+73q04mmy9XQny15iQLy4sQT0wk4 xV4p86rqDZcGepdV2/bLk2coF9cUOPOGwUBqEIc7n5GekC2WTXSnjOEK5c+2Wkbw Yt4jXnvsaQ8bwpchHfM1K3mLn+2rCEZ3F4E5Ug7DKebrwU4z/Nccf1DwM4pdI0EI -----END CERTIFICATE----- """ private let exampleServerKey = """ -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA5UPdc3MERjIjrKNMcsCJEPJtzFZG7T99rDaENxl5hF5TdlCu MfKQMyf4rmUk2KdQXduWDmP/9keOBtc3Hw9xm7mHn7UPbK0kHjlncqTCnjZzVQ2j 0stg4Q0WjGeS0aB8k1AHPiBaOnvJLYcBJrA8mZK+inEE0gWEJsODTM+bKb3+5I69 qVoHAkU2tXTDV9g1YKfP4H3rufEg622AR1yAo8UxaGjY3amWps6XF/9R2iaSDAPL H1dCBw/YWrIH51n75S+n/H3Rz0+H/aT9Eze0M2F2Nj1cU8fVcbDNR0smssgXVmE2 mvQ+OvbO0H7VTS1HK2q2aPOPkRWhyhFnOvPnbQIDAQABAoIBAQDk0+vAQ1hMx9ab hRHUpx8nbxDwFl0Mh4Zj0LX+WMrUt2EOglCbQcNzi73GMuWn6LdqNrV6/4yGv7ye T0iRE9UM3Qzk9s7CZb3a/OinoJMvXqGWjtqolp3HgkyzLt13pXsxfXr9I0Vrggm2 Cz2248hYcAMGIu/wv9i66AGxNLVl3nzlo3K3J+6LwGYSrM5MMsN8p/RIc7RD30cg Qer6uiGdYemD2hbOuqcqImzhMLvoYn683uLOoDhiFLmAPIU+VxtHs2pMpp4ebjrl PpS8TtHnV85v/fhX6RE/jo5razdSU4LxW/p/fF5Zte+QR6FJgFFWaQvZd6/Vtuh6 K0Hadt1xAoGBAP1fuBjUElQgWBtoXb422X2/LurnyHfNSqSDM3z8OiCSN08r5GmM ylWqh7k1sQWBzQ4OAsZcbwvrpvxMGYEd1K99LtUcM235WcKTomz7QRRUKG74tyFk VdCgcMF+q2DdBE+hlF08bTNk1dM6uPlinNiMklydhLFjjhLlfDkiteGTAoGBAOek LXqKMK4H5I1VQBgNKAv25tVItDabX5MPqhJVxmsvbNNTh/pfaNW7ietZNkec8FXs UtS2Hv2hwNMVSb8l9bk96b2x9wiww2exI4oWKjKkJrSVsIcWc4BgeZ2xUtnV6QR5 XSNm7D4E11KhuHPbB01cAZeC0Cf/4rTZ5ERhULL/AoGAS/UpHJBfGkdEAptsFv0c gH0TFKr9xySNLvqCMgLvbhpHaH2xEQ97DOl9nMGC2zLJhWAf5tWJGNrBibtKnhGS VDXEF3FH3b018oYN2HwOS4jbQkFfrSwGKfAfPXK67+PySekXsEfQOOsOyy88is7M VIL30boLMJ621eVkM0C7o+8CgYBLiiK6n24YksJZxL9OGJxCqpXEYB1E4Y5davJP YGGAesrGb6scXxjU+n+TnFgzKl7F5ndsnqeklqdHLt4J09s6OZKMJgklcF+I5R9t 3KSONzHYGiijJRMtfkiqwDUAjN2cc+eHr/zCjNmbPNnmDjtnYuWx/xrasHvB9nyW QBYNCQKBgQCDqdvchLcreSdbXKr6swvBz8XxzCaEParbm7iOvdLlv93svvCaHgI8 6E+FlXk68Qc2Dj8de/xEnl/OonNQRgIQh7czBJmYP8+TCPECm8fvv2TsddNvjTmF TTx8wf9gixHffRtXZ4ILrP1sX7c4if3bfaMxKz+0ZyfzWZry8qZtVQ== -----END RSA PRIVATE KEY----- """ private let clientCert = """ -----BEGIN CERTIFICATE----- MIICmjCCAYICAQEwDQYJKoZIhvcNAQELBQAwEjEQMA4GA1UEAwwHc29tZS1jYTAe Fw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBQxEjAQBgNVBAMMCWxvY2Fs aG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOMSDHjt5P3MOmtw atYP0PnCfr2sxsMd1uxKeb+x5mpYuckcsnm1UR0LcBCizwBZ7yYAZQkFyK7vdJge Hv9P3Rki6+6Jj/ngLdpOirtUcOfnfzbdlA2k6qJtY6G+ZKyczDICWaZHzNRycDkL Yv4kzUT8PynIRIK/LPyXQa+tGty9+G2exVPdpzKpCgE8fKd8FeCOLW06Z0RsP0FS ySPSJxdDq0BRbfurhplhawh7uJ+7IoVfdWV2wwDvLztCEXHn2iiNpyzIixYapnVB PX1MXelsPRJaa9EKwOiqJB5ZcV9JWk9wa4W7mJrRfFTRh/9HRsoXIAaJPIqjTmqI ffat/1cCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAWpPkMzjKLAnxbfyasR6cPk3t ZanuBQ9RqVJw2gPem+SmSpvyPZ3CJTi0ZeUbPRSJ2W8YHyogaA5XShZSm8JJQKye TNYqUewVbU18OwVco0l7Wc8R1iiZgYEUcvMF2f/EWEMoCTmS3JlpbLl7LmdTy7iQ gIrR+iQ649nLw1T4Q5kp7zxjI6WJ3eZVNUjlTrUzKapSY4Tm2/+GafD+WNVRRACh Y9VNkaQ6qYy4SaLw6+bX2YdbDhIi275vAONHIZcAsMt6/aLJzKgfTxRqqmEvmJdQ KSVRRaSKZ/qe9UBdl4oFn1wupFAoNDQWkXT/Q3kVhxVXZ8ZE+ylZnuWcj3CHvQ== -----END CERTIFICATE----- """ private let clientSignedByOtherCACert = """ -----BEGIN CERTIFICATE----- MIICoDCCAYgCAQEwDQYJKoZIhvcNAQELBQAwGDEWMBQGA1UEAwwNc29tZS1vdGhl ci1jYTAeFw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBQxEjAQBgNVBAMM CWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOMSDHjt 5P3MOmtwatYP0PnCfr2sxsMd1uxKeb+x5mpYuckcsnm1UR0LcBCizwBZ7yYAZQkF yK7vdJgeHv9P3Rki6+6Jj/ngLdpOirtUcOfnfzbdlA2k6qJtY6G+ZKyczDICWaZH zNRycDkLYv4kzUT8PynIRIK/LPyXQa+tGty9+G2exVPdpzKpCgE8fKd8FeCOLW06 Z0RsP0FSySPSJxdDq0BRbfurhplhawh7uJ+7IoVfdWV2wwDvLztCEXHn2iiNpyzI ixYapnVBPX1MXelsPRJaa9EKwOiqJB5ZcV9JWk9wa4W7mJrRfFTRh/9HRsoXIAaJ PIqjTmqIffat/1cCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAIqGPpw/m3oIb+Ok7 eZCEph/IcEwvkJXAFYeYjQHDsK1EW/HNoyjKKU3CaLJuWtvNbW+8GpmiVdAcO0XS RN+xwDOLmB+9Ob70tZRsR/4/695WkkCm/70Y89YqTq3ev86vZmPWBGZsdXB/rvfs sJbEkNeDRAquEbVQ3K8qmG7w8oC+VdzdQfQHY6hdkzsb0Q99aPASwGjxPVDz12Tb v9g9f9yVwI+vxxabHr4nvKJ/GfuHRzG2eSW2TNBY/Kxp10+lCdMfbPq2p0LsV4eZ eHPCFqiBe6CK80Pdpy7CNCPBBvGkGb7nfxBi4/tNVDgMlOQy6pA3PLjib8NLMCIA 5iUEvw== -----END CERTIFICATE----- """ private let clientKey = """ -----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEA4xIMeO3k/cw6a3Bq1g/Q+cJ+vazGwx3W7Ep5v7Hmali5yRyy ebVRHQtwEKLPAFnvJgBlCQXIru90mB4e/0/dGSLr7omP+eAt2k6Ku1Rw5+d/Nt2U DaTqom1job5krJzMMgJZpkfM1HJwOQti/iTNRPw/KchEgr8s/JdBr60a3L34bZ7F U92nMqkKATx8p3wV4I4tbTpnRGw/QVLJI9InF0OrQFFt+6uGmWFrCHu4n7sihV91 ZXbDAO8vO0IRcefaKI2nLMiLFhqmdUE9fUxd6Ww9Elpr0QrA6KokHllxX0laT3Br hbuYmtF8VNGH/0dGyhcgBok8iqNOaoh99q3/VwIDAQABAoIBAQC5gA4mYJoY6FW1 XcI5m/QphcWKaHJ8BY2FvZXWj5vftxoXfNUk7oYURzrGrGqVK+Nd1Sa1Bz+aAc7r UngaNQE3vrqlRUYUaRqsZEubm/Ec0pavmLaRqu9vwBOLmAGgrft2w0q/t5pS2CZr w6ycWC5FNBjZplypv0oeE+c6gB0YxKJ2mjKEYHWOop+uBPql2G6TfCeu4mMekZPH cHbMuMlBPN23HT7BmGCvk1YSaGbMt0iCTM0zThfe53AtLSVKn33szHm/XjLYJYGM 7N+SttwM+O88diFShWHUHmWsy5Lv0Mrkw3NRz37yQ8Uh1fJ0TMeLZEIzKSLrI8lv XrBVE89ZAoGBAP8bBSytb6Aof6p1noIx8nu31d5/5mvRSUxoF1Lu/B/EeaNTGXxD HvJEi4Lh/txm6/3IeC5gfJ0jExxoWyTD3wLqVvmf+FEMntXqnATC832uw3vkxZpd E/MldDHE4UkWGBUvii7JN1fisyyZKLUu517crebJthpwk5Sf/1FgK1SbAoGBAOPd 3VTQ7uaD2zPn4QM9KZsFJ+7cS7l1qtupplj9e12T7r53tQLoFjcery2Ja7ZrF3aq y07D2ww8y8v1ShxqTgSOdeqPCX1a4OS7Z93zsy58Jv3ZcXbfbSGiLbpoueQJbUZ0 vKlDIf4uHn78fz8WIbe87UwKneKnaRrO64DtHQX1AoGBAIH11vYCySozV46UaxLy tRB3//lg+RcWQJwvLyqt2z2nzzv4OrSGUT6k0tnzne3UdQcN2MPvnaxD0RmYxE3/ hx4qGfMDnvJTVput8JuwYXE21hnI2y4fmuk0vHQaU5bzLYOle2UIVyxrrlHbGNTs tywpimJXgnEHxvdhZyWis5BfAoGBAN45P2M6J+KzcRGb8DuiaHMAgkNWoJsMAEcd mldrTeajINCsGeHtycyTpi/4tw0+P7HBO2ljZLr4h6AvZcl0ewXCkYjhWlXgTTeE 9PTmeDa7aaNjbl6J4vpMGeCTxcZ40xNFQcCo8fvbqm4ZfVdfFB8Gpz3jlLq4na5B YjdoB0gJAoGAZCK3JbIN56KnmyENuZ6szWTZwkCMZq3kPVKBK8LAITVLVxg7Emjs GyTU+JhMx9Hk2tU/tftM/dTZ2TRRMwmPbZNadtkQdDgsXDhfkrW9JmVewx4ECCcI gBfWFOoABVTmVM9oNc74FeWu3nDjqGix5ZJ8+Zjjr8wUEcrU2TPZKn4= -----END RSA PRIVATE KEY----- """ private let serverExplicitCurveCert = """ -----BEGIN CERTIFICATE----- MIICEDCCAbYCCQDCeNe2vM7d6DAKBggqhkjOPQQDAjAWMRQwEgYDVQQDDAtleGFt cGxlLmNvbTAeFw0yMjExMTQxMTE5MzRaFw0yMzExMTQxMTE5MzRaMBYxFDASBgNV BAMMC2V4YW1wbGUuY29tMIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0B AQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAAB AAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxT sPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vObl Y6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBo N79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABDmd 3Pzv6HbsUTmNd7RljKbkYP+36ljl6qVZKZ+8m3Exq4DvtIzLKho/4NluAhWCsRev 2pWTfEiqiYS/U40TnfQwCgYIKoZIzj0EAwIDSAAwRQIhAI+BpDBjiqZD7r5vhPrG TT9Kq9s4ekIc1/a4AoTioT8CAiAluJHscXt+vBcqEI9sH0wudusCdPJyLbvNtMZd wdduCw== -----END CERTIFICATE----- """ private let serverExplicitCurveKey = """ -----BEGIN EC PRIVATE KEY----- MIIBaAIBAQQgBLTFlKchn4c+dQphsqJ2hWVpLPeRQ0opnSwvRsH+63iggfowgfcC AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA//////////////// MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8 YyVRAgEBoUQDQgAEOZ3c/O/oduxROY13tGWMpuRg/7fqWOXqpVkpn7ybcTGrgO+0 jMsqGj/g2W4CFYKxF6/alZN8SKqJhL9TjROd9A== -----END EC PRIVATE KEY----- """ #endif // canImport(NIOSSL)
eb7b3a7697f9a9b5a55f06b785c012dd
47.137363
103
0.872617
false
false
false
false
chenchangqing/travelMapMvvm
refs/heads/master
travelMapMvvm/travelMapMvvm/ViewModels/FilterViewModel.swift
apache-2.0
1
// // FilterViewModjel.swift // travelMapMvvm // // Created by green on 15/8/31. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import ReactiveCocoa import ReactiveViewModel class FilterViewModel: RVMViewModel { private var selectionViewDataSourceProtocol:SelectionViewDataSourceProtocol = SelectionViewDataSource.shareInstance() // 被观察数据源 var dataSource = DataSource(dataSource: OrderedDictionary<CJCollectionViewHeaderModel, [CJCollectionViewCellModel]>()) var filterSelectionDicSearch : RACCommand! override init() { super.init() // 初始化命令 setupFilterSelectionDicSearch() } private func setupFilterSelectionDicSearch() { filterSelectionDicSearch = RACCommand(signalBlock: { (any:AnyObject!) -> RACSignal! in let signal = self.selectionViewDataSourceProtocol.queryFilterDictionary() let scheduler = RACScheduler(priority: RACSchedulerPriorityBackground) return signal.subscribeOn(scheduler) }) filterSelectionDicSearch.executionSignals.switchToLatest().deliverOn(RACScheduler.mainThreadScheduler()).subscribeNextAs { (dataSource:DataSource) -> () in self.setValue(dataSource, forKey: "dataSource") } } }
a03c1f3bba0931a93ff9703271d06018
30.534884
163
0.676991
false
false
false
false
varshylmobile/VMXMLParser
refs/heads/master
XMLParserTest/XMLParserTest/ViewController.swift
mit
1
// // ViewController.swift // XMLParserTest // // Created by Jimmy Jose on 21/08/14. // Copyright (c) 2014 Varshyl Mobile Pvt. Ltd. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableview:UITableView! = UITableView() var activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0,0, 50, 50)) as UIActivityIndicatorView var tagsArray = NSArray() var selectedIndex = 0 override func viewDidLoad() { super.viewDidLoad() self.tableview.delegate = self self.tableview.dataSource = self activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge activityIndicator.color = UIColor.blueColor() view.addSubview(activityIndicator) activityIndicator.startAnimating() let url:String="http://images.apple.com/main/rss/hotnews/hotnews.rss" /* VMXMLParser.initParserWithURLString(url, completionHandler: { (tags, error) -> Void in if(error != nil){ println(error) }else{ dispatch_async(dispatch_get_main_queue()){ self.tagsArray = tags! self.tableview.reloadData() self.activityIndicator.stopAnimating() } } })*/ let tagName = "item" VMXMLParser().parseXMLFromURLString(url, takeChildOfTag: tagName) { (tags, error) -> Void in if(error != nil){ print(error!) }else{ dispatch_async(dispatch_get_main_queue()) { self.tagsArray = tags! self.tableview.reloadData() self.activityIndicator.stopAnimating() } } } } func numberOfSectionsInTableView(tableView: UITableView) -> Int{ return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tagsArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell") let idxForValue:Int = indexPath.row let dictTable:NSDictionary = tagsArray[idxForValue] as! NSDictionary let title = dictTable["title"] as? String let subtitle = dictTable["pubDate"] as? String cell.textLabel!.text = title ?? "" cell.detailTextLabel!.text = subtitle ?? "" cell.backgroundColor = UIColor.clearColor() cell.textLabel!.font = UIFont(name: "Helvetica Neue Light", size: 15.0) cell.selectionStyle = UITableViewCellSelectionStyle.None cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ tableView.deselectRowAtIndexPath(indexPath, animated: true) selectedIndex = indexPath.row self.performSegueWithIdentifier("Detail", sender: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let detailView = segue.destinationViewController as! DetailView detailView.title = "Detail" let dictTable:NSDictionary = tagsArray[selectedIndex] as! NSDictionary let description = dictTable["description"] as! NSString? let link = dictTable["link"] as! NSString? detailView.text = description! detailView.urlString = link! } }
3279850fe6e8e41f98bc4e7fce03232d
29.294118
114
0.593105
false
false
false
false
algolia/algoliasearch-client-swift
refs/heads/master
Sources/AlgoliaSearchClient/Index/Index+Index.swift
mit
1
// // Index+Index.swift // // // Created by Vladislav Fitc on 01/04/2020. // import Foundation public extension Index { // MARK: - Delete index /** Delete the index and all its settings, including links to its replicas. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Launched asynchronous operation */ @discardableResult func delete(requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexDeletion>) -> Operation & TransportTask { let command = Command.Index.DeleteIndex(indexName: name, requestOptions: requestOptions) return execute(command, completion: completion) } /** Delete the index and all its settings, including links to its replicas. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: DeletionIndex object */ @discardableResult func delete(requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexDeletion> { let command = Command.Index.DeleteIndex(indexName: name, requestOptions: requestOptions) return try execute(command) } // MARK: - Exists /** Return whether an index exists or not - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func exists(completion: @escaping ResultCallback<Bool>) -> Operation & TransportTask { let command = Command.Settings.GetSettings(indexName: name, requestOptions: nil) return execute(command) { (result: Result<Settings, Swift.Error>) in switch result { case .success: completion(.success(true)) case .failure(let error) where (error as? HTTPError)?.statusCode == .notFound: completion(.success(false)) case .failure(let error): completion(.failure(error)) } } } /** Return whether an index exists or not - Returns: Bool */ @discardableResult func exists() throws -> Bool { let command = Command.Settings.GetSettings(indexName: name, requestOptions: nil) let result = Result { try execute(command) as Settings } switch result { case .success: return true case .failure(let error): switch error { case TransportError.httpError(let httpError) where httpError.statusCode == .notFound: return false default: throw error } } } // MARK: - Copy index /** Make a copy of an index, including its objects, settings, synonyms, and query rules. - Note: This method enables you to copy the entire index (objects, settings, synonyms, and rules) OR one or more of the following index elements: - setting - synonyms - and rules (query rules) - Parameter scope: Scope set. If empty (.all alias), then all objects and all scopes are copied. - Parameter destination: IndexName of the destination Index. - Parameter requestOptions: Configure request locally with RequestOptions - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func copy(_ scope: Scope = .all, to destination: IndexName, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Index.Operation(indexName: name, operation: .init(action: .copy, destination: destination, scopes: scope.components), requestOptions: requestOptions) return execute(command, completion: completion) } /** Make a copy of an index, including its objects, settings, synonyms, and query rules. - Note: This method enables you to copy the entire index (objects, settings, synonyms, and rules) OR one or more of the following index elements: - setting - synonyms - and rules (query rules) - Parameter scope: Scope set. If empty (.all alias), then all objects and all scopes are copied. - Parameter destination: IndexName of the destination Index. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: RevisionIndex object */ @discardableResult func copy(_ scope: Scope = .all, to destination: IndexName, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Index.Operation(indexName: name, operation: .init(action: .copy, destination: destination, scopes: scope.components), requestOptions: requestOptions) return try execute(command) } // MARK: - Move index /** Rename an index. Normally used to reindex your data atomically, without any down time. The move index method is a safe and atomic way to rename an index. - Parameter destination: IndexName of the destination Index. - Parameter requestOptions: Configure request locally with RequestOptions - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func move(to destination: IndexName, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Index.Operation(indexName: name, operation: .init(action: .move, destination: destination, scopes: nil), requestOptions: requestOptions) return execute(command, completion: completion) } /** Rename an index. Normally used to reindex your data atomically, without any down time. The move index method is a safe and atomic way to rename an index. - Parameter destination: IndexName of the destination Index. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: RevisionIndex object */ @discardableResult func move(to destination: IndexName, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Index.Operation(indexName: name, operation: .init(action: .move, destination: destination, scopes: nil), requestOptions: requestOptions) return try execute(command) } }
ec825d060185e36098d8f2c1e917732c
39.314103
175
0.692479
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
refs/heads/master
精通Swift设计模式/Chapter 10/AbstractFactory/AbstractFactory/Drivetrains.swift
mit
1
protocol Drivetrain { var driveType:DriveOption { get }; } enum DriveOption : String { case FRONT = "Front"; case REAR = "Rear"; case ALL = "4WD"; } class FrontWheelDrive : Drivetrain { var driveType = DriveOption.FRONT; } class RearWheelDrive : Drivetrain { var driveType = DriveOption.REAR; } class AllWheelDrive : Drivetrain { var driveType = DriveOption.ALL; }
b3f3549ba5179bd28baf800cf55f5b25
19.473684
63
0.691517
false
false
false
false
Palleas/romain-pouclet.com
refs/heads/master
_snippets/batman-colours.swift
mit
1
enum ProjectColor: String { case darkPink = "dark-pink" case darkGreen = "dark-green" case darkBlue = "dark-blue" case darkRed = "dark-red" case darkTeal = "dark-teal" case darkBrown = "dark-brown" case darkOrange = "dark-orange" case darkPurple = "dark-purple" case darkWarmGray = "dark-warm-gray" case lightPink = "light-pink" case lightGreen = "light-green" case lightBlue = "light-blue" case lightRed = "light-red" case lightTeal = "light-teal" case lightYellow = "light-yellow" case lightOrange = "light-orange" case lightPurple = "light-purple" case lightWarmGray = "light-warm-gray" var raw: UIColor { /* ... */ } }
810d826d391d705797523cbed4eb5e63
30.863636
42
0.643367
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCEventTableViewCell.swift
lgpl-2.1
2
// // NCEventTableViewCell.swift // Neocom // // Created by Artem Shimanski on 05.05.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import CoreData class NCEventTableViewCell: NCTableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! } extension Prototype { enum NCEventTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCEventTableViewCell") } } class NCEventRow: TreeRow { let event: ESI.Calendar.Summary init(event: ESI.Calendar.Summary) { self.event = event super.init(prototype: Prototype.NCEventTableViewCell.default, route: Router.Calendar.Event(event: event)) } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCEventTableViewCell else {return} cell.titleLabel.text = event.title if let date = event.eventDate { cell.dateLabel.text = DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .short) } else { cell.dateLabel.text = nil } cell.stateLabel.text = (event.eventResponse ?? .notResponded).title } override var hash: Int { return event.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCEventRow)?.hashValue == hashValue } }
d6076289f0c3918cd05ddbd054feb338
23.4
107
0.723547
false
false
false
false
AaoIi/FMPhoneTextField
refs/heads/master
FMPhoneTextField/FMPhoneTextField/FMPhoneTextField.swift
mit
1
// // FMPhoneTextField.swift // // // Created by Saad Basha on 5/16/17. // Copyright © 2017 Saad Basha. All rights reserved. // import UIKit import CoreTelephony public protocol FMPhoneDelegate : class{ func didGetDefaultCountry(success:Bool,country: CountryElement?) func didSelectCountry(_ country:CountryElement) } public class FMPhoneTextField: UITextField { public enum CodeDisplay { case isoShortCode case internationlKey case bothIsoShortCodeAndInternationlKey case countryName } public enum SearchType { case cellular case locale case both } // Views private var contentViewholder : UIView! private var countryButton: UIButton! private var countryCodeLabel : UILabel! private var separator : UIView! // Default Styles private var borderColor = UIColor(red: 232/255, green: 232/255, blue: 232/255, alpha: 1.0) private var borderWidth : CGFloat = 1 private var cornerRadius : CGFloat = 7 private var backgroundTintColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0) private var codeTextColor = UIColor(red: 107/255, green: 174/255, blue: 242/255, alpha: 1.0) private var separatorBackgroundColor = UIColor(red: 226/255, green: 226/255, blue: 226/255, alpha: 1.0) private var separatorWidth : CGFloat = 1 private var defaultRegex = "(\\d{9,10})" private var selectedCountry : CountryElement? private weak var countryDelegate : FMPhoneDelegate? private var language : language! = .english private var defaultsSearchType : SearchType = .locale private var countryCodeDisplay : CodeDisplay = .bothIsoShortCodeAndInternationlKey private var isCountryCodeInListHidden : Bool = false //MARK: - Life cycle /// It will setup the view and layout, including getting the default country /// /// - Parameters: /// - delegate: managing the details of country and phone field. /// - language: selected language (arabic,english) public func initiate(delegate:FMPhoneDelegate,language:language){ // update local variables self.countryDelegate = delegate self.language = language // force layout to be left to right self.semanticContentAttribute = .forceLeftToRight // Add country left View self.setupCountryView() // Setup TextField Keyboard if #available(iOS 10, *){ self.keyboardType = .asciiCapableNumberPad }else { self.keyboardType = .phonePad } self.getCurrentCountryCode() } //MARK: - Update Views /// This is called automaticaly after country is being selected, its responsible for displaying the country/code details /// /// - Parameter country: object to be displayed public func updateCountryDisplay(country: CountryElement){ var text = "" switch countryCodeDisplay { case .bothIsoShortCodeAndInternationlKey: text = "\(country.isoShortCode ?? "") \(country.countryInternationlKey ?? "")" break; case .countryName: let name = language == .arabic ? country.nameAr : country.nameEn text = "\(name ?? "")" break; case .isoShortCode: text = "\(country.isoShortCode ?? "")" break; case .internationlKey: text = "\(country.countryInternationlKey ?? "")" break; } self.setupCountryView(text: text) self.selectedCountry = country } /// Get the phone number in full shape, /// IAC : International Access Code which is + or 00 /// - Parameter withPlus: will return 00 if passed false else will return + /// - Returns: the full phone number including country code. public func getPhoneNumberIncludingIAC(withPlus:Bool = false)->String{ guard let code = self.selectedCountry?.countryInternationlKey else { print("Error: Could not get country"); return "" } if withPlus { let text = self.text ?? "" if text.count > 0 { if text.first == "0" { let phone = String(text.dropFirst()) self.text = phone } } return code + (self.text ?? "") }else { let code = code.replacingOccurrences(of: "+", with: "00") let text = self.text ?? "" if text.count > 0 { if text.first == "0" { let phone = String(text.dropFirst()) self.text = phone } } return code + (self.text ?? "") } } //MARK: - Validation Method /// Will use the regex provided in each country object to validate the phone /// /// - Returns: valid phone or not public func validatePhone()->Bool{ if self.selectedCountry == nil { return self.evaluate(text: self.text ?? "", regex: defaultRegex) }else { let mobile = self.text ?? "" let regex = self.selectedCountry?.phoneRegex ?? defaultRegex return self.evaluate(text: mobile, regex: regex) } } private func evaluate(text:String, regex:String)->Bool{ let phoneRegex = regex let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex) return phoneTest.evaluate(with: text) } //MARK: - Helping Methods private func getCurrentCountryCode(){ var countryCode : String? = nil if self.defaultsSearchType == .locale { countryCode = FMPhoneTextField.getCountryCodeFromLocale() }else if self.defaultsSearchType == .cellular { countryCode = FMPhoneTextField.getCountryCodeFromCellularProvider() }else { countryCode = FMPhoneTextField.getCountryCodeFromCellularProvider() ?? FMPhoneTextField.getCountryCodeFromLocale() } guard let countries = CountriesDataSource.getCountries(language: language) else {return} for country in countries { if country.isoShortCode?.lowercased() == countryCode?.lowercased() { self.updateCountryDisplay(country: country) guard let delegate = self.countryDelegate else {print("Error:delegate is not set"); return } delegate.didGetDefaultCountry(success: true, country: country) return; } } guard let delegate = self.countryDelegate else { return } delegate.didGetDefaultCountry(success: false, country: nil) } private func getTopMostViewController()->UIViewController?{ guard let keyWindow = UIApplication.shared.keyWindow else { return nil} guard let visableVC = keyWindow.visibleViewController() else { return nil} return visableVC } //MARK: - Country Left View private func setupCountryView(text:String? = nil){ // setup default size for leftview let height = self.frame.size.height; let frame = CGRect(x:0,y:0,width: self.frame.size.width / 2.9,height: height) // Setup main View self.contentViewholder = UIView(frame: frame) self.contentViewholder.backgroundColor = .clear // Setup Button and should be equal to left view frame self.countryButton = UIButton(frame: frame) self.countryButton.backgroundColor = .clear // Setup label size to be dynamicly resized let startPadding = self.frame.size.width / 3.2 let labelOriginX = frame.width - startPadding let labelWidth = frame.width - labelOriginX - labelOriginX self.countryCodeLabel = UILabel(frame: CGRect(x:labelOriginX,y:frame.origin.y,width: labelWidth,height: height)) self.countryCodeLabel.text = text self.countryCodeLabel.textAlignment = .center self.countryCodeLabel.sizeToFit() // Setup separator to be at trailing of left view let topPadding = height / 3.5 let leftPadding : CGFloat = 8 self.separator = UIView(frame: CGRect(x: self.countryCodeLabel.frame.width + labelOriginX + leftPadding,y:topPadding,width: separatorWidth,height: height - topPadding*2)) // Set default style self.separator.backgroundColor = separatorBackgroundColor self.countryCodeLabel.textColor = codeTextColor self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = self.borderWidth self.layer.cornerRadius = self.cornerRadius self.layer.masksToBounds = true self.backgroundColor = self.backgroundTintColor // Add Target To Button self.countryButton.addTarget(self, action: #selector(presentCountries(_:)), for: .touchUpInside) // resize the left view depending on the views inside (label/separator/padding) let leftViewRightPadding : CGFloat = 8 let newContentViewFrame = CGRect(x:0,y:0,width: self.countryCodeLabel.frame.width + labelOriginX + leftPadding + separatorWidth + leftViewRightPadding,height: height) self.contentViewholder = UIView(frame: newContentViewFrame) // Setup contentView self.contentViewholder.addSubview(countryCodeLabel) self.contentViewholder.addSubview(countryButton) self.contentViewholder.addSubview(separator) // set left view self.leftViewMode = UITextField.ViewMode.always self.leftView = self.contentViewholder // re center country code label self.countryCodeLabel.center.y = self.contentViewholder.center.y } //MARK: - Style public func setStyle(backgroundTint:UIColor,separatorColor:UIColor,borderColor:UIColor,borderWidth:CGFloat,cornerRadius:CGFloat,countryCodeTextColor:UIColor){ self.setBorderColor(borderColor, width: borderWidth) self.setCornerRadius(cornerRadius) self.setBackgroundTint(backgroundTint) self.setCountryCodeTextColor(countryCodeTextColor) self.setSeparatorColor(separatorColor) } public func setBorderColor(_ color: UIColor,width:CGFloat){ self.layer.borderColor = color.cgColor self.layer.borderWidth = width } public func setCornerRadius(_ size:CGFloat){ self.layer.cornerRadius = size self.layer.masksToBounds = true } public func setBackgroundTint(_ color:UIColor){ self.backgroundColor = color } public func setCountryCodeTextColor(_ color:UIColor){ countryCodeLabel.textColor = color } public func setSeparatorColor(_ color:UIColor){ separator.backgroundColor = color } //MARK:- Display Customizations /// This is responsible to set the search algo for finding the country eather using locale or sim card, or even both. /// /// - Parameter type: SearchType public func setDefaultCountrySearch(to type:SearchType){ self.defaultsSearchType = type } /// It will hide the country international key in the countries list /// /// - Parameter hidden: true or false public func setCountryCodeInList(hidden:Bool ){ self.isCountryCodeInListHidden = hidden } /// This is responsible for setting your prefered way of showing the selected country in code field, Example US +1 or US or +1 etc. /// /// - Parameter type: CodeDisplay public func setCountryCodeDisplay(type:CodeDisplay){ self.countryCodeDisplay = type } //MARK: - Actions and Selectors @objc private func presentCountries(_ textField:FMPhoneTextField){ let vc = CountriesViewController(delegate: self, language: language,isCountryCodeHidden: self.isCountryCodeInListHidden) let navigation = UINavigationController(rootViewController: vc) guard let topMostViewController = self.getTopMostViewController() else { print("Could not present"); return } topMostViewController.present(navigation, animated: true, completion: nil) } } //MARK: - Country Delegate extension FMPhoneTextField:CountriesDelegate { internal func didSelectCountry(country: CountryElement) { DispatchQueue.main.async { // update the country and the code self.updateCountryDisplay(country: country) } guard let delegate = self.countryDelegate else {return} delegate.didSelectCountry(country) } } //MARK: - Country Code Getters fileprivate extension FMPhoneTextField { class func getCountryCodeFromCellularProvider() -> String? { let networkInfo = CTTelephonyNetworkInfo() let carrier = networkInfo.subscriberCellularProvider return carrier?.isoCountryCode } class func getCountryCodeFromLocale() -> String? { let currentLocale : NSLocale = NSLocale.current as NSLocale let countryCode = currentLocale.object(forKey: NSLocale.Key.countryCode) as? String return countryCode } } //MARK: - View Controller Getter fileprivate extension UIWindow { func visibleViewController() -> UIViewController? { if let rootViewController: UIViewController = self.rootViewController { return UIWindow.getVisibleViewControllerFrom(rootViewController) } return nil } class func getVisibleViewControllerFrom(_ vc:UIViewController) -> UIViewController { if vc.isKind(of: UINavigationController.self) { let navigationController = vc as! UINavigationController return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController!) } else if vc.isKind(of: UITabBarController.self) { let tabBarController = vc as! UITabBarController return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!) } else { if let presentedViewController = vc.presentedViewController { return UIWindow.getVisibleViewControllerFrom(presentedViewController) } else { return vc; } } } }
81cba7b25f029481806e0faee002c2d2
33.462243
178
0.619588
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Global/Controls/FocusRectView.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 2019-05-30. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class FocusRectView: UIView { var focusRectSize: CGSize? var focusRectFrameColor: UIColor? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = .clear } override func draw(_ rect: CGRect) { super.draw(rect) if let ct = UIGraphicsGetCurrentContext(), let focusRectSize = focusRectSize { let color = (self.focusRectFrameColor ?? UIColor.black.withAlphaComponent(0.65)).cgColor ct.setFillColor(color) ct.fill(self.bounds) let targetHalfHeight = min(focusRectSize.height, self.bounds.height) / 2 let targetHalfWidth = min(focusRectSize.width, self.bounds.width) / 2 let cutoutRect = CGRect(x: self.bounds.midX - targetHalfWidth, y: self.bounds.midY - targetHalfHeight, width: targetHalfWidth * 2, height: targetHalfHeight * 2) let path = UIBezierPath(roundedRect: cutoutRect, cornerRadius: 8) ct.setBlendMode(.destinationOut) path.fill() } } }
267d5bc65099e1b159e774534b8a189e
30.02381
172
0.650038
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornTime/Extensions/PCTPlayerViewController+MediaPlayer.swift
gpl-3.0
1
import Foundation import MediaPlayer import AlamofireImage extension PCTPlayerViewController { func addRemoteCommandCenterHandlers() { let center = MPRemoteCommandCenter.shared() center.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.playandPause() return self.mediaplayer.state == .paused ? .success : .commandFailed } center.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.playandPause() return self.mediaplayer.state == .playing ? .success : .commandFailed } if #available(iOS 9.1, tvOS 9.1, *) { center.changePlaybackPositionCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.mediaplayer.time = VLCTime(number: NSNumber(value: (event as! MPChangePlaybackPositionCommandEvent).positionTime * 1000)) return .success } } center.stopCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.mediaplayer.stop() return .success } center.changePlaybackRateCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.mediaplayer.rate = (event as! MPChangePlaybackRateCommandEvent).playbackRate return .success } center.skipForwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.mediaplayer.jumpForward(Int32((event as! MPSkipIntervalCommandEvent).interval)) return .success } center.skipBackwardCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in self.mediaplayer.jumpBackward(Int32((event as! MPSkipIntervalCommandEvent).interval)) return .success } } func removeRemoteCommandCenterHandlers() { nowPlayingInfo = nil UIApplication.shared.endReceivingRemoteControlEvents() } func configureNowPlayingInfo() { nowPlayingInfo = [MPMediaItemPropertyTitle: media.title, MPMediaItemPropertyPlaybackDuration: TimeInterval(streamDuration/1000), MPNowPlayingInfoPropertyElapsedPlaybackTime: mediaplayer.time.value.doubleValue/1000, MPNowPlayingInfoPropertyPlaybackRate: Double(mediaplayer.rate), MPMediaItemPropertyMediaType: MPMediaType.movie.rawValue] if let image = media.mediumCoverImage ?? media.mediumBackgroundImage, let request = try? URLRequest(url: image, method: .get) { ImageDownloader.default.download(request) { (response) in guard let image = response.result.value else { return } if #available(iOS 10.0, tvOS 10.0, *) { self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { (_) -> UIImage in return image } } else { self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: image) } } } } override func remoteControlReceived(with event: UIEvent?) { guard let event = event else { return } switch event.subtype { case .remoteControlPlay: fallthrough case .remoteControlPause: fallthrough case .remoteControlTogglePlayPause: playandPause() case .remoteControlStop: mediaplayer.stop() default: break } } }
04c2a3967644c3ccb80bfb9a2f289473
39.107527
142
0.606434
false
false
false
false
Lollipop95/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/View/Main/NewFeature/WBNewFeatureView.swift
mit
1
// // WBNewFeatureView.swift // WeiBo // // Created by Ning Li on 2017/5/5. // Copyright © 2017年 Ning Li. All rights reserved. // import UIKit /// 新特性视图 class WBNewFeatureView: UIView { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var enterButton: UIButton! @IBOutlet weak var pageControl: UIPageControl! /// 创建新特性视图 class func newFeatureView() -> WBNewFeatureView { let nib = UINib(nibName: "WBNewFeatureView", bundle: nil) let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView v.frame = UIScreen.main.bounds return v } override func awakeFromNib() { super.awakeFromNib() let count = 4 let rect = scrollView.bounds for i in 1...count { let imageName = "new_feature_\(i)" let imageView = UIImageView(image: UIImage(named: imageName)) imageView.frame = rect.offsetBy(dx: CGFloat(i - 1) * rect.width, dy: 0) scrollView.addSubview(imageView) } scrollView.contentSize = CGSize(width: CGFloat(count) * rect.width, height: 0) scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.isPagingEnabled = true scrollView.bounces = false scrollView.delegate = self enterButton.isHidden = true } // MARK: - 监听方法 /// 进入微博 @IBAction func enterStatus() { removeFromSuperview() } } // MARK: - UIScrollViewDelegate extension WBNewFeatureView: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5) pageControl.currentPage = page pageControl.isHidden = (page > scrollView.subviews.count - 2) enterButton.isHidden = true } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let page = Int(scrollView.contentOffset.x / scrollView.bounds.width) enterButton.isHidden = (page != scrollView.subviews.count - 1) } }
dd42cdc83eddd2d5043b5479a9e049e5
26.634146
86
0.606355
false
false
false
false