repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hoseking/Peak
Source/Audio/Nodes/IONode.swift
1
778
// Copyright © 2015 Venture Media Labs. All rights reserved. // // This file is part of Peak. The full Peak copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import AudioToolbox open class IONode: Node { open var audioUnit: AudioUnit? = nil open var audioNode: AUNode = 0 open var cd: AudioComponentDescription public init() { #if os(iOS) let audioUnitSubType = kAudioUnitSubType_RemoteIO #else let audioUnitSubType = kAudioUnitSubType_VoiceProcessingIO #endif cd = AudioComponentDescription(manufacturer: kAudioUnitManufacturer_Apple, type: kAudioUnitType_Output, subType: audioUnitSubType) } }
mit
ff9d5aaa051996566a0a7dc41e894dc1
34.318182
138
0.736165
4.709091
false
false
false
false
ihomway/RayWenderlichCourses
Mastering Auto Layout/MasteringAutoLayout/MasteringAutoLayout/DictionaryViewController.swift
1
1430
// // DictionaryViewController.swift // MasteringAutoLayout // // Created by HOMWAY on 29/06/2017. // Copyright © 2017 ihomway. All rights reserved. // import UIKit class DictionaryViewController: UITableViewController { override func awakeFromNib() { super.awakeFromNib() modalPresentationStyle = .popover popoverPresentationController?.delegate = self let rightButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(DictionaryViewController.dismissAction)) self.navigationItem.rightBarButtonItem = rightButtonItem let backgroundImageView = UIImageView(image: #imageLiteral(resourceName: "bg-parchment")) backgroundImageView.contentMode = .center tableView.backgroundView = backgroundImageView } func dismissAction() { dismiss(animated: true, completion: nil) } } extension DictionaryViewController: UIPopoverPresentationControllerDelegate { func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { return UINavigationController(rootViewController: controller.presentedViewController) } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { if traitCollection.verticalSizeClass == .regular { return .none } else { return .fullScreen } } }
mit
e13ed3a2003c14072e6330fdc750971c
32.232558
167
0.79846
5.158845
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/EnhancedMultipleChoice/RSEnhancedMultipleChoiceCellTextFieldAccessory.swift
1
1820
// // RSEnhancedMultipleChoiceCellTextFieldAccessory.swift // ResearchSuiteExtensions // // Created by James Kizer on 4/26/18. // import UIKit import ResearchKit open class RSEnhancedMultipleChoiceCellTextFieldAccessory: UIStackView { open class func newView() -> RSEnhancedMultipleChoiceCellTextFieldAccessory? { let bundle = Bundle(for: RSEnhancedMultipleChoiceCellTextFieldAccessory.self) guard let views = bundle.loadNibNamed("RSEnhancedMultipleChoiceCellTextFieldAccessory", owner: nil, options: nil), let view = views.first as? RSEnhancedMultipleChoiceCellTextFieldAccessory else { return nil } // self.configureView(view: view, minimumValue: minimumValue, maximumValue: maximumValue) return view } // open class func configureView(view: RSSliderView, minimumValue: Int, maximumValue: Int, stepSize: Int = 1) { // // view.sliderView.numberOfSteps = (maximumValue - minimumValue) / stepSize // view.sliderView.maximumValue = Float(maximumValue) // view.sliderView.minimumValue = Float(minimumValue) // // let tapGestureRecognizer = UITapGestureRecognizer(target: view, action: #selector(sliderTouched(_:))) // view.sliderView.addGestureRecognizer(tapGestureRecognizer) // // let panGestureRecognizer = UIPanGestureRecognizer(target: view, action: #selector(sliderTouched(_:))) // view.sliderView.addGestureRecognizer(panGestureRecognizer) // // // view.sliderView.isUserInteractionEnabled = false // // view.minimumValue = minimumValue // view.maximumValue = maximumValue // } @IBOutlet var textLabel: UILabel! @IBOutlet var textField: UITextField! }
apache-2.0
00df951f4b851cb9e1cdd53d9d9cecbd
36.142857
122
0.682418
5.2
false
false
false
false
WalterCreazyBear/Swifter30
UIAnimateDemo/UIAnimateDemo/ViewController.swift
1
2854
// // ViewController.swift // UIAnimateDemo // // Created by Bear on 2017/6/29. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class ViewController: UIViewController { let cellId = "CELLID" // MARK: - Variables fileprivate let items = ["2-Color", "Simple 2D Rotation", "Multicolor", "Multi Point Position", "BezierCurve Position", "Color and Frame Change", "View Fade In", "Pop"] lazy var tableView : UITableView = { let view : UITableView = UITableView.init(frame: self.view.bounds) view.delegate = self view.dataSource = self view.backgroundColor = UIColor.white view.register(UITableViewCell.self, forCellReuseIdentifier: self.cellId) return view }() override func viewDidLoad() { super.viewDidLoad() title = "UIAnimationDemo" view.backgroundColor = UIColor.white view.addSubview(tableView) } override func viewWillAppear(_ animated: Bool) { animateTable() } func animateTable() { tableView.reloadData() let cells = tableView.visibleCells let tableHeight = tableView.bounds.size.height // move all cells to the bottom of the screen for cell in cells { cell.transform = CGAffineTransform(translationX: 0, y: tableHeight) } // move all cells from bottom to the right place var index = 0 for cell in cells { UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { cell.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: nil) index += 1 } } } extension ViewController:UITableViewDelegate,UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath) cell.textLabel?.text = items[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailVC = DetailViewController(animate: items[indexPath.row]) navigationController?.pushViewController(detailVC, animated: true) } }
mit
107f43ddf523b7899578661a8ae91452
29.010526
123
0.58611
5.269871
false
false
false
false
Bunn/macGist
macGist/SettingsViewController.swift
1
2208
// // SettingsViewController.swift // macGist // // Created by Fernando Bunn on 20/06/17. // Copyright © 2017 Fernando Bunn. All rights reserved. // import Cocoa import ServiceManagement class SettingsViewController: NSViewController { @IBOutlet weak var githubButton: NSButton! private let githubAPI = GitHubAPI() weak var delegate: SettingsViewControllerDelegate? @IBOutlet weak var notificationsButton: NSButton! @IBOutlet weak var statusLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() setupUI() } fileprivate func setupUI() { title = "Settings" if githubAPI.isAuthenticated { githubButton.title = "GitHub Log Out" statusLabel.stringValue = "Logged in" if let name = UserDefaults.standard.string(forKey: UserDefaultKeys.usernameKey.rawValue) { statusLabel.stringValue = "Logged in as \(name)" } } else { githubButton.title = "GitHub Log In" statusLabel.stringValue = "To post authenticated Gists" } notificationsButton.state = NSControl.StateValue(rawValue: UserDefaults.standard.integer(forKey: UserDefaultKeys.notificationsKey.rawValue)) } @IBAction func notificationClicked(_ sender: NSButton) { UserDefaults.standard.set(sender.state, forKey: UserDefaultKeys.notificationsKey.rawValue) } @IBAction func githubButtonClicked(_ sender: NSButton) { if githubAPI.isAuthenticated { githubAPI.logout() delegate?.didUpdateAuthStatus(controller: self) setupUI() } else { let loginViewController = LoginViewController() loginViewController.delegate = self presentAsSheet(loginViewController) } } } extension SettingsViewController: LoginViewControllerDelegate { func didFinish(controller: LoginViewController) { setupUI() delegate?.didUpdateAuthStatus(controller: self) controller.dismiss(nil) } } protocol SettingsViewControllerDelegate: class { func didUpdateAuthStatus(controller: SettingsViewController) }
mit
1396daa8806f1fb1b754efe9f9acb4ce
31.455882
148
0.670594
5.330918
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Events/WeekEventsViewController.swift
1
6433
import CoreData import Foundation import TBAData import TBAKit /** Although the weekEvent can be set via a YearSelect in the EventsContainerViewController, we need this delegate because on an initial load the weekEvent isn't set yet, and we have to set it and have the EventsContainerViewController respond to setting weekEvent in WeekEventsViewController. */ protocol WeekEventsDelegate: AnyObject { func weekEventUpdated() } class WeekEventsViewController: EventsViewController { private let year: Int weak var weekEventsDelegate: WeekEventsDelegate? // The selected Event from the weekEvents array to represent the Week to show // We need a full object as opposed to a number because of CMP, off-season, etc. var weekEvent: Event? { didSet { updateDataSource() DispatchQueue.main.async { // TODO: Scroll to top } weekEventsDelegate?.weekEventUpdated() } } var weeks: [Event] = [] init(year: Int, dependencies: Dependencies) { self.year = year self.weekEvent = WeekEventsViewController.weekEvent(for: year, in: dependencies.persistentContainer.viewContext) super.init(dependencies: dependencies) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Refreshable override var refreshKey: String? { return "\(year)_events" } override var automaticRefreshInterval: DateComponents? { return DateComponents(day: 7) } override var automaticRefreshEndDate: Date? { // Automatically refresh the events for the duration of the year // Ex: 2019 events will stop automatically refreshing on Jan 1st, 2020 return Calendar.current.date(from: DateComponents(year: year + 1)) } @objc override func refresh() { // Default to refreshing the currently selected year // Fall back to the init'd year (used during initial refresh) var year = self.year if let weekEventYear = weekEvent?.year { year = Int(weekEventYear) } var operation: TBAKitOperation! operation = tbaKit.fetchEvents(year: year) { [unowned self] (result, notModified) in guard case .success(let events) = result, !notModified else { return } let context = self.persistentContainer.newBackgroundContext() context.performChangesAndWait({ Event.insert(events, year: year, in: context) }, saved: { [unowned self] in markTBARefreshSuccessful(self.tbaKit, operation: operation) }, errorRecorder: errorRecorder) // Only setup weeks if we don't have a currently selected week if self.weekEvent == nil { context.perform { guard let we = WeekEventsViewController.weekEvent(for: year, in: context) else { return } self.persistentContainer.viewContext.perform { self.weekEvent = self.persistentContainer.viewContext.object(with: we.objectID) as? Event } } } } addRefreshOperations([operation]) } // MARK: - Stateful override var noDataText: String? { return "No events for year" } // MARK: - EventsViewControllerDataSourceConfiguration override var fetchRequestPredicate: NSPredicate { if let weekEvent = weekEvent { guard let eventType = weekEvent.eventType else { return Event.unknownYearPredicate(year: weekEvent.year) } if let week = weekEvent.week { // Event has a week - filter based on the week return Event.weekYearPredicate(week: week, year: weekEvent.year) } else { if eventType == .championshipFinals { return Event.champsYearPredicate(key: weekEvent.key, year: weekEvent.year) } else if eventType == .offseason { // Get all off season events for selected month return Event.offseasonYearPredicate(startDate: weekEvent.startDate!, endDate: weekEvent.endDate!, year: weekEvent.year) } else { return Event.eventTypeYearPredicate(eventType: eventType, year: weekEvent.year) } } } return Event.nonePredicate() } // MARK: - Private private static func weekEvent(for year: Int, in context: NSManagedObjectContext) -> Event? { let weekEvents = Event.weekEvents(for: year, in: context) if year == Calendar.current.year { // If it's the current year, setup the current week for this year return currentSeasonWeekEvent(for: year, in: context) } else if let firstWeekEvent = weekEvents.first { // Otherwise, default to the first week for this years return firstWeekEvent } return nil } private static func currentSeasonWeekEvent(for year: Int, in context: NSManagedObjectContext) -> Event? { // Find the first non-finished event for the selected year let event = Event.fetchSingleObject(in: context) { (fetchRequest) in let predicate = Event.unplayedEventPredicate(date: Date().startOfDay(), year: year) fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ predicate, Event.populatedEventsPredicate() ]) fetchRequest.sortDescriptors = [ Event.endDateSortDescriptor() ] } // Find the first overall event for the selected year let firstEvent = Event.fetchSingleObject(in: context) { (fetchRequest) in fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [ Event.yearPredicate(year: year), Event.populatedEventsPredicate() ]) fetchRequest.sortDescriptors = [ Event.startDateSortDescriptor() ] } if let event = event { return event } else if let firstEvent = firstEvent { return firstEvent } return nil } }
mit
bc06aebb79eefc80ea9229648422d5f7
35.971264
139
0.614177
5.142286
false
false
false
false
simeonpp/home-hunt
ios-client/HomeHunt/Data/AgentsData.swift
1
1811
import Foundation class AgentsData: BaseData, HttpRequesterDelegate { var url: String? var httpRequester: HttpRequesterBase? var delegate: AgentsDatadelegate? func getAll(cookie: String) { self.httpRequester?.getAll(fromUrl: self.url!, withHeaders: self.getAuthenticationHeaders(cookie: cookie), identifier: nil) } func get(agentId: Int, cookie: String) { let newUrl = "\(self.url!)/\(agentId)" self.httpRequester?.getDetails(fromUrl: newUrl, withHeaders: getAuthenticationHeaders(cookie: cookie), identifier: nil) } func didCompleteGetAllJSON(result: Any, identifier: String) { let resultAsDict = result as! Dictionary<String, Any> let error = resultAsDict["error"] if (error == nil) { let agents = (resultAsDict["result"] as! [Dictionary<String, Any>]) .map(){ Agent(withDict: $0) } self.delegate?.didReceiveAgents(agents: agents, error: nil) } else { let errorDict = error as! Dictionary<String, Any> let apiError = ApiError(withDict: errorDict) self.delegate?.didReceiveAgents(agents: [], error: apiError) } } func didCompleteGetJSON(result: Any, identifier: String) { let resultAsDict = result as! Dictionary<String, Any> let error = resultAsDict["error"] if (error == nil) { let agent = Agent(withDict: resultAsDict["result"] as! Dictionary<String, Any>) self.delegate?.didReceiveAgent(agent: agent, error: nil) } else { let errorDict = error as! Dictionary<String, Any> let apiError = ApiError(withDict: errorDict) self.delegate?.didReceiveAgent(agent: nil, error: apiError) } } }
mit
efc3485c9d3ee2114aa27b154a3b2d01
39.244444
131
0.623412
4.311905
false
false
false
false
Zyj163/YJPageViewController
YJPagerViewController/YJPageViewController/YJContainerView.swift
1
1640
// // YJContainerView.swift // YJPagerViewController // // Created by ddn on 16/8/24. // Copyright © 2016年 张永俊. All rights reserved. // import UIKit class YJContainerView: UIScrollView { fileprivate lazy var views = [Int : UIView]() var maxIdx = 0 subscript(index: Int) -> UIView? { get { return views[index] } set { let view = views[index] if view == nil && newValue != nil { views[index] = newValue addSubview(newValue!) } if view != nil && newValue == nil { views[index] = nil } } } override init(frame: CGRect) { super.init(frame: frame) isPagingEnabled = true bounces = false showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() for (index, subview) in views { maxIdx = index > maxIdx ? index : maxIdx let width = bounds.size.width let height = bounds.size.height subview.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height - contentInset.top - contentInset.bottom) } } func changeTo(_ idx: Int, animation: Bool) { setContentOffset(CGPoint(x: CGFloat(idx) * bounds.size.width, y: contentOffset.y), animated: animation) } }
gpl-3.0
da9060342fa0b9eacc524fadeee6b20b
25.306452
138
0.546291
4.594366
false
false
false
false
apple/swift-nio
Sources/NIOPosix/FileDescriptor.swift
1
1223
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore extension FileDescriptor { internal static func setNonBlocking(fileDescriptor: CInt) throws { let flags = try Posix.fcntl(descriptor: fileDescriptor, command: F_GETFL, value: 0) do { let ret = try Posix.fcntl(descriptor: fileDescriptor, command: F_SETFL, value: flags | O_NONBLOCK) assert(ret == 0, "unexpectedly, fcntl(\(fileDescriptor), F_SETFL, \(flags) | O_NONBLOCK) returned \(ret)") } catch let error as IOError { if error.errnoCode == EINVAL { // Darwin seems to sometimes do this despite the docs claiming it can't happen throw NIOFcntlFailedError() } throw error } } }
apache-2.0
d65b83b7a32cdb59e9677217e8ce64fb
39.766667
118
0.566639
4.931452
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/find-the-difference.swift
1
1444
/** * https://leetcode.com/problems/find-the-difference/ * * */ // Date: Thu Sep 24 09:23:06 PDT 2020 class Solution { /// - Complexity: /// - Time: O(s.count + t.count) /// - Space: O(s.count) func findTheDifference(_ s: String, _ t: String) -> Character { var dict: [Character : Int] = [:] for c in s { dict[c] = 1 + dict[c, default: 0] } for c in t { if let v = dict[c] { if v == 0 { return c } dict[c] = v - 1 } else { return c } } return Character("a") } }/** * https://leetcode.com/problems/find-the-difference/ * * */ // Date: Thu Sep 24 09:52:54 PDT 2020 class Solution { func findTheDifference(_ s: String, _ t: String) -> Character { var result:UInt8 = 0 for x in s.utf8 { result ^= UInt8(x) } for x in t.utf8 { result ^= UInt8(x) } return Character(UnicodeScalar(result)) } }/** * https://leetcode.com/problems/find-the-difference/ * * */ // Date: Thu Sep 24 09:59:15 PDT 2020 class Solution { func findTheDifference(_ s: String, _ t: String) -> Character { var result = s.unicodeScalars.reduce(0) { $0 ^ $1.value } result = t.unicodeScalars.reduce(result) { $0 ^ $1.value } return Character(UnicodeScalar(result)!) } }
mit
32ecd281aa2694c49c9ed0a678851d43
24.803571
67
0.500693
3.504854
false
false
false
false
lenssss/whereAmI
Whereami/View/GameAnswerBottomView.swift
1
6392
// // GameAnswerBottomView.swift // Whereami // // Created by A on 16/3/25. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit enum GameAnswerButtonType:Int { case answer1 = 1 case answer2 = 2 case answer3 = 3 case answer4 = 4 case bomb = 5 case chance = 6 case skip = 7 case wrong = 100 } class GameAnswerBottomView: UIView { typealias ButtonCallback = (UIButton) -> Void var answerBtn1:UIButton? = nil var answerBtn2:UIButton? = nil var answerBtn3:UIButton? = nil var answerBtn4:UIButton? = nil var answerButtonArray:[AnyObject]? = nil var bombBtn:UIButton? = nil var chanceBtn:UIButton? = nil var skipBtn:UIButton? = nil var callBack:ButtonCallback? = nil override init(frame: CGRect) { super.init(frame:frame) self.setUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setUI() } func setUI(){ self.answerBtn1 = UIButton() self.answerBtn1?.layer.cornerRadius = 10 self.answerBtn1?.tag = GameAnswerButtonType.answer1.rawValue self.answerBtn1?.setTitleColor(UIColor.blackColor(), forState: .Normal) self.answerBtn1?.setTitleShadowColor(UIColor.lightGrayColor(), forState: .Normal) self.answerBtn1?.backgroundColor = UIColor.whiteColor() self.answerBtn1?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.answerBtn1!) self.answerBtn2 = UIButton() self.answerBtn2?.layer.cornerRadius = 10 self.answerBtn2?.tag = GameAnswerButtonType.answer2.rawValue self.answerBtn2?.setTitleColor(UIColor.blackColor(), forState: .Normal) self.answerBtn2?.backgroundColor = UIColor.whiteColor() self.answerBtn2?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.answerBtn2!) self.answerBtn3 = UIButton() self.answerBtn3?.layer.cornerRadius = 10 self.answerBtn3?.tag = GameAnswerButtonType.answer3.rawValue self.answerBtn3?.setTitleColor(UIColor.blackColor(), forState: .Normal) self.answerBtn3?.backgroundColor = UIColor.whiteColor() self.answerBtn3?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.answerBtn3!) self.answerBtn4 = UIButton() self.answerBtn4?.layer.cornerRadius = 10 self.answerBtn4?.tag = GameAnswerButtonType.answer4.rawValue self.answerBtn4?.setTitleColor(UIColor.blackColor(), forState: .Normal) self.answerBtn4?.backgroundColor = UIColor.whiteColor() self.answerBtn4?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.answerBtn4!) self.bombBtn = UIButton() self.bombBtn?.tag = GameAnswerButtonType.bomb.rawValue self.bombBtn?.hidden = false self.bombBtn?.setBackgroundImage(UIImage(named: "bomb"), forState: .Normal) self.bombBtn?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.bombBtn!) self.chanceBtn = UIButton() self.chanceBtn?.tag = GameAnswerButtonType.chance.rawValue self.chanceBtn?.hidden = false self.chanceBtn?.setBackgroundImage(UIImage(named: "chance"), forState: .Normal) self.chanceBtn?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.chanceBtn!) self.skipBtn = UIButton() self.skipBtn?.tag = GameAnswerButtonType.skip.rawValue self.skipBtn?.hidden = false self.skipBtn?.setBackgroundImage(UIImage(named: "skip"), forState: .Normal) self.skipBtn?.rac_signalForControlEvents(.TouchUpInside).subscribeNext({ (button) -> Void in self.AnswerButtonClick(button as! UIButton) }) self.addSubview(self.skipBtn!) self.answerBtn1?.autoPinEdgeToSuperviewEdge(.Top, withInset: 0) // self.answerBtn1?.autoAlignAxisToSuperviewAxis(.Vertical) self.answerBtn1?.autoPinEdgeToSuperviewEdge(.Left, withInset: 40) self.answerBtn1?.autoPinEdgeToSuperviewEdge(.Right, withInset: 40) self.answerBtn1?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.answerBtn2!, withOffset: -10) self.answerBtn2?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.answerBtn3!, withOffset: -10) self.answerBtn3?.autoPinEdge(.Bottom, toEdge: .Top, ofView: self.answerBtn4!, withOffset: -10) self.answerBtn4?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 90) self.answerButtonArray = [self.answerBtn1!,self.answerBtn2!,self.answerBtn3!,self.answerBtn4!] // let buttonArray = self.answerButtonArray as! NSArray let buttonArray = NSArray(array: self.answerButtonArray!) buttonArray.autoMatchViewsDimension(.Height) buttonArray.autoAlignViewsToEdge(.Trailing) buttonArray.autoAlignViewsToEdge(.Leading) self.bombBtn?.autoPinEdgeToSuperviewEdge(.Left, withInset: 20) self.bombBtn?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 10) self.bombBtn?.autoSetDimensionsToSize(CGSize(width: 40,height: 40)) self.chanceBtn?.autoSetDimensionsToSize(CGSize(width: 40,height: 40)) self.chanceBtn?.autoAlignAxisToSuperviewAxis(.Vertical) self.chanceBtn?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 10) self.skipBtn?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 10) self.skipBtn?.autoPinEdgeToSuperviewEdge(.Right, withInset: 20) self.skipBtn?.autoSetDimensionsToSize(CGSize(width: 40,height: 40)) } func AnswerButtonClick(sender:UIButton){ print("---------------------\(sender.tag)") self.callBack!(sender) } }
mit
a22e6653fff3cbba1879c47b587102d2
42.462585
103
0.671623
4.385038
false
false
false
false
myandy/shi_ios
shishi/UI/Util/SSImageUtil.swift
1
7577
// // SSImageUtil.swift // shishi // // Created by tb on 2017/6/14. // Copyright © 2017年 andymao. All rights reserved. // import UIKit import Accelerate class SSImageUtil: NSObject { public static func genShiImage(_ bgImage: UIImage?, _ title: String, content: String) -> UIImage { let bgView = UIView(frame: UIScreen.main.bounds) let drawView = UIImageView() bgView.addSubview(drawView) drawView.image = bgImage // drawView.setContentHuggingPriority(1000, for: .vertical) drawView.setContentCompressionResistancePriority(250, for: .vertical) let maxWidth = bgImage?.size.width ?? UIScreen.main.bounds.size.width drawView.snp.makeConstraints { (make) in make.top.centerX.equalToSuperview() make.width.equalTo(maxWidth) } let widthOffset = convertWidth(pix: 20) let titleLabel = UILabel() drawView.addSubview(titleLabel) titleLabel.text = title titleLabel.numberOfLines = 1 titleLabel.font = UIFont.boldSystemFont(ofSize: 20) titleLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(convertWidth(pix: 20)) make.centerX.equalToSuperview() make.width.lessThanOrEqualToSuperview().offset(-widthOffset) } let contentLabel = UILabel() drawView.addSubview(contentLabel) contentLabel.text = content contentLabel.font = UIFont.systemFont(ofSize: 17) contentLabel.numberOfLines = 0 contentLabel.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom) make.left.equalToSuperview().offset(convertWidth(pix: 20)) make.centerX.equalToSuperview() make.bottom.equalToSuperview().offset(convertWidth(pix: -20)) make.width.lessThanOrEqualToSuperview().offset(-widthOffset) } bgView.layoutIfNeeded() let image = SSImageUtil.image(with: drawView) return image } // public static func genShiImage(_ bgImage: UIImage?, _ title: String, content: String) -> UIImage { // let titleAttrString = NSAttributedString(string: title, // attributes: [ // NSFontAttributeName : UIFont.boldSystemFont(ofSize: 20.0), // NSForegroundColorAttributeName : UIColor.black, // ]) // // let maxWidth = bgImage?.size.width ?? UIScreen.main.bounds.size.width // let horizonalPadding = convertWidth(pix: 20) // let maxSize = CGSize(width: maxWidth - horizonalPadding * 2, height: CGFloat(MAXFLOAT)) // let titleSize = titleAttrString.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, context: nil) // // let drawView = UIImageView() // drawView.image = bgImage // drawView.frame = CGRect(origin: CGPoint.zero, size: titleSize.size) // // let image = SSImageUtil.image(with: drawView) // return image // } public static func image(with view: UIView) -> UIImage { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(view.layer.frame.size, false, scale) view.layer.render(in: UIGraphicsGetCurrentContext()!) let viewImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return viewImage } } public let numberOfComponentsPerARBGPixel = 4 public let numberOfComponentsPerRGBAPixel = 4 public let numberOfComponentsPerGrayPixel = 3 public extension CGContext { // MARK: - ARGB bitmap context public class func ARGBBitmapContext(width: Int, height: Int, withAlpha: Bool) -> CGContext? { let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedFirst : CGImageAlphaInfo.noneSkipFirst let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * numberOfComponentsPerARBGPixel, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) return bmContext } // MARK: - RGBA bitmap context public class func RGBABitmapContext(width: Int, height: Int, withAlpha: Bool) -> CGContext? { let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * numberOfComponentsPerRGBAPixel, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) return bmContext } // MARK: - Gray bitmap context public class func GrayBitmapContext(width: Int, height: Int) -> CGContext? { let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * numberOfComponentsPerGrayPixel, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) return bmContext } } private let minPixelComponentValue = UInt8(0) private let maxPixelComponentValue = UInt8(255) // MARK: - public extension CGImage { public func hasAlpha() -> Bool { let alphaInfo = self.alphaInfo return (alphaInfo == .first || alphaInfo == .last || alphaInfo == .premultipliedFirst || alphaInfo == .premultipliedLast) } } extension CGImage { // Value should be in the range (-255, 255) public func brightened(value: Float) -> CGImage? { // Create an ARGB bitmap context let width = self.width let height = self.height guard let bmContext = CGContext.ARGBBitmapContext(width: width, height: height, withAlpha: self.hasAlpha()) else { return nil } // Get image data bmContext.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) guard let data = bmContext.data else { return nil } let pixelsCount = UInt(width * height) let pixelsCountInt = Int(pixelsCount) let dataAsFloat = UnsafeMutablePointer<Float>.allocate(capacity: pixelsCountInt) var min = Float(minPixelComponentValue), max = Float(maxPixelComponentValue) // Calculate red components var v = value let t: UnsafeMutablePointer<UInt8> = data.assumingMemoryBound(to: UInt8.self) vDSP_vfltu8(t + 1, 4, dataAsFloat, 1, pixelsCount) vDSP_vsadd(dataAsFloat, 1, &v, dataAsFloat, 1, pixelsCount) vDSP_vclip(dataAsFloat, 1, &min, &max, dataAsFloat, 1, pixelsCount) vDSP_vfixu8(dataAsFloat, 1, t + 1, 4, pixelsCount) // Calculate green components vDSP_vfltu8(t + 2, 4, dataAsFloat, 1, pixelsCount) vDSP_vsadd(dataAsFloat, 1, &v, dataAsFloat, 1, pixelsCount) vDSP_vclip(dataAsFloat, 1, &min, &max, dataAsFloat, 1, pixelsCount) vDSP_vfixu8(dataAsFloat, 1, t + 2, 4, pixelsCount) // Calculate blue components vDSP_vfltu8(t + 3, 4, dataAsFloat, 1, pixelsCount) vDSP_vsadd(dataAsFloat, 1, &v, dataAsFloat, 1, pixelsCount) vDSP_vclip(dataAsFloat, 1, &min, &max, dataAsFloat, 1, pixelsCount) vDSP_vfixu8(dataAsFloat, 1, t + 3, 4, pixelsCount) // Cleanup dataAsFloat.deallocate(capacity: pixelsCountInt) return bmContext.makeImage() } }
apache-2.0
adea4a7bb91baa8a6a81a48fb44bfde1
40.387978
231
0.639292
4.590303
false
false
false
false
larryhou/swift
ColorPicker/ColorPicker/ViewController.swift
1
6277
// // ViewController.swift // ColorPicker // // Created by larryhou on 21/09/2017. // Copyright © 2017 larryhou. All rights reserved. // import Cocoa enum ColorCollection: Int { case complementary = 2, triadic, tetradic, analogous, neutral_15, neutral_10, neutral_05 } enum ColorTheme: Int { case rgb = 0, traditional } enum ColorSpaceType: Int { case sRGB = 1, genericRGB, deviceRGB, displayP3 } var sharedColorSpace: NSColorSpace = .sRGB class ViewController: NSViewController, NSWindowDelegate, ColorPickerDelegate { @IBOutlet weak var platterView: ColorPlatterView! @IBOutlet weak var barView: ColorBarView! @IBOutlet weak var colorCollectionView: NSCollectionView! let id = NSUserInterfaceItemIdentifier("ColorCell") var size = NSSize(width: 100, height: 100) let spacing: CGFloat = 5, column: CGFloat = 2 var assets: [CGColor] = [] var collection: ColorCollection = .neutral_15 var theme: ColorTheme = .rgb override func viewDidLoad() { super.viewDidLoad() colorCollectionView.register(ColorCell.self, forItemWithIdentifier: id) barView.restoreOrigin() colorPicker(barView, eventWith: barView.color(at: barView.position)) NSEvent.addLocalMonitorForEvents(matching: .keyUp) { self.keyUp(with: $0) return $0 } } override func keyUp(with event: NSEvent) { if event.keyCode == 123 { let value = collection.rawValue - 1 collection = ColorCollection(rawValue: value < 2 ? 8 : value)! synchronize() } else if event.keyCode == 124 { let value = collection.rawValue + 1 collection = ColorCollection(rawValue: value > 8 ? 2 : value)! synchronize() } } // MARK: memu @IBAction func setTheme(_ sender: NSMenuItem) { if let parent = sender.parent?.submenu { for item in parent.items { item.state = item == sender ? .on : .off } } theme = ColorTheme(rawValue: sender.tag)! barView.theme = theme colorPicker(barView, eventWith: barView.color(at: barView.position)) } @IBAction func setCollection(_ sender: NSMenuItem) { collection = ColorCollection(rawValue: sender.tag)! synchronize() } @IBAction func setDisplayColorSpace(_ sender: NSMenuItem) { let type = ColorSpaceType(rawValue: sender.tag)! switch type { case .sRGB: sharedColorSpace = .sRGB case .genericRGB: sharedColorSpace = .genericRGB case .deviceRGB: sharedColorSpace = .deviceRGB case .displayP3: sharedColorSpace = .displayP3 } if let parent = sender.parent?.submenu { for item in parent.items { item.state = item == sender ? .on : .off } } colorCollectionView.reloadData() } override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { if menuItem.action == #selector(saveDocument(_:)) { return false } return menuItem.isEnabled } @IBAction func saveDocument(_ sender: NSMenuItem) { } func reload() { size.width = (colorCollectionView.frame.width - (column - 1) * spacing) / column size.height = size.width / 16 * 9 colorCollectionView.reloadData() } func windowDidResize(_ notification: Notification) { reload() } func colorPicker(_ sender: NSView, eventWith color: CGColor) { if sender == barView { platterView.setColor(color) } synchronize() } func synchronize() { assets.removeAll() switch collection { case .complementary: assets = barView.getComplementoryColors() case .triadic: assets = barView.getTriadicColors() case .tetradic: assets = barView.getTetradicColors() case .analogous: assets = barView.getAdjacentColors(angle: 30) case .neutral_15: assets = barView.getAdjacentColors(angle: 15) case .neutral_10: assets = barView.getAdjacentColors(angle: 10) case .neutral_05: assets = barView.getAdjacentColors(angle: 5) } if collection == .complementary { assets = [platterView.blendColor(assets[0])] assets.append(assets[0].opposite) } else { for i in 0..<assets.count { assets[i] = platterView.blendColor(assets[i]) } } reload() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } } extension ViewController: NSCollectionViewDataSource { func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return assets.count } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: id, for: indexPath) as! ColorCell item.color = assets[indexPath.item] return item } } extension ViewController: NSCollectionViewDelegate { } extension ViewController: NSCollectionViewDelegateFlowLayout { func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> NSEdgeInsets { return NSEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize { return size } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return spacing } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return spacing } }
mit
0817583185d47777c50fdc749ff1a947
30.38
175
0.631931
4.88785
false
false
false
false
haijianhuo/TopStore
TopStore/ViewModels/ProductsViewModel.swift
1
3265
// // ProductsViewModel.swift // TopStore // // Created by Haijian Huo on 7/14/17. // Copyright © 2017 Haijian Huo. All rights reserved. // import Foundation import RxSwift import ObjectMapper import Alamofire import Reachability class ProductsViewModel { var avatar = Variable<UIImage?>(nil) var products = [Product]([]) var productsUpdated = Variable<Bool>(false) var query: String = "" var nextPage = 1 var loadingPage = false let reachability = Reachability() let cartViewModel = CartViewModel.shared let meViewModel = MeViewModel.shared init() { print("\(#function), \(type(of: self)) *Log*") self.avatar = meViewModel.avatar } deinit { print("\(#function), \(type(of: self)) *Log*") } func addToCart(_ product: Product) { cartViewModel.addToCart(product) } func loadNextPage() { if self.loadingPage { return } self.loadingPage = true loadPage(query: self.query, page: self.nextPage) } func loadPage(query: String, page: Int) { //print("query,page:\(query), \(page)") if page == 1 { self.query = query self.nextPage = 1 } if query.count == 0 { self.products.removeAll() self.loadingPage = false self.productsUpdated.value = true return } guard let url = self.url(for: query, page: page) else { self.products.removeAll() self.loadingPage = false self.productsUpdated.value = true return } if let reachability = self.reachability { if reachability.connection == .none { self.loadingPage = false return } } Alamofire.request(url).responseJSON { response in guard let dict = response.result.value as? [String: Any] else { self.loadingPage = false return } guard let items = dict["hits"] as? [[String: Any]] else { self.loadingPage = false return } let products = Mapper<Product>().mapArray(JSONArray: items) if page == 1 { self.products.removeAll() } self.products.append(contentsOf: products) self.nextPage += 1 self.loadingPage = false self.productsUpdated.value = true } } private func url(for query: String?, page: Int) -> URL? { guard let query = query, !query.isEmpty else { return nil } let params = [ "key": "9640291-0f83fe015c9bf829242f12fcc", "q": query, "per_page": "40", "page": String(page) ] var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "pixabay.com" urlComponents.path = "/api/" urlComponents.queryItems = params.map { key, value in URLQueryItem(name: key, value: value) } return urlComponents.url } }
mit
f92499677b64b7ea17780faf4a02d8f9
25.975207
101
0.528493
4.649573
false
false
false
false
BlurredSoftware/BSWFoundation
Tests/BSWFoundationTests/APIClient/APIClientTests.swift
1
7474
// // Created by Pierluigi Cifani on 09/02/2017. // import XCTest import BSWFoundation class APIClientTests: XCTestCase { var sut: APIClient! override func setUp() { sut = APIClient(environment: HTTPBin.Hosts.production) } func testGET() throws { let ipRequest = BSWFoundation.Request<HTTPBin.Responses.IP>( endpoint: HTTPBin.API.ip ) let getTask = sut.perform(ipRequest) let _ = try self.waitAndExtractValue(getTask, timeout: 3) } func testGETWithCustomValidation() throws { let ipRequest = BSWFoundation.Request<HTTPBin.Responses.IP>( endpoint: HTTPBin.API.ip, validator: { response in if response.httpResponse.statusCode != 200 { throw ValidationError() } }) let getTask = sut.perform(ipRequest) let _ = try self.waitAndExtractValue(getTask, timeout: 3) } func testGETCancel() throws { let ipRequest = BSWFoundation.Request<HTTPBin.Responses.IP>( endpoint: HTTPBin.API.ip ) let getTask = sut.perform(ipRequest) getTask.cancel() do { let _ = try self.waitAndExtractValue(getTask) XCTFail("This should fail here") } catch let error { let nsError = error as NSError XCTAssert(nsError.domain == NSURLErrorDomain) XCTAssert(nsError.code == NSURLErrorCancelled) } } func testUpload() throws { let uploadRequest = BSWFoundation.Request<VoidResponse>( endpoint: HTTPBin.API.upload(generateRandomData()) ) let uploadTask = sut.perform(uploadRequest) var progress: ProgressObserver! = ProgressObserver(progress: uploadTask.progress) { (progress) in print(progress.fractionCompleted) } let _ = try self.waitAndExtractValue(uploadTask, timeout: 10) progress = nil } func testUploadCancel() { let uploadRequest = BSWFoundation.Request<VoidResponse>( endpoint: HTTPBin.API.upload(generateRandomData()) ) let uploadTask = sut.perform(uploadRequest) uploadTask.cancel() do { let _ = try self.waitAndExtractValue(uploadTask) XCTFail("This should fail here") } catch let error { let nsError = error as NSError XCTAssert(nsError.domain == NSURLErrorDomain) XCTAssert(nsError.code == NSURLErrorCancelled) } } func testUnauthorizedCallsRightMethod() throws { let mockDelegate = MockAPIClientDelegate() sut = APIClient(environment: HTTPBin.Hosts.production, networkFetcher: Network401Fetcher()) sut.delegate = mockDelegate let ipRequest = BSWFoundation.Request<HTTPBin.Responses.IP>( endpoint: HTTPBin.API.ip ) // We don't care about the error here let _ = try? waitAndExtractValue(sut.perform(ipRequest)) XCTAssert(mockDelegate.failedPath != nil) } func testUnauthorizedRetriesAfterGeneratingNewCredentials() throws { class MockAPIClientDelegateThatGeneratesNewSignature: APIClientDelegate { func apiClientDidReceiveUnauthorized(forRequest atPath: String, apiClient: APIClient) -> Task<()>? { apiClient.customizeRequest = { urlRequest in var mutableRequest = urlRequest mutableRequest.setValue("Daenerys Targaryen is the True Queen", forHTTPHeaderField: "JWT") return mutableRequest } return Task(success: ()) } } class SignatureCheckingNetworkFetcher: APIClientNetworkFetcher { func fetchData(with urlRequest: URLRequest) -> Task<APIClient.Response> { guard let _ = urlRequest.allHTTPHeaderFields?["JWT"] else { return Task(success: APIClient.Response(data: Data(), httpResponse: HTTPURLResponse(url: urlRequest.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!)) } return URLSession.shared.fetchData(with: urlRequest) } func uploadFile(with urlRequest: URLRequest, fileURL: URL) -> Task<APIClient.Response> { fatalError() } } sut = APIClient(environment: HTTPBin.Hosts.production, networkFetcher: SignatureCheckingNetworkFetcher()) let mockDelegate = MockAPIClientDelegateThatGeneratesNewSignature() sut.delegate = mockDelegate let ipRequest = BSWFoundation.Request<HTTPBin.Responses.IP>( endpoint: HTTPBin.API.ip ) let _ = try waitAndExtractValue(sut.perform(ipRequest)) } func testCustomizeRequests() throws { let mockNetworkFetcher = MockNetworkFetcher() mockNetworkFetcher.mockedData = Data() sut = APIClient(environment: HTTPBin.Hosts.production, networkFetcher: mockNetworkFetcher) sut.customizeRequest = { var mutableURLRequest = $0 mutableURLRequest.setValue("hello", forHTTPHeaderField: "Signature") return mutableURLRequest } let ipRequest = BSWFoundation.Request<VoidResponse>( endpoint: HTTPBin.API.ip ) let _ = try waitAndExtractValue(sut.perform(ipRequest)) guard let capturedURLRequest = mockNetworkFetcher.capturedURLRequest else { throw ValidationError() } XCTAssert(capturedURLRequest.allHTTPHeaderFields?["Signature"] == "hello") } func testCustomizeSimpleRequests() throws { let mockNetworkFetcher = MockNetworkFetcher() mockNetworkFetcher.mockedData = Data() sut = APIClient(environment: HTTPBin.Hosts.production, networkFetcher: mockNetworkFetcher) sut.customizeRequest = { var mutableURLRequest = $0 mutableURLRequest.setValue("hello", forHTTPHeaderField: "Signature") return mutableURLRequest } let _ = try waitAndExtractValue(sut.performSimpleRequest(forEndpoint: HTTPBin.API.ip)) guard let capturedURLRequest = mockNetworkFetcher.capturedURLRequest else { throw ValidationError() } XCTAssert(capturedURLRequest.allHTTPHeaderFields?["Signature"] == "hello") } } private func generateRandomData() -> Data { let length = 2048 let bytes = [UInt32](repeating: 0, count: length).map { _ in arc4random() } return Data(bytes: bytes, count: length) } import Task private class MockAPIClientDelegate: APIClientDelegate { func apiClientDidReceiveUnauthorized(forRequest atPath: String, apiClient: APIClient) -> Task<()>? { failedPath = atPath return nil } var failedPath: String? } private class Network401Fetcher: APIClientNetworkFetcher { func fetchData(with urlRequest: URLRequest) -> Task<APIClient.Response> { return Task(success: APIClient.Response(data: Data(), httpResponse: HTTPURLResponse(url: urlRequest.url!, statusCode: 401, httpVersion: nil, headerFields: nil)!)) } func uploadFile(with urlRequest: URLRequest, fileURL: URL) -> Task<APIClient.Response> { fatalError() } } struct ValidationError: Swift.Error {}
mit
c20aee722e007bcca7e15b61b42bd7d3
34.932692
182
0.631656
5.1262
false
true
false
false
arvedviehweger/swift
stdlib/public/SDK/Foundation/Data.swift
1
69632
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if DEPLOYMENT_RUNTIME_SWIFT #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) { munmap(mem, length) } internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) { free(mem) } #else @_exported import Foundation // Clang module import _SwiftFoundationOverlayShims import _SwiftCoreFoundationOverlayShims @_silgen_name("__NSDataWriteToURL") internal func __NSDataWriteToURL(_ data: NSData, _ url: NSURL, _ options: UInt, _ error: NSErrorPointer) -> Bool #endif public final class _DataStorage { public enum Backing { // A mirror of the Objective-C implementation that is suitable to inline in Swift case swift // these two storage points for immutable and mutable data are reserved for references that are returned by "known" // cases from Foundation in which implement the backing of struct Data, these have signed up for the concept that // the backing bytes/mutableBytes pointer does not change per call (unless mutated) as well as the length is ok // to be cached, this means that as long as the backing reference is retained no further objc_msgSends need to be // dynamically dispatched out to the reference. case immutable(NSData) // This will most often (perhaps always) be NSConcreteData case mutable(NSMutableData) // This will often (perhaps always) be NSConcreteMutableData // These are reserved for foreign sources where neither Swift nor Foundation are fully certain whom they belong // to from an object inheritance standpoint, this means that all bets are off and the values of bytes, mutableBytes, // and length cannot be cached. This also means that all methods are expected to dynamically dispatch out to the // backing reference. case customReference(NSData) // tracks data references that are only known to be immutable case customMutableReference(NSMutableData) // tracks data references that are known to be mutable } public static let maxSize = Int.max >> 1 public static let vmOpsThreshold = NSPageSize() * 4 public static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? { if clear { return calloc(1, size) } else { return malloc(size) } } public static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) { var dest = dest_ var source = source_ var num = num_ if _DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 { let pages = NSRoundDownToMultipleOfPageSize(num) NSCopyMemoryPages(source!, dest, pages) source = source!.advanced(by: pages) dest = dest.advanced(by: pages) num -= pages } if num > 0 { memmove(dest, source!, num) } } public static func shouldAllocateCleared(_ size: Int) -> Bool { return (size > (128 * 1024)) } public var _bytes: UnsafeMutableRawPointer? public var _length: Int public var _capacity: Int public var _needToZero: Bool public var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? public var _backing: Backing = .swift public var bytes: UnsafeRawPointer? { @inline(__always) get { switch _backing { case .swift: return UnsafeRawPointer(_bytes) case .immutable: return UnsafeRawPointer(_bytes) case .mutable: return UnsafeRawPointer(_bytes) case .customReference(let d): return d.bytes case .customMutableReference(let d): return d.bytes } } } public var mutableBytes: UnsafeMutableRawPointer? { @inline(__always) get { switch _backing { case .swift: return _bytes case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _bytes = data.mutableBytes return data.mutableBytes case .mutable: return _bytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) _bytes = data.mutableBytes return data.mutableBytes case .customMutableReference(let d): return d.mutableBytes } } } public var length: Int { @inline(__always) get { switch _backing { case .swift: return _length case .immutable: return _length case .mutable: return _length case .customReference(let d): return d.length case .customMutableReference(let d): return d.length } } @inline(__always) set { setLength(newValue) } } public func _freeBytes() { if let bytes = _bytes { if let dealloc = _deallocator { dealloc(bytes, length) } else { free(bytes) } } } public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) { var stop: Bool = false switch _backing { case .swift: block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop) case .immutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop) case .mutable: block(UnsafeBufferPointer<UInt8>(start: _bytes?.assumingMemoryBound(to: UInt8.self), count: _length), 0, &stop) case .customReference(let d): d.enumerateBytes { (ptr, range, stop) in var stopv = false let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: range.length) block(UnsafeBufferPointer(start: bytePtr, count: range.length), range.location, &stopv) if stopv { stop.pointee = true } } case .customMutableReference(let d): d.enumerateBytes { (ptr, range, stop) in var stopv = false let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: range.length) block(UnsafeBufferPointer(start: bytePtr, count: range.length), range.location, &stopv) if stopv { stop.pointee = true } } } } @inline(never) public func _grow(_ newLength: Int, _ clear: Bool) { let cap = _capacity var additionalCapacity = (newLength >> (_DataStorage.vmOpsThreshold <= newLength ? 2 : 1)) if Int.max - additionalCapacity < newLength { additionalCapacity = 0 } var newCapacity = Swift.max(cap, newLength + additionalCapacity) let origLength = _length var allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) var newBytes: UnsafeMutableRawPointer? = nil if _bytes == nil { newBytes = _DataStorage.allocate(newCapacity, allocateCleared) if newBytes == nil { /* Try again with minimum length */ allocateCleared = clear && _DataStorage.shouldAllocateCleared(newLength) newBytes = _DataStorage.allocate(newLength, allocateCleared) } } else { let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if newBytes != nil { _DataStorage.move(newBytes!, _bytes!, origLength) _freeBytes() } } /* Where calloc/memmove/free fails, realloc might succeed */ if newBytes == nil { allocateCleared = false if _deallocator != nil { newBytes = _DataStorage.allocate(newCapacity, true) if newBytes != nil { _DataStorage.move(newBytes!, _bytes!, origLength) _freeBytes() _deallocator = nil } } else { newBytes = realloc(_bytes!, newCapacity) } } /* Try again with minimum length */ if newBytes == nil { newCapacity = newLength allocateCleared = clear && _DataStorage.shouldAllocateCleared(newCapacity) if allocateCleared && tryCalloc { newBytes = _DataStorage.allocate(newCapacity, true) if newBytes != nil { _DataStorage.move(newBytes!, _bytes!, origLength) _freeBytes() } } if newBytes == nil { allocateCleared = false newBytes = realloc(_bytes!, newCapacity) } } } if newBytes == nil { /* Could not allocate bytes */ // At this point if the allocation cannot occur the process is likely out of memory // and Bad-Things™ are going to happen anyhow fatalError("unable to allocate memory for length (\(newLength))") } if origLength < newLength && clear && !allocateCleared { memset(newBytes!.advanced(by: origLength), 0, newLength - origLength) } /* _length set by caller */ _bytes = newBytes _capacity = newCapacity /* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */ _needToZero = !allocateCleared } @inline(__always) public func setLength(_ length: Int) { switch _backing { case .swift: let origLength = _length let newLength = length if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if origLength < newLength && _needToZero { memset(_bytes! + origLength, 0, newLength - origLength) } else if newLength < origLength { _needToZero = true } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .mutable(data) _length = length _bytes = data.mutableBytes case .mutable(let d): d.length = length _length = length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.length = length _backing = .customMutableReference(data) case .customMutableReference(let d): d.length = length } } @inline(__always) public func append(_ bytes: UnsafeRawPointer, length: Int) { switch _backing { case .swift: let origLength = _length let newLength = origLength + length if _capacity < newLength || _bytes == nil { _grow(newLength, false) } _length = newLength _DataStorage.move(_bytes!.advanced(by: origLength), bytes, length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.append(bytes, length: length) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.append(bytes, length: length) _backing = .customReference(data) case .customMutableReference(let d): d.append(bytes, length: length) } } // fast-path for appending directly from another data storage @inline(__always) public func append(_ otherData: _DataStorage, startingAt start: Int) { let otherLength = otherData.length if otherLength == 0 { return } if let bytes = otherData.bytes { append(bytes.advanced(by: start), length: otherLength) } } @inline(__always) public func append(_ otherData: Data) { otherData.enumerateBytes { (buffer: UnsafeBufferPointer<UInt8>, _, _) in append(buffer.baseAddress!, length: buffer.count) } } @inline(__always) public func increaseLength(by extraLength: Int) { if extraLength == 0 { return } switch _backing { case .swift: let origLength = _length let newLength = origLength + extraLength if _capacity < newLength || _bytes == nil { _grow(newLength, true) } else if _needToZero { memset(_bytes!.advanced(by: origLength), 0, extraLength) } _length = newLength case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .mutable(data) _length += extraLength _bytes = data.mutableBytes case .mutable(let d): d.increaseLength(by: extraLength) _length += extraLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.increaseLength(by: extraLength) _backing = .customReference(data) case .customMutableReference(let d): d.increaseLength(by: extraLength) } } @inline(__always) public func set(_ index: Int, to value: UInt8) { switch _backing { case .swift: fallthrough case .mutable: _bytes!.advanced(by: index).assumingMemoryBound(to: UInt8.self).pointee = value default: var theByte = value let range = NSRange(location: index, length: 1) replaceBytes(in: range, with: &theByte, length: 1) } } @inline(__always) public func replaceBytes(in range: NSRange, with bytes: UnsafeRawPointer?) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } _DataStorage.move(_bytes!.advanced(by: range.location), bytes!, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: bytes!) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: bytes!) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: bytes!) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: bytes!) } } @inline(__always) public func replaceBytes(in range: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) { let currentLength = _length let resultingLength = currentLength - range.length + replacementLength switch _backing { case .swift: let shift = resultingLength - currentLength var mutableBytes = _bytes if resultingLength > currentLength { setLength(resultingLength) mutableBytes = _bytes! } /* shift the trailing bytes */ let start = range.location let length = range.length if shift != 0 { memmove(mutableBytes! + start + replacementLength, mutableBytes! + start + length, currentLength - start - length) } if replacementLength != 0 { if replacementBytes != nil { memmove(mutableBytes! + start, replacementBytes!, replacementLength) } else { memset(mutableBytes! + start, 0, replacementLength) } } if resultingLength < currentLength { setLength(resultingLength) } case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(data) _length = replacementLength _bytes = data.mutableBytes case .mutable(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .mutable(d) _length = replacementLength _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) _backing = .customMutableReference(data) case .customMutableReference(let d): d.replaceBytes(in: range, withBytes: replacementBytes, length: replacementLength) } } @inline(__always) public func resetBytes(in range: NSRange) { if range.length == 0 { return } switch _backing { case .swift: if _length < range.location + range.length { let newLength = range.location + range.length if _capacity < newLength { _grow(newLength, false) } _length = newLength } memset(_bytes!.advanced(by: range.location), 0, range.length) case .immutable(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .mutable(data) _length = data.length _bytes = data.mutableBytes case .mutable(let d): d.resetBytes(in: range) _length = d.length _bytes = d.mutableBytes case .customReference(let d): let data = d.mutableCopy() as! NSMutableData data.resetBytes(in: range) _backing = .customMutableReference(data) case .customMutableReference(let d): d.resetBytes(in: range) } } public convenience init() { self.init(capacity: 0) } public init(length: Int) { precondition(length < _DataStorage.maxSize) var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } let clear = _DataStorage.shouldAllocateCleared(length) _bytes = _DataStorage.allocate(capacity, clear)! _capacity = capacity _needToZero = !clear _length = 0 setLength(length) } public init(capacity capacity_: Int) { var capacity = capacity_ precondition(capacity < _DataStorage.maxSize) if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = 0 _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true } public init(bytes: UnsafeRawPointer?, length: Int) { precondition(length < _DataStorage.maxSize) if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) } } public init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?) { precondition(length < _DataStorage.maxSize) if length == 0 { _capacity = 0 _length = 0 _needToZero = false _bytes = nil if let dealloc = deallocator, let bytes_ = bytes { dealloc(bytes_, length) } } else if !copy { _capacity = length _length = length _needToZero = false _bytes = bytes _deallocator = deallocator } else if _DataStorage.vmOpsThreshold <= length { _capacity = length _length = length _needToZero = true _bytes = _DataStorage.allocate(length, false)! _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } else { var capacity = length if _DataStorage.vmOpsThreshold <= capacity { capacity = NSRoundUpToMultipleOfPageSize(capacity) } _length = length _bytes = _DataStorage.allocate(capacity, false)! _capacity = capacity _needToZero = true _DataStorage.move(_bytes!, bytes, length) if let dealloc = deallocator { dealloc(bytes!, length) } } } public init(immutableReference: NSData) { _bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes) _capacity = 0 _needToZero = false _length = immutableReference.length _backing = .immutable(immutableReference) } public init(mutableReference: NSMutableData) { _bytes = mutableReference.mutableBytes _capacity = 0 _needToZero = false _length = mutableReference.length _backing = .mutable(mutableReference) } public init(customReference: NSData) { _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customReference(customReference) } public init(customMutableReference: NSMutableData) { _bytes = nil _capacity = 0 _needToZero = false _length = 0 _backing = .customMutableReference(customMutableReference) } deinit { switch _backing { case .swift: _freeBytes() default: break } } @inline(__always) public func mutableCopy(_ range: Range<Int>) -> _DataStorage { switch _backing { case .swift: return _DataStorage(bytes: _bytes?.advanced(by: range.lowerBound), length: range.count, copy: true, deallocator: nil) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return _DataStorage(mutableReference: d.mutableCopy() as! NSMutableData) } else { return _DataStorage(mutableReference: d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC().mutableCopy() as! NSMutableData) } } } public func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T { switch _backing { case .swift: let d = _bytes == nil ? NSData() : NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound), length: range.count, freeWhenDone: false) return try work(d) case .immutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return try work(d) } else { return try work(d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()) } case .mutable(let d): if range.lowerBound == 0 && range.upperBound == _length { return try work(d) } else { return try work(d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()) } case .customReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return try work(d) } else { return try work(d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()) } case .customMutableReference(let d): if range.lowerBound == 0 && range.upperBound == _length { return try work(d) } else { return try work(d.subdata(with: NSRange(location: range.lowerBound, length: range.count))._bridgeToObjectiveC()) } } } public func bridgedReference() -> NSData { switch _backing { case .swift: return _NSSwiftData(backing: self) case .immutable(let d): return d case .mutable(let d): return d case .customReference(let d): return d case .customMutableReference(let d): // Because this is returning an object that may be mutated in the future it needs to create a copy to prevent // any further mutations out from under the receiver return d.copy() as! NSData } } public var hashValue: Int { switch _backing { case .customReference(let d): return d.hash case .customMutableReference(let d): return d.hash default: let len = _length return Int(bitPattern: CFHashBytes(_bytes?.assumingMemoryBound(to: UInt8.self), Swift.min(len, 80))) } } public func subdata(in range: Range<Data.Index>) -> Data { switch _backing { case .customReference(let d): return d.subdata(with: NSRange(location: range.lowerBound, length: range.count)) case .customMutableReference(let d): return d.subdata(with: NSRange(location: range.lowerBound, length: range.count)) default: return Data(bytes: _bytes!.advanced(by: range.lowerBound), count: range.count) } } } internal class _NSSwiftData : NSData { var _backing: _DataStorage! convenience init(backing: _DataStorage) { self.init() _backing = backing } override var length: Int { return _backing.length } override var bytes: UnsafeRawPointer { // NSData's byte pointer methods are not annotated for nullability correctly // (but assume non-null by the wrapping macro guards). This placeholder value // is to work-around this bug. Any indirection to the underlying bytes of an NSData // with a length of zero would have been a programmer error anyhow so the actual // return value here is not needed to be an allocated value. This is specifically // needed to live like this to be source compatible with Swift3. Beyond that point // this API may be subject to correction. return _backing.bytes ?? UnsafeRawPointer(bitPattern: 0xBAD0)! } override func copy(with zone: NSZone? = nil) -> Any { return NSData(bytes: _backing.bytes, length: _backing.length) } #if !DEPLOYMENT_RUNTIME_SWIFT @objc func _isCompact() -> Bool { return true } #endif #if DEPLOYMENT_RUNTIME_SWIFT override func _providesConcreteBacking() -> Bool { return true } #else @objc(_providesConcreteBacking) func _providesConcreteBacking() -> Bool { return true } #endif } public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection { public typealias ReferenceType = NSData public typealias ReadingOptions = NSData.ReadingOptions public typealias WritingOptions = NSData.WritingOptions public typealias SearchOptions = NSData.SearchOptions public typealias Base64EncodingOptions = NSData.Base64EncodingOptions public typealias Base64DecodingOptions = NSData.Base64DecodingOptions public typealias Index = Int public typealias Indices = CountableRange<Int> @_versioned internal var _backing : _DataStorage @_versioned internal var _sliceRange: Range<Index> // A standard or custom deallocator for `Data`. /// /// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated. public enum Deallocator { /// Use a virtual memory deallocator. #if !DEPLOYMENT_RUNTIME_SWIFT case virtualMemory #endif /// Use `munmap`. case unmap /// Use `free`. case free /// Do nothing upon deallocation. case none /// A custom deallocator. case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) { #if DEPLOYMENT_RUNTIME_SWIFT switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } case .free: return { __NSDataInvokeDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #else switch self { case .virtualMemory: return { NSDataDeallocatorVM($0, $1) } case .unmap: return { NSDataDeallocatorUnmap($0, $1) } case .free: return { NSDataDeallocatorFree($0, $1) } case .none: return { _, _ in } case .custom(let b): return { (ptr, len) in b(ptr, len) } } #endif } } // MARK: - // MARK: Init methods /// Initialize a `Data` with copied memory content. /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes: UnsafeRawPointer, count: Int) { _backing = _DataStorage(bytes: bytes, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) { let count = MemoryLayout<SourceType>.stride * buffer.count _backing = _DataStorage(bytes: buffer.baseAddress, length: count) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of an Array. /// /// - parameter bytes: An array of bytes to copy. public init(bytes: Array<UInt8>) { let count = bytes.count _backing = bytes.withUnsafeBufferPointer { return _DataStorage(bytes: $0.baseAddress, length: count) } _sliceRange = 0..<count } /// Initialize a `Data` with the contents of an Array. /// /// - parameter bytes: An array of bytes to copy. public init(bytes: ArraySlice<UInt8>) { let count = bytes.count _backing = bytes.withUnsafeBufferPointer { return _DataStorage(bytes: $0.baseAddress, length: count) } _sliceRange = 0..<count } /// Initialize a `Data` with a repeating byte pattern /// /// - parameter repeatedValue: A byte to initialize the pattern /// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue public init(repeating repeatedValue: UInt8, count: Int) { self.init(count: count) withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in memset(bytes, Int32(repeatedValue), count) } } /// Initialize a `Data` with the specified size. /// /// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. /// /// This method sets the `count` of the data to 0. /// /// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page. /// /// - parameter capacity: The size of the data. public init(capacity: Int) { _backing = _DataStorage(capacity: capacity) _sliceRange = 0..<0 } /// Initialize a `Data` with the specified count of zeroed bytes. /// /// - parameter count: The number of bytes the data initially contains. public init(count: Int) { _backing = _DataStorage(length: count) _sliceRange = 0..<count } /// Initialize an empty `Data`. public init() { _backing = _DataStorage(length: 0) _sliceRange = 0..<0 } /// Initialize a `Data` without copying the bytes. /// /// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed. /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _backing = _DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator) _sliceRange = 0..<count } /// Initialize a `Data` with the contents of a `URL`. /// /// - parameter url: The `URL` to read. /// - parameter options: Options for the read operation. Default value is `[]`. /// - throws: An error in the Cocoa domain, if `url` cannot be read. public init(contentsOf url: URL, options: Data.ReadingOptions = []) throws { let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue)) _backing = _DataStorage(immutableReference: d) _sliceRange = 0..<d.length } /// Initialize a `Data` from a Base-64 encoded String using the given options. /// /// Returns nil when the input is not recognized as valid Base-64. /// - parameter base64String: The string to parse. /// - parameter options: Encoding options. Default value is `[]`. public init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`. /// /// Returns nil when the input is not recognized as valid Base-64. /// /// - parameter base64Data: Base-64, UTF-8 encoded input data. /// - parameter options: Decoding options. Default value is `[]`. public init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = []) { if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) { _backing = _DataStorage(immutableReference: d) _sliceRange = 0..<d.length } else { return nil } } /// Initialize a `Data` by adopting a reference type. /// /// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation. /// /// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass. /// /// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`. public init(referencing reference: NSData) { #if DEPLOYMENT_RUNTIME_SWIFT let providesConcreteBacking = reference._providesConcreteBacking() #else let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false #endif if providesConcreteBacking { _backing = _DataStorage(immutableReference: reference.copy() as! NSData) _sliceRange = 0..<reference.length } else { _backing = _DataStorage(customReference: reference.copy() as! NSData) _sliceRange = 0..<reference.length } } @_versioned internal init(backing: _DataStorage, range: Range<Index>) { _backing = backing _sliceRange = range } // ----------------------------------- // MARK: - Properties and Functions /// The number of bytes in the data. public var count: Int { @inline(__always) get { return _sliceRange.count } @inline(__always) set { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.length = newValue _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newValue) } } /// Access the bytes in the data. /// /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @inline(__always) public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { let bytes = _backing.bytes?.advanced(by: _sliceRange.lowerBound) ?? UnsafeRawPointer(bitPattern: 0xBAD0)! let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride) return try body(contentPtr) } /// Mutate the bytes in the data. /// /// This function assumes that you are mutating the contents. /// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. @inline(__always) public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let mutableBytes = _backing.mutableBytes?.advanced(by: _sliceRange.lowerBound) ?? UnsafeMutableRawPointer(bitPattern: 0xBAD0)! let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride) return try body(UnsafeMutablePointer(contentPtr)) } // MARK: - // MARK: Copy Bytes /// Copy the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter count: The number of bytes to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes. @inline(__always) public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) { if count == 0 { return } memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: _sliceRange.lowerBound), count) } @inline(__always) private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { if range.length == 0 { return } memcpy(UnsafeMutableRawPointer(pointer), _backing.bytes!.advanced(by: range.location), range.length) } /// Copy a subset of the contents of the data to a pointer. /// /// - parameter pointer: A pointer to the buffer you wish to copy the bytes into. /// - parameter range: The range in the `Data` to copy. /// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes. public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) { _copyBytesHelper(to: pointer, from: NSRange(range)) } // Copy the contents of the data into a buffer. /// /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. /// - returns: Number of bytes copied into the destination buffer. public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int { let cnt = count guard cnt > 0 else { return 0 } let copyRange : Range<Index> if let r = range { guard !r.isEmpty else { return 0 } precondition(r.lowerBound >= 0) precondition(r.lowerBound < cnt, "The range is outside the bounds of the data") precondition(r.upperBound >= 0) precondition(r.upperBound <= cnt, "The range is outside the bounds of the data") copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count)) } else { copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt) } guard !copyRange.isEmpty else { return 0 } let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound) _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } // MARK: - #if !DEPLOYMENT_RUNTIME_SWIFT @inline(__always) private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool { // Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation. if !options.contains(.atomic) { #if os(OSX) return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max) #else return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max) #endif } else { return false } } #endif /// Write the contents of the `Data` to a location. /// /// - parameter url: The location to write the data into. /// - parameter options: Options for writing the data. Default value is `[]`. /// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`. public func write(to url: URL, options: Data.WritingOptions = []) throws { try _backing.withInteriorPointerReference(_sliceRange) { #if DEPLOYMENT_RUNTIME_SWIFT try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) #else if _shouldUseNonAtomicWriteReimplementation(options: options) { var error: NSError? = nil guard __NSDataWriteToURL($0, url as NSURL, options.rawValue, &error) else { throw error! } } else { try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue)) } #endif } } // MARK: - /// Find the given `Data` in the content of this `Data`. /// /// - parameter dataToFind: The data to be searched for. /// - parameter options: Options for the search. Default value is `[]`. /// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data. /// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found. /// - precondition: `range` must be in the bounds of the Data. public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? { let nsRange : NSRange if let r = range { nsRange = NSMakeRange(r.lowerBound, r.upperBound - r.lowerBound) } else { nsRange = NSMakeRange(0, _backing.length) } let result = _backing.withInteriorPointerReference(_sliceRange) { $0.range(of: dataToFind, options: options, in: nsRange) } if result.location == NSNotFound { return nil } return result.location..<(result.location + result.length) } /// Enumerate the contents of the data. /// /// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes. /// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`. public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) { _backing.enumerateBytes(block) } @inline(__always) public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) { if count == 0 { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.append(bytes, length: count) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + count) } @inline(__always) public mutating func append(_ other: Data) { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.append(other._backing, startingAt: other._sliceRange.lowerBound) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + other.count) } /// Append a buffer of bytes to the data. /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. @inline(__always) public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) { if buffer.count == 0 { return } if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.append(buffer.baseAddress!, length: buffer.count * MemoryLayout<SourceType>.stride) _sliceRange = _sliceRange.lowerBound..<(_sliceRange.upperBound + buffer.count * MemoryLayout<SourceType>.stride) } @inline(__always) public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Iterator.Element { let estimatedCount = newElements.underestimatedCount var idx = count count += estimatedCount for byte in newElements { let newIndex = idx + 1 if newIndex > count { count = newIndex } self[idx] = byte idx = newIndex } } @inline(__always) public mutating func append(contentsOf bytes: [UInt8]) { bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in append(buffer) } } // MARK: - /// Set a region of the data to `0`. /// /// If `range` exceeds the bounds of the data, then the data is resized to fit. /// - parameter range: The range in the data to set to `0`. @inline(__always) public mutating func resetBytes(in range: Range<Index>) { let range = NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.resetBytes(in: range) if _sliceRange.count < range.location + range.length { let newLength = range.location + range.length _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + newLength) } } /// Replace a region of bytes in the data with new data. /// /// This will resize the data if required, to fit the entire contents of `data`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append. /// - parameter data: The replacement data. @inline(__always) public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) { let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound) let cnt = data.count if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let resultingLength = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Int in let currentLength = _backing.length _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) return currentLength - nsRange.length + cnt } _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + resultingLength) } @inline(__always) public mutating func replaceSubrange(_ subrange: CountableRange<Index>, with data: Data) { let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound) let cnt = data.count if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let resultingLength = data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Int in let currentLength = _backing.length _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) return currentLength - nsRange.length + cnt } _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + resultingLength) } /// Replace a region of bytes in the data with new bytes from a buffer. /// /// This will resize the data if required, to fit the entire contents of `buffer`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter buffer: The replacement bytes. @inline(__always) public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) { let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound) let bufferCount = buffer.count * MemoryLayout<SourceType>.stride if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let currentLength = _backing.length _backing.replaceBytes(in: nsRange, with: buffer.baseAddress, length: bufferCount) let resultingLength = currentLength - nsRange.length + bufferCount _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + resultingLength) } /// Replace a region of bytes in the data with new bytes from a collection. /// /// This will resize the data if required, to fit the entire contents of `newElements`. /// /// - precondition: The bounds of `subrange` must be valid indices of the collection. /// - parameter subrange: The range in the data to replace. /// - parameter newElements: The replacement bytes. @inline(__always) public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element { // Calculate this once, it may not be O(1) let replacementCount: Int = numericCast(newElements.count) let currentCount = self.count let subrangeCount = subrange.count if currentCount < subrange.lowerBound + subrangeCount { if subrangeCount == 0 { preconditionFailure("location \(subrange.lowerBound) exceeds data count \(currentCount)") } else { preconditionFailure("range \(subrange) exceeds data count \(currentCount)") } } let resultCount = currentCount - subrangeCount + replacementCount if resultCount != currentCount { // This may realloc. // In the future, if we keep the malloced pointer and count inside this struct/ref instead of deferring to NSData, we may be able to do this more efficiently. self.count = resultCount } let shift = resultCount - currentCount let start = subrange.lowerBound self.withUnsafeMutableBytes { (bytes : UnsafeMutablePointer<UInt8>) -> Void in if shift != 0 { let destination = bytes + start + replacementCount let source = bytes + start + subrangeCount memmove(destination, source, currentCount - start - subrangeCount) } if replacementCount != 0 { let buf = UnsafeMutableBufferPointer(start: bytes + start, count: replacementCount) var (it,idx) = newElements._copyContents(initializing: buf) precondition(it.next() == nil && idx == buf.endIndex, "newElements iterator returned different count to newElements.count") } } } @inline(__always) public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) { let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound) if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } let currentLength = _backing.length _backing.replaceBytes(in: nsRange, with: bytes, length: cnt) let resultingLength = currentLength - nsRange.length + cnt _sliceRange = _sliceRange.lowerBound..<(_sliceRange.lowerBound + resultingLength) } /// Return a new copy of the data in a specified range. /// /// - parameter range: The range to copy. @inline(__always) public func subdata(in range: Range<Index>) -> Data { let length = count if count == 0 { return Data() } precondition(length >= range.upperBound) return _backing.subdata(in: range) } // MARK: - // /// Returns a Base-64 encoded string. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded string. public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedString(options: options) } } /// Returns a Base-64 encoded `Data`. /// /// - parameter options: The options to use for the encoding. Default value is `[]`. /// - returns: The Base-64 encoded data. public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data { return _backing.withInteriorPointerReference(_sliceRange) { return $0.base64EncodedData(options: options) } } // MARK: - // /// The hash value for the data. public var hashValue: Int { return _backing.hashValue } @inline(__always) public func advanced(by amount: Int) -> Data { let length = count - amount precondition(length > 0) return withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data in return Data(bytes: ptr.advanced(by: amount), count: length) } } // MARK: - // MARK: - // MARK: Index and Subscript /// Sets or returns the byte at the specified index. public subscript(index: Index) -> UInt8 { @inline(__always) get { return _backing.bytes!.advanced(by: _sliceRange.lowerBound + index).assumingMemoryBound(to: UInt8.self).pointee } @inline(__always) set { if !isKnownUniquelyReferenced(&_backing) { _backing = _backing.mutableCopy(_sliceRange) } _backing.set(index, to: newValue) } } public subscript(bounds: Range<Index>) -> Data { @inline(__always) get { return Data(backing: _backing, range: bounds) } @inline(__always) set { replaceSubrange(bounds, with: newValue) } } public subscript(bounds: CountableRange<Index>) -> Data { @inline(__always) get { return Data(backing: _backing, range: bounds.lowerBound..<bounds.upperBound) } @inline(__always) set { replaceSubrange(bounds, with: newValue) } } public subscript(bounds: ClosedRange<Index>) -> Data { @inline(__always) get { return Data(backing: _backing, range: bounds.lowerBound..<bounds.upperBound) } @inline(__always) set { replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue) } } public subscript(bounds: CountableClosedRange<Index>) -> Data { @inline(__always) get { return Data(backing: _backing, range: bounds.lowerBound..<bounds.upperBound) } @inline(__always) set { replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue) } } /// The start `Index` in the data. public var startIndex: Index { @inline(__always) get { return _sliceRange.lowerBound } } /// The end `Index` into the data. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { @inline(__always) get { return _sliceRange.upperBound } } @inline(__always) public func index(before i: Index) -> Index { return i - 1 } @inline(__always) public func index(after i: Index) -> Index { return i + 1 } public var indices: CountableRange<Int> { @inline(__always) get { return startIndex..<endIndex } } /// An iterator over the contents of the data. /// /// The iterator will increment byte-by-byte. public func makeIterator() -> Data.Iterator { return Iterator(_data: self) } public struct Iterator : IteratorProtocol { private let _data: Data private var _buffer: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) private var _idx: Data.Index private let _endIdx: Data.Index fileprivate init(_data: Data) { self._data = _data _buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) _idx = _data.startIndex _endIdx = _data.endIndex } public mutating func next() -> UInt8? { guard _idx < _endIdx else { return nil } defer { _idx += 1 } let bufferSize = MemoryLayout.size(ofValue: _buffer) return withUnsafeMutablePointer(to: &_buffer) { ptr_ in let ptr = UnsafeMutableRawPointer(ptr_).assumingMemoryBound(to: UInt8.self) let bufferIdx = (_idx - _data.startIndex) % bufferSize if bufferIdx == 0 { // populate the buffer _data.copyBytes(to: ptr, from: _idx..<(_endIdx - _idx > bufferSize ? _idx + bufferSize : _endIdx)) } return ptr[bufferIdx] } } } // MARK: - // @available(*, unavailable, renamed: "count") public var length: Int { get { fatalError() } set { fatalError() } } @available(*, unavailable, message: "use withUnsafeBytes instead") public var bytes: UnsafeRawPointer { fatalError() } @available(*, unavailable, message: "use withUnsafeMutableBytes instead") public var mutableBytes: UnsafeMutableRawPointer { fatalError() } /// Returns `true` if the two `Data` arguments are equal. public static func ==(d1 : Data, d2 : Data) -> Bool { let backing1 = d1._backing let backing2 = d2._backing if backing1 === backing2 { return true } let length1 = backing1.length if length1 != backing2.length { return false } if backing1.bytes == backing2.bytes { return true } if length1 > 0 { return d1.withUnsafeBytes { (b1) in return d2.withUnsafeBytes { (b2) in return memcmp(b1, b2, length1) == 0 } } } return true } } extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { /// A human-readable description for the data. public var description: String { return "\(self.count) bytes" } /// A human-readable debug description for the data. public var debugDescription: String { return self.description } public var customMirror: Mirror { let nBytes = self.count var children: [(label: String?, value: Any)] = [] children.append((label: "count", value: nBytes)) self.withUnsafeBytes { (bytes : UnsafePointer<UInt8>) in children.append((label: "pointer", value: bytes)) } // Minimal size data is output as an array if nBytes < 64 { children.append((label: "bytes", value: Array(self[0..<nBytes]))) } let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct) return m } } extension Data { @available(*, unavailable, renamed: "copyBytes(to:count:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { } @available(*, unavailable, renamed: "copyBytes(to:from:)") public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { } } /// Provides bridging functionality for struct Data to class NSData and vice-versa. #if DEPLOYMENT_RUNTIME_SWIFT internal typealias DataBridgeType = _ObjectTypeBridgeable #else internal typealias DataBridgeType = _ObjectiveCBridgeable #endif extension Data : DataBridgeType { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSData { return _backing.bridgedReference() } public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) } public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool { // We must copy the input because it might be mutable; just like storing a value type in ObjC result = Data(referencing: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data { var result: Data? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSData : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self)) } }
apache-2.0
0a1cd910000eb0241c09ec7b127ac010
38.879725
352
0.593178
4.977482
false
false
false
false
apple/swift-syntax
lit_tests/round_trip_regex.swift
1
441
// RUN: %empty-directory(%t) // RUN: %lit-test-helper -roundtrip -source-file %s -out %t/afterRoundtrip.swift // RUN: diff -u %t/afterRoundtrip.swift %s _ = /abc/ _ = #/abc/# _ = ##/abc/## func foo<T>(_ x: T...) {} foo(/abc/, #/abc/#, ##/abc/##) let arr = [/abc/, #/abc/#, ##/abc/##] _ = /\w+/.self _ = #/\w+/#.self _ = ##/\w+/##.self _ = /#\/\#\\/ _ = #/#/\/\#\\/# _ = ##/#|\|\#\\/## _ = #/ multiline /# _ = #/ double multiline /#
apache-2.0
43d135e2410aea2239e9b798708e4809
13.225806
80
0.433107
2.161765
false
false
false
false
PiHanHsu/myscorebaord_lite
myscoreboard_lite/Protocol/Gradient.swift
1
708
// // Gradient.swift // myscoreboard_lite // // Created by PiHan on 2017/10/9. // Copyright © 2017年 PiHan. All rights reserved. // import Foundation import UIKit protocol Gradient {} extension Gradient where Self: UIView { func addGradient(){ let gradientLayer = CAGradientLayer() gradientLayer.frame = self.bounds gradientLayer.colors = [UIColor.cyan.cgColor, UIColor.myBlue.cgColor, UIColor.blue.cgColor] gradientLayer.locations = [0.0, 0.3, 2.0] gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0) gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0) layer.insertSublayer(gradientLayer, at: 0) } } extension UIView: Gradient{}
mit
2f8f4694b3ca48c910bbde19dc4a38b3
24.178571
98
0.66383
3.710526
false
false
false
false
wowiwj/Yeep
Yeep/Yeep/ViewControllers/Base/BaseViewController.swift
1
1498
// // BaseViewController.swift // Yeep // // Created by wangju on 16/7/18. // Copyright © 2016年 wangju. All rights reserved. // import UIKit class BaseViewController: SegueViewController { var animatedOnNavigationBar = true override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) guard let navigationController = navigationController else { return } navigationController.navigationBar.backgroundColor = nil navigationController.navigationBar.translucent = true navigationController.navigationBar.shadowImage = nil navigationController.navigationBar.barStyle = UIBarStyle.Default navigationController.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default) let textAttributes: [String: AnyObject] = [ NSForegroundColorAttributeName: UIColor.yeepNavgationBarTitleColor(), NSFontAttributeName: UIFont.navigationBarTitleFont() ] navigationController.navigationBar.titleTextAttributes = textAttributes navigationController.navigationBar.tintColor = nil if navigationController.navigationBarHidden { navigationController.setNavigationBarHidden(false, animated: animatedOnNavigationBar) } } }
mit
ba28c9a46a9e6cd5a67cc225e99fb1de
28.9
103
0.688294
6.388889
false
false
false
false
almapp/uc-access-ios
uc-access/src/services/WebCursos.swift
1
1184
// // WebCursos.swift // uc-access // // Created by Patricio Lopez on 11-01-16. // Copyright © 2016 Almapp. All rights reserved. // import Foundation import Alamofire import PromiseKit import Kanna public class WebCursos: Service { public static let ID = "WEBCURSOS" private static let URL = "http://webcurso.uc.cl/direct/session" private let user: String private let password: String init(user: String, password: String) { self.user = user self.password = password super.init(name: "Web Cursos UC", urls: URLs( basic: "http://webcurso.uc.cl/portal", logged: "http://webcurso.uc.cl/portal", failed: "http://webcurso.uc.cl/portal" )) self.domain = "webcurso.uc.cl" } override func login() -> Promise<[NSHTTPCookie]> { let params = [ "_username": self.user, "_password": self.password, ] return Request.POST(WebCursos.URL, parameters: params) .then { (response, _) -> [NSHTTPCookie] in self.addCookies(response) return self.cookies } } }
gpl-3.0
eb5ca98dcdb37ed1577ec1addfc72ff1
25.886364
67
0.573964
3.767516
false
false
false
false
zapdroid/RXWeather
Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift
1
1977
// // Do.swift // RxSwift // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class DoSink<O: ObserverType>: Sink<O>, ObserverType { typealias Element = O.E typealias Parent = Do<Element> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { do { try _parent._eventHandler(event) forwardOn(event) if event.isStopEvent { dispose() } } catch let error { forwardOn(.error(error)) dispose() } } } final class Do<Element>: Producer<Element> { typealias EventHandler = (Event<Element>) throws -> Void fileprivate let _source: Observable<Element> fileprivate let _eventHandler: EventHandler fileprivate let _onSubscribe: (() -> Void)? fileprivate let _onSubscribed: (() -> Void)? fileprivate let _onDispose: (() -> Void)? init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { _source = source _eventHandler = eventHandler _onSubscribe = onSubscribe _onSubscribed = onSubscribed _onDispose = onDispose } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { _onSubscribe?() let sink = DoSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) _onSubscribed?() let onDispose = _onDispose let allSubscriptions = Disposables.create { subscription.dispose() onDispose?() } return (sink: sink, subscription: allSubscriptions) } }
mit
6d58d3d5bd27cd106911d987f5cd8bb5
30.365079
160
0.605263
4.649412
false
false
false
false
XeresRazor/SMGOLFramework
Sources/Socket.swift
2
7837
// // Socket.swift // SMGOLFramework // // Created by David Green on 2/25/16. // Copyright © 2016 David Green. All rights reserved. // import Foundation #if os(Linux) import Glibc #else import Darwin.C #endif func sockaddr_cast(p: UnsafePointer<sockaddr_in>) -> UnsafeMutablePointer<sockaddr> { return UnsafeMutablePointer<sockaddr>(p) } func sockaddr_cast(p: UnsafePointer<sockaddr_in6>) -> UnsafeMutablePointer<sockaddr> { return UnsafeMutablePointer<sockaddr>(p) } public class Socket { public enum SocketError: ErrorType { case BindError case OptionError case ListenError } var socketHandle: Int32 var domain: SocketDomain var type: SocketType var address: SocketAddress? = nil public init?(domain: SocketDomain, type: SocketType) { self.domain = domain self.type = type socketHandle = socket(domain.value(), type.value(), 0) if socketHandle == -1 { return nil } } init(socketHandle: Int32, domain: SocketDomain, type: SocketType) { self.domain = domain self.type = type self.socketHandle = socketHandle } deinit { self.closeSocket() } public func bindTo(address: SocketAddress) throws { self.address = address var sockAddr: UnsafeMutablePointer<sockaddr> var sockLen: socklen_t var ip4Addr = address.ip4SockAddr var ip6Addr = address.ip6SockAddr switch address.type { case .ipv4: sockAddr = sockaddr_cast(&ip4Addr) sockLen = socklen_t(sizeof(sockaddr_in)) case .ipv6: sockAddr = sockaddr_cast(&ip6Addr) sockLen = socklen_t(sizeof(sockaddr_in6)) } guard bind(socketHandle, sockAddr , sockLen) == 0 else { throw SocketError.BindError } } public func closeSocket() { close(socketHandle) } } public extension Socket { public enum SocketDomain { case Unix case IPv4 case IPv6 func value() -> Int32 { switch self { case Unix: return AF_UNIX case IPv4: return AF_INET case IPv6: return AF_INET6 } } } } extension Socket { public enum SocketType { case Stream case Datagram case SequencedPacket case Raw case ReliableDatagram func value() -> Int32 { switch self { case .Stream: return SOCK_STREAM case .Datagram: return SOCK_DGRAM case .SequencedPacket: return SOCK_SEQPACKET case Raw: return SOCK_RAW case .ReliableDatagram: return SOCK_RDM } } } } public extension Socket { public struct SocketAddress { public enum SocketType { case ipv4 case ipv6 } public typealias IP6Address = (UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) var ip4SockAddr = sockaddr_in() var ip6SockAddr = sockaddr_in6() var type: SocketType public init(type: SocketType, port: UInt16) { switch type { case .ipv4: self.init(address: 0, port: port) case .ipv6: self.init(address: in6addr_any, port: port) } self.type = type } public init(address: UInt32, port: UInt16) { type = .ipv4 ip4SockAddr.sin_family = UInt8(AF_INET) ip4SockAddr.sin_addr.s_addr = address.bigEndian ip4SockAddr.sin_port = port.bigEndian } public init(address: IP6Address, port: UInt16) { type = .ipv6 ip6SockAddr.sin6_family = UInt8(AF_INET6) ip6SockAddr.sin6_addr = in6_addr(__u6_addr: in6_addr.__Unnamed_union___u6_addr(__u6_addr16: address)) ip6SockAddr.sin6_port = port.bigEndian } public init(address: in6_addr, port: UInt16) { type = .ipv6 ip6SockAddr.sin6_family = UInt8(AF_INET6) ip6SockAddr.sin6_addr = address ip6SockAddr.sin6_port = port.bigEndian } init(sockv4: sockaddr_in) { type = .ipv4 ip4SockAddr = sockv4 } init(sockv6: sockaddr_in6) { type = .ipv6 ip6SockAddr = sockv6 } } } // TODO: implement the other options, or at least the useful ones public extension Socket { public enum SocketOption { case AcceptConnections(Bool) case ReuseAddress(Bool) } public func setOption(option: SocketOption) throws { var optVal = UnsafePointer<Void>() var optLen: UInt32 var optName: Int32 var optLevel: Int32 var int32Val = Int32(0) //var stringVal = "" switch option { case .AcceptConnections(let value): int32Val = value ? 1 : 0 withUnsafePointer(&int32Val){ optVal = UnsafePointer($0) } optLen = UInt32(sizeof(Int32)) optName = SO_ACCEPTCONN optLevel = SOL_SOCKET case .ReuseAddress(let value): int32Val = value ? 1 : 0 withUnsafePointer(&int32Val){ optVal = UnsafePointer($0) } optLen = UInt32(sizeof(Int32)) optName = SO_REUSEADDR optLevel = SOL_SOCKET } guard setsockopt(socketHandle, optLevel, optName, optVal, optLen) == 0 else { throw SocketError.OptionError } } } public extension Socket { public typealias ListeningHandler = () -> Void public typealias ConnectionAcceptedHandler = (socket: Socket, address: SocketAddress) -> Void public func beginListening(backlog: Int32 = SOMAXCONN, listeningHandler: ListeningHandler, connectionHandler: ConnectionAcceptedHandler) throws { guard listen(socketHandle, backlog) == 0 else { throw SocketError.ListenError } guard let selfAddress = self.address else { throw SocketError.ListenError } listeningHandler() while true { var address: SocketAddress var socket: Socket switch selfAddress.type { case .ipv4: var incomingAddress = sockaddr_in() var incomingAddressSize = socklen_t(sizeof(sockaddr_in)) let incomingSocket = accept(self.socketHandle, sockaddr_cast(&incomingAddress), &incomingAddressSize) address = SocketAddress(sockv4: incomingAddress) socket = Socket(socketHandle: incomingSocket, domain: self.domain, type: self.type) case .ipv6: var incomingAddress = sockaddr_in6() var incomingAddressSize = socklen_t(sizeof(sockaddr_in6)) let incomingSocket = accept(self.socketHandle, sockaddr_cast(&incomingAddress), &incomingAddressSize) address = SocketAddress(sockv6: incomingAddress) socket = Socket(socketHandle: incomingSocket, domain: self.domain, type: self.type) } connectionHandler(socket: socket, address: address) } } } public extension Socket { public func setNonBlocking(shouldBlock:Bool) { var flags = fcntl(socketHandle, F_GETFL, 0) if shouldBlock { flags &= ~O_NONBLOCK } else { flags |= O_NONBLOCK } _ = fcntl(socketHandle, F_SETFL, flags) } }
mit
74f37483aeb3ebd6b1b773f9bbb7f8ea
28.908397
149
0.565722
4.38255
false
false
false
false
wujianguo/GitHubKit
GitHubApp/Classes/Profile/ProfileTableViewController.swift
1
8252
// // ProfileTableViewController.swift // GitHubKit // // Created by wujianguo on 16/7/21. // // import UIKit import SnapKit import GitHubKit import Kingfisher extension Profile { var profileDescription: String? { if let user = self as? User { return user.bio } else if let org = self as? Organization { return org.description } else { return nil } } } extension UIImageView { func clipsAsAvatar() { layer.masksToBounds = true layer.cornerRadius = 4 } } class ProfileHeadView: UIView { var isFollowing: Bool? { didSet { if let follow = isFollowing { followButton.selected = follow } } } lazy var avatarImageView: UIImageView = { let imageView = UIImageView(image: UIImage.defaultAvatar) imageView.snp_makeConstraints { (make) in make.width.height.equalTo(120) } imageView.clipsAsAvatar() return imageView }() lazy var nameLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleTitle3) return label }() lazy var loginLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) return label }() lazy var companyLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) return label }() lazy var locationLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) return label }() lazy var emailLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) return label }() lazy var linkLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption1) return label }() lazy var avatarHeadDescription: UIStackView = { let stackView = UIStackView() stackView.axis = .Vertical stackView.alignment = .Leading stackView.spacing = 4 stackView.addArrangedSubview(self.nameLabel) stackView.addArrangedSubview(self.loginLabel) stackView.addArrangedSubview(self.companyLabel) stackView.addArrangedSubview(self.locationLabel) stackView.addArrangedSubview(self.emailLabel) stackView.addArrangedSubview(self.linkLabel) return stackView }() lazy var avatarHead: UIStackView = { let stackView = UIStackView() stackView.axis = .Horizontal stackView.distribution = .Fill stackView.spacing = 8 stackView.addArrangedSubview(self.avatarImageView) stackView.addArrangedSubview(self.avatarHeadDescription) return stackView }() lazy var descriptionLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) return label }() lazy var followButton: UIButton = { let button = UIButton() button.setTitle(NSLocalizedString("Follow", comment: ""), forState: .Normal) button.setTitle(NSLocalizedString("Unfollow", comment: ""), forState: .Selected) button.addTarget(self, action: #selector(ProfileHeadView.followButtonClick(_:)), forControlEvents: .TouchUpInside) return button }() lazy var followersButton: UIButton = { let button = UIButton() button.setTitle(NSLocalizedString("Followers", comment: ""), forState: .Normal) // button.addTarget(self, action: #selector(ProfileHeadView.performToFollowers), forControlEvents: .TouchUpInside) return button }() lazy var followingButton: UIButton = { let button = UIButton() button.setTitle(NSLocalizedString("Following", comment: ""), forState: .Normal) // button.addTarget(self, action: #selector(ProfileHeadView.performToFollowing), forControlEvents: .TouchUpInside) return button }() lazy var starredButton: UIButton = { let button = UIButton() button.setTitle(NSLocalizedString("Starred", comment: ""), forState: .Normal) // button.addTarget(self, action: #selector(ProfileHeadView.performToStarred), forControlEvents: .TouchUpInside) return button }() lazy var vcardStats: UIStackView = { let stackView = UIStackView() stackView.axis = .Horizontal stackView.alignment = .Center stackView.distribution = .FillEqually stackView.addArrangedSubview(self.followersButton) stackView.addArrangedSubview(self.starredButton) stackView.addArrangedSubview(self.followingButton) return stackView }() lazy var contentView: UIStackView = { let stackView = UIStackView() stackView.axis = .Vertical // stackView.alignment = .Leading // stackView.distribution = .Fill stackView.spacing = 8 // stackView.layoutMarginsRelativeArrangement = true stackView.addArrangedSubview(self.avatarHead) stackView.addArrangedSubview(self.descriptionLabel) stackView.addArrangedSubview(self.followButton) stackView.addArrangedSubview(self.vcardStats) return stackView }() func updateUI(profile: Profile) { backgroundColor = UIColor.grayColor() contentView.removeFromSuperview() addSubview(contentView) contentView.snp_makeConstraints { (make) in make.edges.equalTo(self).inset(UIEdgeInsetsMake(8, 8, 8, 8)) } if let urlstr = profile.avatar_url, url = NSURL(string: urlstr) { avatarImageView.kf_cancelDownloadTask() avatarImageView.kf_setImageWithURL(url) } if let name = profile.name { nameLabel.text = name } if let login = profile.login { loginLabel.text = login } if let company = profile.company { companyLabel.text = company } if let location = profile.location { locationLabel.text = location } if let email = profile.email { emailLabel.text = email } if let link = profile.blog { linkLabel.text = link } if let des = profile.profileDescription { descriptionLabel.text = des } } func followButtonClick(sender: UIButton) { sender.selected = !sender.selected } /* func performToFollowers() { } func performToStarred() { } func performToFollowing() { } */ } class ProfileTableViewController: UITableViewController, RepositoryTableViewCellDelegate { var profileView: ProfileHeadView! var profile: Profile? { return nil } override func viewDidLoad() { super.viewDidLoad() profileView = ProfileHeadView(frame: CGRectMake(0, 0, 1, 280)) tableView.tableHeaderView = profileView tableView.rowHeight = 120 tableView.estimatedRowHeight = UITableViewAutomaticDimension } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let cell = cell as? RepositoryTableViewCell { cell.delegate = self } } func repositoryTableViewCellPerformToRepo(repo: Repository) { let vc = RepositoryViewController(repo: repo) navigationController?.pushViewController(vc, animated: true) } func repositoryTableViewCellPerformToProfile(repo: Repository) { // guard repo.profile?.login != profile?.login else { return } // var vc: ProfileTableViewController? // if let user = repo.user { // vc = UserProfileTableViewController(user: user) // } else if let org = repo.organization { // vc = OrganizationTableViewController(org: org) // } // if let v = vc { // navigationController?.pushViewController(v, animated: true) // } } }
mit
574739a0121a228a1cc18bf9d13cb89a
30.376426
134
0.640814
5.193203
false
false
false
false
RCacheaux/Bitbucket-iOS
UseCaseKit/UseCaseKit/AsyncOperation.swift
1
3273
// // AsyncOperation.swift // UseCaseKit // // Created by Rene Cacheaux on 12/17/16. // Copyright © 2016 Atlassian. All rights reserved. // import Foundation class AsyncOperation: Operation { // TODO: Look for comments in OpX open func asyncMain() { preconditionFailure("Action.run() abstract method must be overridden.") } fileprivate var _executing = false fileprivate var _finished = false override private(set) open var isExecuting: Bool { get { // See if you can create higher order func for this logic below var executing: Bool! synchronize { executing = self._executing } // assert not nil. return executing } set { willChangeValue(forKey: "isExecuting") synchronize { self._executing = newValue } didChangeValue(forKey: "isExecuting") } } /// 'true' if operation has finished regardless of success, error, cancellled result; otherwise `false`. /// /// - Note: Getting and setting is thread safe. override private(set) open var isFinished: Bool { get { var finished: Bool! synchronize { finished = self._finished } return finished } set { willChangeValue(forKey: "isFinished") synchronize { self._finished = newValue } didChangeValue(forKey: "isFinished") } } private var _result: OperationResult? open internal(set) var result: OperationResult? { get { var result: OperationResult? synchronize { result = self._result } // Assert not nil. return result } set { synchronize { self._result = newValue } } } // MARK: Operation Status Flags /// Always `true' since this operation is asynchronous. override open var isAsynchronous: Bool { return true } // MARK: Initialization /// Designated initializer. public override init() { super.init() } // MARK: Operation Methods /// Starts executing operation. This is a non-blocking method since this operation is asynchronous, /// safe to call directy. override open func start() { if isCancelled { isFinished = true return } isExecuting = true autoreleasepool { asyncMain() } } // Cancels executing operation. This will properly trigger KVO for the operation. override open func cancel() { super.cancel() finishedExecutingOperation(withResult: .cancelled) } /// Stores operation's result and marks operation as not executing and finished. /// /// Call this method in some sort of async callback/closure/delegate. `asyncMain()` should return immediately, /// asynchronous operations **do not** finish until this method is called regardless of whether `asyncMain()` has /// returned. open func finishedExecutingOperation(withResult result: OperationResult) { self.result = result self.isExecuting = false self.isFinished = true } /// Serial queue used to synchronize access to stored properties. fileprivate let mutationQueue = DispatchQueue(label: "com.atlassian.operationx.operationmutation", attributes: []) func synchronize(_ accessData: (Void)->Void) { mutationQueue.sync { accessData() } } }
apache-2.0
7031ed3d183208faaccaf2cc7e46ec16
24.364341
116
0.65709
4.680973
false
false
false
false
billdonner/sheetcheats9
sc9/ImportShareViewController.swift
1
2891
// // ImportShareViewController.swift // SheetCheats // // Created by william donner on 6/17/14. // Copyright (c) 2014 william donner. All rights reserved. // import UIKit /// UI reads from Itunes shared directory and calls Incorporator /// in background waiting for completion of assimilateInBackgroundFromFileURL final class ImportShareViewController: UIViewController { @IBAction func donePressed(_ sender: AnyObject) { self.performSegue(withIdentifier: "unwindToModalMenu2ID", sender: self ) } @IBOutlet weak var doneButton: UIBarButtonItem! @IBOutlet weak var importStatus: UILabel! @IBOutlet weak var readcount: UILabel! @IBOutlet weak var dupecount: UILabel! @IBOutlet weak var actindicator: UIActivityIndicatorView! @IBOutlet weak var currentfilepath: UILabel! @IBOutlet weak var viewLogButton: UIBarButtonItem! var assim:Incorporator! override func viewDidLoad() { super.viewDidLoad() lump() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let uiv = segue.destination as? LogViewController { uiv.indata = assim.buf } } func lump() { self.navigationItem.title = "Import From iTunes" self.navigationItem.leftBarButtonItem?.isEnabled = false /// kick off background assimilation let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String assim = Incorporator() let _ = assim.assimilateInBackgroundFromFileURL (URL(fileURLWithPath: documentsPath),//adjust each: { label,read,dupes in self.importStatus.text = "\(read) with \(dupes) dupes " self.readcount.text = "\(read)" self.dupecount.text = "\(dupes)" self.currentfilepath.text = label }, completion: { err,read,dupes,csv in let fresh = read - dupes /// set flag to get search to re-integrate reloadSearchController = true let blh = "added \(fresh) documents and \(csv) csv files" print (blh) AppDelegate.tinyPrint("finished load of \(fresh) fresh from iTunes file sharing") self.importStatus.text = err?.localizedDescription ?? "Finished" self.readcount.text = "\(read)" self.dupecount.text = "\(dupes)" self.currentfilepath.text = blh UIView.animate(withDuration: 2.0, animations: { self.actindicator.isHidden = true self.doneButton.isEnabled = true if dupes > 0 { self.viewLogButton.isEnabled = true } }) }) } }
apache-2.0
f0ccc27427a587e4d75331e3d8bf5f01
35.594937
119
0.60256
4.867003
false
false
false
false
IBM-Swift/Kitura
Sources/Kitura/bodyParser/Part.swift
1
1723
/* * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation // MARK Part /// A part of a parsed multi-part form body. public struct Part { /// The name attribute of the part. public internal(set) var name = "" /// The filename attribute of the part. public internal(set) var filename = "" /// Content type of the data in the part. public internal(set) var type = "text/plain" /// A dictionary of the headers: Content-Type, Content-Disposition, /// Content-Transfer-Encoding. public internal(set) var headers = [HeaderType: String]() /// The contents of the part. public internal(set) var body: ParsedBody = .raw(Data()) /// Possible header types that can be found in a part of multi-part body. public enum HeaderType { /// A Content-Disposition header (multipart/form-data bodies). case disposition /// A Content-Type header (multipart/form-data bodies). case type /// A Content-Transfer-Encoding header (multipart/form-data bodies). case transferEncoding /// A Content-Range header (multipart/byteranges bodies). case contentRange } }
apache-2.0
c6b3440cfd44e3b250ed02c69398d995
30.327273
77
0.685432
4.35101
false
false
false
false
iosdevzone/IDZSwiftScriptingGoodies
Sources/IDZSwiftScriptingGoodies/Task.swift
1
1251
// // Task.swift // IDZSwiftScriptingGoodies // // Created by idz on 11/14/15. // Copyright © 2015 iOS Developer Zone. All rights reserved. // import Foundation /** Runs a shell command, capturing the exit status, standard output and standard error. This is synchronous function. - parameter command: the shell command, e.g. `/bin/ls -l` - returns: a tuple containing the exit status, standard output and standard error. */ public func runShellCommand(command: String) -> (Int, String?, String?) { let args: [String] = command.split { $0 == " " }.map(String.init) let other = args[1..<args.count] let outputPipe = Pipe() let errorPipe = Pipe() let task = Process() task.launchPath = args[0] task.arguments = other.map { $0 } task.standardOutput = outputPipe task.standardError = errorPipe task.launch() task.waitUntilExit() let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile() let outputString = String(data:outputData, encoding: .utf8) let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile() let errorString = String(data:errorData, encoding: .utf8) return (Int(task.terminationStatus), outputString, errorString) }
mit
81d67ad932b880848ae1d48e49c7e567
31.894737
88
0.6912
4.125413
false
false
false
false
manujua82/VirtualTourist
Photo+CoreDataClass.swift
1
698
// // Photo+CoreDataClass.swift // VirtualTouristPortfolio // // Created by Kevin Bilberry on 4/26/17. // Copyright © 2017 Juan Salcedo. All rights reserved. // import Foundation import CoreData @objc(Photo) public class Photo: NSManagedObject { convenience init(photoData: NSData? = nil, photoUrl:String, pin: Pin, context: NSManagedObjectContext) { if let ent = NSEntityDescription.entity(forEntityName: "Photo", in: context) { self.init(entity: ent, insertInto: context) self.photoData = photoData self.url = photoUrl self.pin = pin } else { fatalError("Unable to find Entity name!") } } }
mit
d88760d5d71b2f23658d56e696e685be
25.807692
108
0.638451
4.14881
false
false
false
false
luzefeng/iOS8-day-by-day
23-photo-extension/ChromaKey/ChromaKeyExtension/ChromaKeyFilter.swift
21
2419
// // Copyright 2014 Scott Logic // // 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 CoreImage class ChromaKeyFilter : CIFilter { // MARK: - Properties private var kernel: CIColorKernel! var inputImage: CIImage? var activeColor = CIColor(red: 0.0, green: 1.0, blue: 0.0) var threshold: Float = 0.7 // MARK: - Initialization override init() { super.init() kernel = createKernel() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) kernel = createKernel() } // MARK: - API override var outputImage: CIImage? { if let inputImage = inputImage { let dod = inputImage.extent() let args = [inputImage as AnyObject, activeColor as AnyObject, threshold as AnyObject] return kernel.applyWithExtent(dod, arguments: args) } return nil } // MARK: - Utility methods private func createKernel() -> CIColorKernel { let kernelString = "kernel vec4 chromaKey( __sample s, __color c, float threshold ) { \n" + " vec4 diff = s.rgba - c;\n" + " float distance = length( diff );\n" + " float alpha = compare( distance - threshold, 0.0, 1.0 );\n" + " return vec4( s.rgb, alpha ); \n" + "}" return CIColorKernel(string: kernelString) } } // MARK:- Filter parameter serialization extension ChromaKeyFilter { func encodeFilterParameters() -> NSData { var dataDict = [String : AnyObject]() dataDict["activeColor"] = activeColor dataDict["threshold"] = threshold return NSKeyedArchiver.archivedDataWithRootObject(dataDict) } func importFilterParameters(data: NSData?) { if let data = data { if let dataDict = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [String : AnyObject] { activeColor = (dataDict["color"] as? CIColor) ?? activeColor threshold = (dataDict["threshold"] as? Float) ?? threshold } } } }
apache-2.0
25c6f5859f1d45ebd82c1baa860a6539
30.012821
98
0.670525
4.113946
false
false
false
false
mendesbarreto/IOS
Playground.playground/Contents.swift
1
7229
//: Playground - noun: a place where people can play import UIKit public enum WeekDays: Int { case Sunday = 1 case Monday = 2 case Tuesday = 3 case Wednesday = 4 case Thursday = 5 case Friday = 6 case Saturday = 7 } let secondsPerDay:Double = 24 * 60 * 60 ; let secondsPerWeek:Double = secondsPerDay * 7 let secondsPerMonth:Double = secondsPerWeek * 4 extension NSDate { func nextDay() -> NSDate { return self.dateByAddingTimeInterval(secondsPerDay) } func lastDay() -> NSDate { return self.dateByAddingTimeInterval(-secondsPerDay) } func lastWeek() -> NSDate { return self.dateByAddingTimeInterval(-secondsPerWeek) } func nextWeek() -> NSDate { return self.dateByAddingTimeInterval(secondsPerWeek) } func forwardWeek( weeks:Int ) -> NSDate { return self.forward(days: weeks * 7) } func backwardWeek( weeks:Int ) -> NSDate { return self.backward(days: weeks * 7) } func forward( days days:Int ) -> NSDate { return self.dateByAddingTimeInterval( NSTimeInterval( secondsPerDay * Double(days) ) ) } func backward( days days:Int ) -> NSDate { return self.dateByAddingTimeInterval( NSTimeInterval( -( secondsPerDay * Double(days) ) ) ) } func beginOfMonth() -> NSDate { let componet = self.createDateComponents() componet.day -= componet.day - 1 return componet.date! } func endOfWeek() -> NSDate { return self.forward(days: WeekDays.Saturday.rawValue - self.weekday().rawValue) } func beginOfWeek() -> NSDate { return self.forward(days: WeekDays.Sunday.rawValue - self.weekday().rawValue) } func gotoMonday() ->NSDate { return self.forward(days: WeekDays.Monday.rawValue - self.weekday().rawValue) } func weekday() -> WeekDays { let weekDay = self.createDateComponents(components: NSCalendarUnit.Weekday ).weekday return WeekDays(rawValue: weekDay)! } func day() -> Int { return self.createDateComponents(components: NSCalendarUnit.Day ).day } func month() -> Int { return self.createDateComponents(components: NSCalendarUnit.Month ).month } func year() -> Int { return self.createDateComponents(components: NSCalendarUnit.Year ).year } func createDateComponents(components components: NSCalendarUnit? = nil, calendar:NSCalendar? = nil ) -> NSDateComponents { let ca: NSCalendar if let calTemp = calendar { ca = calTemp } else { ca = NSCalendar.currentCalendar() } if let co = components { return ca.components(co, fromDate: self) } return ca.components([ NSCalendarUnit.Weekday, NSCalendarUnit.Day, NSCalendarUnit.Calendar, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second, NSCalendarUnit.Nanosecond], fromDate: self) } func weekDayName( localeIdentifier localeId:String? = nil ) -> String { let dateFormatter = NSDateFormatter() let locale: NSLocale if let localeIdentifier: String = localeId { locale = NSLocale(localeIdentifier: localeIdentifier) } else { if let preferred: String = NSLocale.preferredLanguages().first { locale = NSLocale(localeIdentifier: preferred) } else { locale = NSLocale(localeIdentifier: "pt_br") } } dateFormatter.dateFormat = "EEEE" dateFormatter.locale = locale return dateFormatter.stringFromDate(self) } func weekdayPrefix(length length:Int, localeIdentifier localeId:String? = nil ) -> String { let weekDayName = self.weekDayName(localeIdentifier: localeId) let usedLength: Int let range: Range<String.Index> if( length > weekDayName.characters.count ) { usedLength = weekDayName.characters.count } else { usedLength = length } range = Range<String.Index>(start: weekDayName.startIndex, end: weekDayName.startIndex.advancedBy(usedLength)) return weekDayName.substringWithRange(range) } func isWeekDay( weekDay:WeekDays ) -> Bool { return self.weekday() == weekDay } func zeroTime() -> NSDate { let comp = self.createDateComponents() comp.timeZone = NSTimeZone(forSecondsFromGMT: 0) return NSCalendar.currentCalendar().dateBySettingHour(0, minute: 0, second: 0, ofDate: comp.date!, options: NSCalendarOptions())! } } extension NSDateComponents { func zeroTime() { self.hour -= self.hour self.minute -= self.minute self.second -= self.second self.nanosecond -= self.nanosecond } func nextDay() { self.day += 1 updateWeekDay() } func lastDay() { self.day -= 1 updateWeekDay() } func lastWeek() { self.backward(days: 7) updateWeekDay() } func nextWeek() { self.forward(days: 7) updateWeekDay() } func forwardWeek( weeks:Int ) { self.forward(days: weeks * 7) } func backwardWeek( weeks:Int ) { self.backward(days: weeks * 7) } func forward( days days:Int ) { self.day += days updateWeekDay() } func backward( days days:Int ) { self.day -= days updateWeekDay() } func beginOfMonth() { self.day -= self.day - 1 updateWeekDay() } func endOfWeek() { self.forward(days: WeekDays.Saturday.rawValue - self.weekday) updateWeekDay() } func gotoMonday() { print( WeekDays.Monday.rawValue - self.weekday ) self.forward(days: WeekDays.Monday.rawValue - self.weekday) updateWeekDay() } func beginOfWeek() { print( WeekDays.Sunday.rawValue - self.weekday ) self.forward(days: WeekDays.Sunday.rawValue - self.weekday) updateWeekDay() } func updateWeekDay() { if let date = self.date { self.weekday = NSCalendar.currentCalendar().components(NSCalendarUnit.Weekday, fromDate: date).weekday } } } public class Day { public let name: WeekDays public let number:Int public let date: NSDate public init( date:NSDate ) { self.name = date.weekday() self.number = date.day() self.date = date print( " Name: \(name) Day: \(number) Date: \(date)" ) } } public class Week { public let days: [Day] public init( days: [Day] ){ self.days = days } } func getWeeks( from date: NSDate, weeksBefore:Int , weeksAfter: Int ) -> [Week] { let weeksToCount = weeksAfter + weeksBefore var day:NSDate var weeks = [Week]() let monday = date.gotoMonday() day = monday.backwardWeek(weeksBefore) for _ in 0...weeksToCount { var days = [Day]() print("Weed: \(day) ") for _ in 1...7 { days.append( Day(date: day) ) day = day.nextDay() } weeks.append(Week(days: days)) print("----------------------") } return weeks } let date = NSDate().zeroTime() let timeZone = NSTimeZone.localTimeZone() let seconds = timeZone.secondsFromGMTForDate(date) let d = NSDate(timeInterval: NSTimeInterval(seconds), sinceDate: date) date.createDateComponents(components: NSCalendarUnit.Day ).day // //NSTimeZone *tz = [NSTimeZone localTimeZone]; //NSInteger seconds = [tz secondsFromGMTForDate: self]; //return [NSDate dateWithTimeInterval: seconds sinceDate: self]; NSDate().zeroTime() //NSDateFormatter * dateFormatter = [NSDateFormatter new]; //NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:deviceLanguage]; // //[dateFormatter setDateFormat:@"EEEE dd MMMM"]; //[dateFormatter setLocale:locale]; // //NSString * dateString = [dateFormatter stringFromDate:[NSDate date]];
mit
6cf7b9aa10058063efa086953158aadb
22.169872
131
0.697607
3.6001
false
false
false
false
TrainingPair/Async
Source/Async.swift
9
10878
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // 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 // MARK: - DSL for GCD queues private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Don't ever use dispatch_get_global_queue(qos_class_main(), 0) re https://gist.github.com/duemunk/34babc7ca8150ff81844 } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) } } // MARK: - Async – Struct public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } // MARK: - Async – Static methods public extension Async { // Static methods /* dispatch_async() */ private static func async(block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } static func main(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.mainQueue()) } static func userInteractive(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInitiatedQueue()) } static func utility(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.utilityQueue()) } static func background(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.backgroundQueue()) } static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.async(block, inQueue: queue) } /* dispatch_after() */ private static func after(seconds: Double, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, inQueue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } static func main(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.mainQueue()) } static func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue()) } static func utility(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.utilityQueue()) } static func background(#after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.backgroundQueue()) } static func customQueue(queue: dispatch_queue_t, after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: queue) } } // MARK: - Async – Regualar methods matching static ones public extension Async { /* dispatch_async() */ private func chain(block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(self.block, queue, _chainingBlock) return Async(_chainingBlock) } func main(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.mainQueue()) } func userInteractive(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue()) } func utility(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.utilityQueue()) } func background(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue()) } func customQueue(queue: dispatch_queue_t, chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: queue) } /* dispatch_after() */ private func after(seconds: Double, block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } func main(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.mainQueue()) } func userInteractive(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue()) } func utility(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.utilityQueue()) } func background(#after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.backgroundQueue()) } func customQueue(queue: dispatch_queue_t, after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: queue) } /* cancel */ public func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER public func wait(seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } } // MARK: - Apply public struct Apply { // DSL for GCD dispatch_apply() // // Apply runs a block multiple times, before returning. // If you want run the block asynchronously from the current thread, // wrap it in an Async block, // e.g. Async.main { Apply.background(3) { ... } } public static func userInteractive(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInteractiveQueue(), block) } public static func userInitiated(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.userInitiatedQueue(), block) } public static func utility(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.utilityQueue(), block) } public static func background(iterations: Int, block: Int -> ()) { dispatch_apply(iterations, GCD.backgroundQueue(), block) } public static func customQueue(iterations: Int, queue: dispatch_queue_t, block: Int -> ()) { dispatch_apply(iterations, queue, block) } } // MARK: - qos_class_t public extension qos_class_t { // Convenience description of qos_class_t // Calculated property var description: String { get { switch self { case qos_class_main(): return "Main" case QOS_CLASS_USER_INTERACTIVE: return "User Interactive" case QOS_CLASS_USER_INITIATED: return "User Initiated" case QOS_CLASS_DEFAULT: return "Default" case QOS_CLASS_UTILITY: return "Utility" case QOS_CLASS_BACKGROUND: return "Background" case QOS_CLASS_UNSPECIFIED: return "Unspecified" default: return "Unknown" } } } } // Binary operator for qos_class_t allows for comparison in switch-statements func ~=(lhs: qos_class_t, rhs: qos_class_t) -> Bool { return lhs.value ~= rhs.value } // Make qos_class_t equatable extension qos_class_t: Equatable {} public func ==(lhs: qos_class_t, rhs: qos_class_t) -> Bool { return lhs.value == rhs.value }
mit
0c083c2b25f0531a49d62724d9ca2e46
35.483221
126
0.714864
3.61196
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookShare/Sources/Share/Views/LikeControl.swift
13
5405
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright notice shall be // included in all copies or substantial portions of the software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation import UIKit import FBSDKShareKit /** UI control to like an object in the Facebook graph. Taps on the like button within this control will invoke an API call to the Facebook app through a fast-app-switch that allows the user to like the object. Upon return to the calling app, the view will update with the new state. */ public class LikeControl: UIView { fileprivate let sdkLikeControl: FBSDKLikeControl /** Create a new LikeControl with an optional frame and object. - parameter frame: The frame to use for this control. If `nil`, defaults to a default size. - parameter object: The object to like. */ public init(frame: CGRect? = nil, object: LikableObject) { let sdkLikeControl = FBSDKLikeControl() let frame = frame ?? sdkLikeControl.bounds self.sdkLikeControl = sdkLikeControl super.init(frame: frame) self.object = object addSubview(sdkLikeControl) } /** Create a new LikeControl from an encoded interface file. - parameter coder: The coder to initialize from. */ public required init?(coder: NSCoder) { sdkLikeControl = FBSDKLikeControl() super.init(coder: coder) self.addSubview(sdkLikeControl) } /// The foreground color to use for the content of the control. public var foregroundColor: UIColor { get { return sdkLikeControl.foregroundColor } set { sdkLikeControl.foregroundColor = newValue } } /// The object to like. public var object: LikableObject { get { return LikableObject(sdkObjectType: sdkLikeControl.objectType, sdkObjectId: sdkLikeControl.objectID) } set { let sdkRepresentation = newValue.sdkObjectRepresntation sdkLikeControl.objectType = sdkRepresentation.objectType sdkLikeControl.objectID = sdkRepresentation.objectId } } /// The style to use for this control. public var auxilaryStyle: AuxilaryStyle { get { return AuxilaryStyle( sdkStyle: sdkLikeControl.likeControlStyle, sdkHorizontalAlignment: sdkLikeControl.likeControlHorizontalAlignment, sdkAuxilaryPosition: sdkLikeControl.likeControlAuxiliaryPosition ) } set { ( sdkLikeControl.likeControlStyle, sdkLikeControl.likeControlHorizontalAlignment, sdkLikeControl.likeControlAuxiliaryPosition ) = newValue.sdkStyleRepresentation } } /** The preferred maximum width (in points) for autolayout. This property affects the size of the receiver when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text is flowed to one or more new lines, thereby increasing the height of the receiver. */ public var preferredMaxLayoutWidth: CGFloat { get { return sdkLikeControl.preferredMaxLayoutWidth } set { sdkLikeControl.preferredMaxLayoutWidth = newValue } } /// If `true`, a sound is played when the control is toggled. public var isSoundEnabled: Bool { get { return sdkLikeControl.isSoundEnabled } set { sdkLikeControl.isSoundEnabled = newValue } } } extension LikeControl { /** Performs logic for laying out subviews. */ public override func layoutSubviews() { super.layoutSubviews() sdkLikeControl.frame = CGRect(origin: .zero, size: bounds.size) } /** Resizes and moves the receiver view so it just encloses its subviews. */ public override func sizeToFit() { bounds.size = sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)) } /** Asks the view to calculate and return the size that best fits the specified size. - parameter size: A new size that fits the receiver’s subviews. - returns: A new size that fits the receiver’s subviews. */ public override func sizeThatFits(_ size: CGSize) -> CGSize { return sdkLikeControl.sizeThatFits(size) } /** Returns the natural size for the receiving view, considering only properties of the view itself. - returns: A size indicating the natural size for the receiving view based on its intrinsic properties. */ public override var intrinsicContentSize: CGSize { return sdkLikeControl.intrinsicContentSize } }
mit
48ed1b6fadb45d5cbf1042939c289ee3
31.733333
119
0.727828
4.565511
false
false
false
false
algoaccess/SwiftValidator
Validator/RegexRule.swift
1
853
// // RegexRule.swift // Validator // // Created by Jeff Potter on 4/3/15. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation public class RegexRule : Rule { private var REGEX: String = "^(?=.*?[A-Z]).{8,}$" private var message : String public init(regex: String, message: String = "Invalid Regular Expression"){ self.REGEX = regex self.message = message } public func validate(value: String) -> Bool { let thisValue = value as NSString let newValue = thisValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let test = NSPredicate(format: "SELF MATCHES %@", self.REGEX) return test.evaluateWithObject(newValue) } public func errorMessage() -> String { return message } }
mit
03774f06605a23b703d06cd49fcf235a
24.848485
105
0.623681
4.513228
false
true
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/PowerupSystem.swift
1
7023
// // PowerupSystem.swift // OnGettingThere // // Created by Benzi on 20/07/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit import UIKit class PowerupSystem : System { override init(_ world:WorldMapper){ super.init(world) world.eventBus.subscribe(GameEvent.PowerupCollected, handler: self) } override func handleEvent(event:Int, _ data:AnyObject?) { if event == GameEvent.PowerupCollected { //collectPowerup(data as Entity) togglePowerup(data as! Entity) } } func collectPowerup(p:Entity) { let powerup = world.powerup.get(p) if powerup.powerupType == PowerupType.Freeze { // add a freeze component to all enemies for enemy in world.enemy.entities() { let enemyComponent = world.enemy.get(enemy) // only freeze active enemies if !enemyComponent.enabled { continue } // monsters cannot be frozen if enemyComponent.enemyType == EnemyType.Monster { continue } let enemyAlreadyFrozen = world.freeze.belongsTo(enemy) switch powerup.duration { case let PowerupDuration.TurnBased(turns): if turns == 0 { // a turns=0 specifies this is a swtich off powerup // add to enemy only if already frozen otherwise ignore // as add this to an enemy will have no effect if enemyAlreadyFrozen { world.manager.addComponent(enemy, c: FreezeComponent(duration: powerup.duration)) } } else { // we need to update if enemy already has, else add the component world.manager.addComponent(enemy, c: FreezeComponent(duration: powerup.duration)) if !enemyAlreadyFrozen { // we raise an event only if this is the first time an enemy is being // frozen world.eventBus.raise(GameEvent.EnemyFrozen, data: enemy) } } case PowerupDuration.Infinite: world.manager.addComponent(enemy, c: FreezeComponent(duration: powerup.duration)) if !enemyAlreadyFrozen { world.eventBus.raise(GameEvent.EnemyFrozen, data: enemy) } } } } else if powerup.powerupType == PowerupType.Slide { // add a slide component to the player // if the slide powerup is of turns 0 (off switch, and player already has a // slide component, remove it. else add switch powerup.duration { case let PowerupDuration.TurnBased(turns): if turns == 0 { if world.slide.belongsTo(world.mainPlayer) { world.eventBus.raise(GameEvent.SlideCompleted, data: world.mainPlayer) world.eventBus.raise(GameEvent.SlideDeactivated, data: world.mainPlayer) world.manager.removeComponent(world.mainPlayer, c: world.slide.get(world.mainPlayer)) } } else { world.manager.addComponent(world.mainPlayer, c: SlideComponent(duration: powerup.duration)) world.eventBus.raise(GameEvent.SlideActivated, data: world.mainPlayer) } case PowerupDuration.Infinite: world.manager.addComponent(world.mainPlayer, c: SlideComponent(duration: powerup.duration)) world.eventBus.raise(GameEvent.SlideActivated, data: world.mainPlayer) } } } } extension PowerupSystem { // MARK: toggle mode for powerups func togglePowerup(p:Entity) { let powerup = world.powerup.get(p) switch powerup.powerupType { case .Freeze: toggleFreeze() case .Slide: toggleSlide() } } func toggleSlide() { if world.slide.belongsTo(world.mainPlayer) { removeItemFromPlayer("helmet") world.eventBus.raise(GameEvent.SlideDeactivated, data: world.mainPlayer) world.manager.removeComponent(world.mainPlayer, c: world.slide.get(world.mainPlayer)) } else { attachItemToPlayer("helmet", texture: "player_helmet") world.manager.addComponent(world.mainPlayer, c: SlideComponent(duration: PowerupDuration.Infinite)) world.eventBus.raise(GameEvent.SlideActivated, data: world.mainPlayer) } } func toggleFreeze() { // are enabled enemies frozen? for e in world.enemy.entities() { let enemy = world.enemy.get(e) // only freeze active enemies if !enemy.enabled { continue } // monsters cannot be frozen if enemy.enemyType == EnemyType.Monster { continue } if world.freeze.belongsTo(e) { world.eventBus.raise(GameEvent.EnemyUnfrozen, data: e) world.manager.removeComponent(e, c: world.freeze.get(e)) } else { world.manager.addComponent(e, c: FreezeComponent(duration: PowerupDuration.Infinite)) world.eventBus.raise(GameEvent.EnemyFrozen, data: e) } } } func attachItemToPlayer(name:String, texture:String) { let item = entitySprite(texture) item.alpha = 0.0 item.position = CGPointMake(0,0.5*world.gs.sideLength) item.size = world.gs.getSize(FactoredSizes.ScalingFactor.Player).scale(1.1) item.name = name item.runAction( // move in from top to player's head SKAction.moveTo(CGPointZero, duration: 0.3) .alongside(SKAction.fadeInWithDuration(0.3)) ) let sprite = world.sprite.get(world.mainPlayer) sprite.node.addChild(item) } func removeItemFromPlayer(name:String) { // remove the hat let sprite = world.sprite.get(world.mainPlayer) let item = sprite.node.childNodeWithName(name)! item.runAction( // 1. wait SKAction.waitForDuration(0.3) // 2. then fade out and move hat up .followedBy( SKAction.fadeOutWithDuration(0.3) .alongside(SKAction.moveTo(CGPointMake(0,0.5*world.gs.sideLength), duration:0.3)) ) // 3. then remove hat .followedBy(SKAction.removeFromParent()) ) } }
isc
e7592f199e9e0f0278d523759d7ac461
37.80663
111
0.551189
4.866944
false
false
false
false
cxy921126/SoftSwift
SoftSwift/SoftSwift/StatusRefreshControl.swift
1
1974
// // StatusRefreshControl.swift // SoftSwift // // Created by Mac mini on 16/3/28. // Copyright © 2016年 XMU. All rights reserved. // import UIKit class StatusRefreshControl: UIRefreshControl { @IBOutlet weak var rotateImage: UIImageView! @IBOutlet weak var arrowImage: UIImageView! @IBOutlet weak var hintLabel: UILabel! @IBOutlet weak var arrowView: UIView! override func awakeFromNib() { //添加对frame的监视器 addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) } deinit{ removeObserver(self, forKeyPath: "frame") } ///圆圈旋转标识 var isRotate = false //MARK: - 重写kvo方法 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if keyPath == "frame" { let pullY = object?.frame.origin.y if (pullY == -64 || pullY == 0.0) { arrowView.hidden = false return } if pullY == -60{ //isUP = false arrowView.hidden = true if !isRotate{ isRotate = true rotateAnimate() //swift的延时,时长为Int64(3*Double(NSEC_PER_SEC)) //let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(1*Double(NSEC_PER_SEC))) //dispatch_after(delay, dispatch_get_main_queue(), { //}) } } } } //MARK: - 动画 func rotateAnimate(){ let animate = CABasicAnimation(keyPath: "transform.rotation") animate.toValue = 2 * M_PI animate.duration = 1 animate.repeatCount = MAXFLOAT animate.cumulative = true rotateImage.layer.addAnimation(animate, forKey: nil) } }
mit
f429b5dc0f2623ac3ec0195acf0c91ec
29.015625
157
0.553358
4.552133
false
false
false
false
emrecaliskan/ECDropDownList
ECDropDownList/ECListItem.swift
1
602
// // ECListItem.swift // ECDropDownList // // Created by Emre Caliskan on 2015-03-23. // Copyright (c) 2015 pictago. All rights reserved. // import Foundation import UIKit func ==(lhs: ECListItem, rhs: ECListItem) -> Bool { return lhs.text == rhs.text } class ECListItem : NSObject { var text:String = "" var backgroundColor:UIColor = UIColor.whiteColor() var action:(() -> ())? var isSelected = false override init() { super.init() } init(text:String, action:(() -> ())) { self.text = text self.action = action } }
mit
729a74ff78ffad109926f1b8416c1a85
17.8125
54
0.586379
3.626506
false
false
false
false
YinSiQian/SQAutoScrollView
SQAutoScrollView/Demo/OneViewController.swift
1
2019
// // OneViewController.swift // SQAutoScrollView // // Created by ysq on 2017/10/17. // Copyright © 2017年 ysq. All rights reserved. // import UIKit class OneViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // Do any additional setup after loading the view. loadCycleView() } fileprivate func loadCycleView() { let urls = ["http://pic.qyer.com/public/mobileapp/homebanner/2017/10/09/15075430688640/w800", "http://pic.qyer.com/ra/img/15064476767054", "http://pic.qyer.com/public/mobileapp/homebanner/2017/10/09/15075432049166/w800", "http://pic.qyer.com/public/mobileapp/homebanner/2017/10/10/15076301267252/w800" ] let cycleView = SQAutoScrollView(frame: CGRect.init(x: 0, y: 100, width: view.frame.size.width, height: 300)) cycleView.clickCompletionHandler = { (view: SQAutoScrollView, index: Int) in print("view--->\(view), index-->\(index)") } cycleView.imageUrls = urls cycleView.interval = 1 cycleView.pageControl?.alignment = .right cycleView.pageControl?.style = .rectangle cycleView.pageControl?.currentPageIndicatorTintColor = UIColor.blue cycleView.pageControl?.pageIndicatorTintColor = UIColor.red view.addSubview(cycleView) } 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. } */ }
mit
d0ff1126554a0961733cece69a28a9bf
32.6
117
0.639385
4.373102
false
false
false
false
brokenhandsio/SteamPress
Sources/SteamPress/Views/PaginatorTag.swift
1
6274
import TemplateKit public final class PaginatorTag: TagRenderer { public enum Error: Swift.Error { case expectedPaginationInformation } let paginationLabel: String? public init(paginationLabel: String? = nil) { self.paginationLabel = paginationLabel } public static let name = "paginator" public func render(tag: TagContext) throws -> EventLoopFuture<TemplateData> { try tag.requireNoBody() guard let paginationInformaton = tag.context.data.dictionary?["paginationTagInformation"] else { throw Error.expectedPaginationInformation } guard let currentPage = paginationInformaton.dictionary?["currentPage"]?.int, let totalPages = paginationInformaton.dictionary?["totalPages"]?.int else { throw Error.expectedPaginationInformation } let currentQuery = paginationInformaton.dictionary?["currentQuery"]?.string let previousPage: String? let nextPage: String? if currentPage == 1 { previousPage = nil } else { let previousPageNumber = currentPage - 1 previousPage = buildButtonLink(currentQuery: currentQuery, pageNumber: previousPageNumber) } if currentPage == totalPages { nextPage = nil } else { let nextPageNumber = currentPage + 1 nextPage = buildButtonLink(currentQuery: currentQuery, pageNumber: nextPageNumber) } let data = buildNavigation(currentPage: currentPage, totalPages: totalPages, previousPage: previousPage, nextPage: nextPage, currentQuery: currentQuery) return tag.eventLoop.future(data) } } extension PaginatorTag { func buildButtonLink(currentQuery: String?, pageNumber: Int) -> String { var urlComponents = URLComponents() if currentQuery == nil { urlComponents.queryItems = [] } else { urlComponents.query = currentQuery } if (urlComponents.queryItems?.contains { $0.name == "page" }) ?? false { urlComponents.queryItems?.removeAll { $0.name == "page" } } let pageQuery = URLQueryItem(name: "page", value: "\(pageNumber)") urlComponents.queryItems?.append(pageQuery) return "?\(urlComponents.query ?? "")" } func buildBackButton(url: String?) -> String { guard let url = url else { return buildLink(title: "«", active: false, link: nil, disabled: true) } return buildLink(title: "«", active: false, link: url, disabled: false) } func buildForwardButton(url: String?) -> String { guard let url = url else { return buildLink(title: "»", active: false, link: nil, disabled: true) } return buildLink(title: "»", active: false, link: url, disabled: false) } func buildLinks(currentPage: Int, count: Int, currentQuery: String?) -> String { var links = "" if count == 0 { return links } for i in 1...count { if i == currentPage { links += buildLink(title: "\(i)", active: true, link: nil, disabled: false) } else { let link = buildButtonLink(currentQuery: currentQuery, pageNumber: i) links += buildLink(title: "\(i)", active: false, link: link, disabled: false) } } return links } func buildNavigation(currentPage: Int, totalPages: Int, previousPage: String?, nextPage: String?, currentQuery: String?) -> TemplateData { var result = "" let navClass = "paginator" let ulClass = "pagination justify-content-center" var header = "<nav class=\"\(navClass)\"" if let ariaLabel = paginationLabel { header += " aria-label=\"\(ariaLabel)\"" } header += ">\n<ul class=\"\(ulClass)\">\n" let footer = "</ul>\n</nav>" result += header result += buildBackButton(url: previousPage) result += buildLinks(currentPage: currentPage, count: totalPages, currentQuery: currentQuery) result += buildForwardButton(url: nextPage) result += footer return TemplateData.string(result) } func buildLink(title: String, active: Bool, link: String?, disabled: Bool) -> String { let activeSpan = "<span class=\"sr-only\">(current)</span>" let linkClass = "page-link" let liClass = "page-item" var linkString = "<li" if active || disabled { linkString += " class=\"" if active { linkString += "active" } if disabled { linkString += "disabled" } if active || disabled { linkString += " " } linkString += "\(liClass)" linkString += "\"" } linkString += ">" if let link = link { linkString += "<a href=\"\(link)\" class=\"\(linkClass)\"" if title == "«" { linkString += " rel=\"prev\" aria-label=\"Previous\"><span aria-hidden=\"true\">«</span><span class=\"sr-only\">Previous</span>" } else if title == "»" { linkString += " rel=\"next\" aria-label=\"Next\"><span aria-hidden=\"true\">»</span><span class=\"sr-only\">Next</span>" } else { linkString += ">\(title)" } linkString += "</a>" } else { linkString += "<span class=\"\(linkClass)\"" if title == "«" { linkString += " aria-label=\"Previous\" aria-hidden=\"true\">«</span><span class=\"sr-only\">Previous</span>" } else if title == "»" { linkString += " aria-label=\"Next\" aria-hidden=\"true\">»</span><span class=\"sr-only\">Next</span>" } else { linkString += ">\(title)</span>" if active { linkString += activeSpan } } } linkString += "</li>\n" return linkString } }
mit
92c53616bda82f7ed6c420e200478245
31.614583
160
0.546311
4.718915
false
false
false
false
abelsanchezali/ViewBuilder
Source/Layout/View/UIView+PanelLayoutProtocol.swift
1
1550
// // UIView+PanelLayoutProtocol.swift // ViewBuilder // // Created by Abel Sanchez on 8/9/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit extension UIView: PanelLayoutProtocol { private static let PanelLayoutProtocolMeasuredSizeParameterName = "PanelLayoutProtocolMeasuredSizeParameterName" public var measuredSize: CGSize { get { guard let value = getAttachedParameter(UIView.PanelLayoutProtocolMeasuredSizeParameterName) as? NSValue else { return CGSize.zero } return value.cgSizeValue } set { setAttachedParameter(UIView.PanelLayoutProtocolMeasuredSizeParameterName, value: newValue.convertToNSValue()) } } public func measureOverride(_ size: CGSize) -> CGSize { if translatesAutoresizingMaskIntoConstraints { return sizeThatFits(size) } else { return systemLayoutSizeFitting(size) } } public func subviewMeasureChanged(_ subview: UIView) { } public func invalidateMeasure() { superview?.subviewMeasureChanged(self) } public func arrangeToRect(_ rect: CGRect) { // TODO: Add RTL support here // EYE: Don't do this way //frame = rect let anchor = layer.anchorPoint bounds = CGRect(origin: bounds.origin, size: rect.size) center = CGPoint(x: rect.origin.x + rect.size.width * anchor.x, y: rect.origin.y + rect.size.height * anchor.y) } }
mit
2d8111aa76311f7e19e19d3f41048831
28.788462
122
0.64235
4.722561
false
false
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Profile Settings/ProfileSettingsSettings.swift
1
5588
// // ProfileSettingsSettings.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Foundation import ProfilePayloads extension ProfileSettings { // MARK: - // MARK: - Count func settingsCount(forDomainIdentifier domainIdentifier: String, type: PayloadType) -> Int { self.settings(forDomainIdentifier: domainIdentifier, type: type)?.count ?? 0 } func settingsEmptyCount(forDomainIdentifier domainIdentifier: String, type: PayloadType) -> Int { var emptyCount = 0 let domainSettingsArray = self.settings(forDomainIdentifier: domainIdentifier, type: type) ?? [[String: Any]]() if domainSettingsArray.isEmpty { return 1 } else { for domainSettings in domainSettingsArray { if Array(Set(domainSettings.keys).subtracting([PayloadKey.payloadVersion, PayloadKey.payloadUUID])).isEmpty { emptyCount += 1 } } } return emptyCount } // MARK: - // MARK: Get func settings(forType type: PayloadType) -> [String: [[String: Any]]]? { self.settingsPayload[type.rawValue] } func settings(forPayload payload: Payload) -> [[String: Any]]? { self.settings(forDomainIdentifier: payload.domainIdentifier, type: payload.type) } func settings(forDomain domain: String, type: PayloadType, exact: Bool = false) -> [[[String: Any]]]? { guard let typeSettings = self.settings(forType: type) else { return nil } if exact { return Array(typeSettings.filter { $0.key == domain }.values) } else { return Array(typeSettings.filter { $0.key.hasPrefix(domain) }.values) } } func settings(forDomainIdentifier domainIdentifier: String, type: PayloadType) -> [[String: Any]]? { guard let typeSettings = self.settings(forType: type) else { return nil } return typeSettings[domainIdentifier] } func settings(forDomainIdentifier domainIdentifier: String, type: PayloadType, payloadIndex: Int) -> [String: Any]? { guard let domainSettings = self.settings(forDomainIdentifier: domainIdentifier, type: type), payloadIndex < domainSettings.count else { return nil } return domainSettings[payloadIndex] } // MARK: - // MARK: Set func setSettings(_ typeSettings: [String: [[String: Any]]], forType type: PayloadType) { self.settingsPayload[type.rawValue] = typeSettings } func setSettings(_ domainSettings: [[String: Any]], forPayload payload: Payload) { self.setSettings(domainSettings, forDomainIdentifier: payload.domainIdentifier, type: payload.type) } func setSettings(_ domainSettings: [[String: Any]], forDomainIdentifier domainIdentifier: String, type: PayloadType) { var typeSetting = self.settings(forType: type) ?? [String: [[String: Any]]]() typeSetting[domainIdentifier] = domainSettings self.setSettings(typeSetting, forType: type) } func setSettings(_ domainSetting: [String: Any], forDomainIdentifier domainIdentifier: String, type: PayloadType, payloadIndex: Int) { var domainSettings = self.settings(forDomainIdentifier: domainIdentifier, type: type) ?? [[String: Any]]() if payloadIndex < domainSettings.count { domainSettings[payloadIndex] = domainSetting } else { domainSettings.append(domainSetting) if domainSettings.count < payloadIndex { Log.shared.error(message: "Trying to set a domain setting at an out of bounds index: \(payloadIndex). Currently only: \(domainSettings.count) domain payload settings are available.", category: String(describing: self)) } } self.setSettings(domainSettings, forDomainIdentifier: domainIdentifier, type: type) } func setSettingsDefault(forPayload payload: Payload) { // DomainIdentifier domainIdentifier: String, type: PayloadType) { var domainSettings = [String: Any]() self.initializeDomainSetting(&domainSettings, forPayload: payload) self.setSettings(domainSettings, forDomainIdentifier: payload.domainIdentifier, type: payload.type, payloadIndex: self.settingsCount(forDomainIdentifier: payload.domainIdentifier, type: payload.type)) } func verifySettings(_ domainSettingsArray: inout [[String: Any]], forPayload payload: Payload) { if domainSettingsArray.isEmpty { var domainSettings = [String: Any]() self.initializeDomainSetting(&domainSettings, forPayload: payload) domainSettingsArray.append(domainSettings) } else { for index in domainSettingsArray.indices { var domainSettings = domainSettingsArray[index] self.initializeDomainSetting(&domainSettings, forPayload: payload) domainSettingsArray[index] = domainSettings } } } // MARK: - // MARK: Remove func removeSettings(forDomainIdentifier domainIdentifier: String, type: PayloadType, payloadIndex: Int) { guard var domainSettings = self.settings(forDomainIdentifier: domainIdentifier, type: type) else { return } if payloadIndex < domainSettings.count { domainSettings.remove(at: payloadIndex) } self.setSettings(domainSettings, forDomainIdentifier: domainIdentifier, type: type) } }
mit
38c284ce27251a9659e4227b080e82c3
41.648855
234
0.661715
4.71875
false
false
false
false
JasonChen2015/Paradise-Lost
Paradise Lost/Classes/Views/MarqueeLabel.swift
3
67346
// // MarqueeLabel.swift // // Created by Charles Powell on 8/6/14. // Copyright (c) 2015 Charles Powell. All rights reserved. // // code from https://github.com/cbpowell/MarqueeLabel-Swift/blob/master/Classes/MarqueeLabel.swift (under License MIT) import UIKit import QuartzCore open class MarqueeLabel: UILabel, CAAnimationDelegate { /** An enum that defines the types of `MarqueeLabel` scrolling - LeftRight: Scrolls left first, then back right to the original position. - RightLeft: Scrolls right first, then back left to the original position. - Continuous: Continuously scrolls left (with a pause at the original position if animationDelay is set). - ContinuousReverse: Continuously scrolls right (with a pause at the original position if animationDelay is set). */ public enum `Type` { case leftRight case rightLeft case continuous case continuousReverse } // // MARK: - Public properties // /** Defines the direction and method in which the `MarqueeLabel` instance scrolls. `MarqueeLabel` supports four types of scrolling: `MLLeftRight`, `MLRightLeft`, `MLContinuous`, and `MLContinuousReverse`. Given the nature of how text direction works, the options for the `marqueeType` property require specific text alignments and will set the textAlignment property accordingly. - `MLLeftRight` type is ONLY compatible with a label text alignment of `NSTextAlignmentLeft`. - `MLRightLeft` type is ONLY compatible with a label text alignment of `NSTextAlignmentRight`. - `MLContinuous` does not require a text alignment (it is effectively centered). - `MLContinuousReverse` does not require a text alignment (it is effectively centered). Defaults to `MLContinuous`. - SeeAlso: Type - SeeAlso: textAlignment */ open var type: Type = .continuous { didSet { if type == oldValue { return } updateAndScroll() } } /** Specifies the animation curve used in the scrolling motion of the labels. Allowable options: - `UIViewAnimationOptionCurveEaseInOut` - `UIViewAnimationOptionCurveEaseIn` - `UIViewAnimationOptionCurveEaseOut` - `UIViewAnimationOptionCurveLinear` Defaults to `UIViewAnimationOptionCurveEaseInOut`. */ open var animationCurve: UIViewAnimationCurve = .linear /** A boolean property that sets whether the `MarqueeLabel` should behave like a normal `UILabel`. When set to `true` the `MarqueeLabel` will behave and look like a normal `UILabel`, and will not begin any scrolling animations. Changes to this property take effect immediately, removing any in-flight animation as well as any edge fade. Note that `MarqueeLabel` will respect the current values of the `lineBreakMode` and `textAlignment`properties while labelized. To simply prevent automatic scrolling, use the `holdScrolling` property. Defaults to `false`. - SeeAlso: holdScrolling - SeeAlso: lineBreakMode @warning The label will not automatically scroll when this property is set to `YES`. @warning The UILabel default setting for the `lineBreakMode` property is `NSLineBreakByTruncatingTail`, which truncates the text adds an ellipsis glyph (...). Set the `lineBreakMode` property to `NSLineBreakByClipping` in order to avoid the ellipsis, especially if using an edge transparency fade. */ @IBInspectable open var labelize: Bool = false { didSet { if labelize != oldValue { updateAndScroll() } } } /** A boolean property that sets whether the `MarqueeLabel` should hold (prevent) automatic label scrolling. When set to `true`, `MarqueeLabel` will not automatically scroll even its text is larger than the specified frame, although the specified edge fades will remain. To set `MarqueeLabel` to act like a normal UILabel, use the `labelize` property. Defaults to `false`. - SeeAlso: labelize @warning The label will not automatically scroll when this property is set to `YES`. */ @IBInspectable open var holdScrolling: Bool = false { didSet { if holdScrolling != oldValue { if oldValue == true && !(awayFromHome || labelize || tapToScroll ) && labelShouldScroll() { beginScroll() } } } } /** A boolean property that sets whether the `MarqueeLabel` should only begin a scroll when tapped. If this property is set to `true`, the `MarqueeLabel` will only begin a scroll animation cycle when tapped. The label will not automatically being a scroll. This setting overrides the setting of the `holdScrolling` property. Defaults to `false`. @warning The label will not automatically scroll when this property is set to `false`. - SeeAlso: holdScrolling */ @IBInspectable open var tapToScroll: Bool = false { didSet { if tapToScroll != oldValue { if tapToScroll { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MarqueeLabel.labelWasTapped(_:))) self.addGestureRecognizer(tapRecognizer) isUserInteractionEnabled = true } else { if let recognizer = self.gestureRecognizers!.first as UIGestureRecognizer? { self.removeGestureRecognizer(recognizer) } isUserInteractionEnabled = false } } } } /** A read-only boolean property that indicates if the label's scroll animation has been paused. - SeeAlso: pauseLabel - SeeAlso: unpauseLabel */ open var isPaused: Bool { return (sublabel.layer.speed == 0.0) } /** A boolean property that indicates if the label is currently away from the home location. The "home" location is the traditional location of `UILabel` text. This property essentially reflects if a scroll animation is underway. */ open var awayFromHome: Bool { if let presentationLayer = sublabel.layer.presentation() { return !(presentationLayer.position.x == homeLabelFrame.origin.x) } return false } /** The `MarqueeLabel` scrolling speed may be defined by one of two ways: - Rate(CGFloat): The speed is defined by a rate of motion, in units of points per second. - Duration(CGFloat): The speed is defined by the time to complete a scrolling animation cycle, in units of seconds. Each case takes an associated `CGFloat` value, which is the rate/duration desired. */ public enum SpeedLimit { case rate(CGFloat) case duration(CGFloat) var value: CGFloat { switch self { case .rate(let rate): return rate case .duration(let duration): return duration } } } /** Defines the speed of the `MarqueeLabel` scrolling animation. The speed is set by specifying a case of the `SpeedLimit` enum along with an associated value. - SeeAlso: SpeedLimit */ open var speed: SpeedLimit = .duration(7.0) { didSet { switch (speed, oldValue) { case (.rate(let a), .rate(let b)) where a == b: return case (.duration(let a), .duration(let b)) where a == b: return default: updateAndScroll() } } } // @available attribute seems to cause SourceKit to crash right now // @available(*, deprecated = 2.6, message = "Use speed property instead") open var scrollDuration: CGFloat? { get { switch speed { case .duration(let duration): return duration case .rate(_): return nil } } set { if let duration = newValue { speed = .duration(duration) } } } // @available attribute seems to cause SourceKit to crash right now // @available(*, deprecated = 2.6, message = "Use speed property instead") open var scrollRate: CGFloat? { get { switch speed { case .duration(_): return nil case .rate(let rate): return rate } } set { if let rate = newValue { speed = .rate(rate) } } } /** A buffer (offset) between the leading edge of the label text and the label frame. This property adds additional space between the leading edge of the label text and the label frame. The leading edge is the edge of the label text facing the direction of scroll (i.e. the edge that animates offscreen first during scrolling). Defaults to `0`. - Note: The value set to this property affects label positioning at all times (including when `labelize` is set to `true`), including when the text string length is short enough that the label does not need to scroll. - Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength` is used as spacing between the two label instances. Zero is an allowable value for all three properties. - SeeAlso: trailingBuffer */ @IBInspectable open var leadingBuffer: CGFloat = 0.0 { didSet { if leadingBuffer != oldValue { updateAndScroll() } } } /** A buffer (offset) between the trailing edge of the label text and the label frame. This property adds additional space (buffer) between the trailing edge of the label text and the label frame. The trailing edge is the edge of the label text facing away from the direction of scroll (i.e. the edge that animates offscreen last during scrolling). Defaults to `0`. - Note: The value set to this property has no effect when the `labelize` property is set to `true`. - Note: For Continuous-type labels, the smallest value of `leadingBuffer`, `trailingBuffer`, and `fadeLength` is used as spacing between the two label instances. Zero is an allowable value for all three properties. - SeeAlso: leadingBuffer */ @IBInspectable open var trailingBuffer: CGFloat = 0.0 { didSet { if trailingBuffer != oldValue { updateAndScroll() } } } /** The length of transparency fade at the left and right edges of the frame. This propery sets the size (in points) of the view edge transparency fades on the left and right edges of a `MarqueeLabel`. The transparency fades from an alpha of 1.0 (fully visible) to 0.0 (fully transparent) over this distance. Values set to this property will be sanitized to prevent a fade length greater than 1/2 of the frame width. Defaults to `0`. */ @IBInspectable open var fadeLength: CGFloat = 0.0 { didSet { if fadeLength != oldValue { applyGradientMask(fadeLength, animated: true) updateAndScroll() } } } /** The length of delay in seconds that the label pauses at the completion of a scroll. */ @IBInspectable open var animationDelay: CGFloat = 1.0 // // MARK: - Class Functions and Helpers // /** Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. - Parameter controller: The view controller for which to restart all `MarqueeLabel` instances. - Warning: View controllers that appear with animation (such as from underneath a modal-style controller) can cause some `MarqueeLabel` text position "jumping" when this method is used in `viewDidAppear` if scroll animations are already underway. Use this method inside `viewWillAppear:` instead to avoid this problem. - Warning: This method may not function properly if passed the parent view controller when using view controller containment. - SeeAlso: restartLabel - SeeAlso: controllerViewDidAppear: - SeeAlso: controllerViewWillAppear: */ class func restartLabelsOfController(_ controller: UIViewController) { MarqueeLabel.notifyController(controller, message: .Restart) } /** Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements. - Parameter controller: The view controller that will appear. - SeeAlso: restartLabel - SeeAlso: controllerViewDidAppear */ class func controllerViewWillAppear(_ controller: UIViewController) { MarqueeLabel.restartLabelsOfController(controller) } /** Convenience method to restart all `MarqueeLabel` instances that have the specified view controller in their next responder chain. Alternative to `restartLabelsOfController`. This method is retained for backwards compatibility and future enhancements. - Parameter controller: The view controller that did appear. - SeeAlso: restartLabel - SeeAlso: controllerViewWillAppear */ class func controllerViewDidAppear(_ controller: UIViewController) { MarqueeLabel.restartLabelsOfController(controller) } /** Labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain. The `labelize` property of all recognized `MarqueeLabel` instances will be set to `true`. - Parameter controller: The view controller for which all `MarqueeLabel` instances should be labelized. - SeeAlso: labelize */ class func controllerLabelsLabelize(_ controller: UIViewController) { MarqueeLabel.notifyController(controller, message: .Labelize) } /** De-labelizes all `MarqueeLabel` instances that have the specified view controller in their next responder chain. The `labelize` property of all recognized `MarqueeLabel` instances will be set to `false`. - Parameter controller: The view controller for which all `MarqueeLabel` instances should be de-labelized. - SeeAlso: labelize */ class func controllerLabelsAnimate(_ controller: UIViewController) { MarqueeLabel.notifyController(controller, message: .Animate) } // // MARK: - Initialization // /** Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length. - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. - Parameter pixelsPerSec: A rate of scroll for the label scroll animation. Must be non-zero. Note that this will be the peak (mid-transition) rate for ease-type animation. - Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame. - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. - SeeAlso: fadeLength */ init(frame: CGRect, rate: CGFloat, fadeLength fade: CGFloat) { speed = .rate(rate) fadeLength = CGFloat(min(fade, frame.size.width/2.0)) super.init(frame: frame) setup() } /** Returns a newly initialized `MarqueeLabel` instance with the specified scroll rate and edge transparency fade length. - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. - Parameter scrollDuration: A scroll duration the label scroll animation. Must be non-zero. This will be the duration that the animation takes for one-half of the scroll cycle in the case of left-right and right-left marquee types, and for one loop of a continuous marquee type. - Parameter fadeLength: A length of transparency fade at the left and right edges of the `MarqueeLabel` instance's frame. - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. - SeeAlso: fadeLength */ init(frame: CGRect, duration: CGFloat, fadeLength fade: CGFloat) { speed = .duration(duration) fadeLength = CGFloat(min(fade, frame.size.width/2.0)) super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } /** Returns a newly initialized `MarqueeLabel` instance. The default scroll duration of 7.0 seconds and fade length of 0.0 are used. - Parameter frame: A rectangle specifying the initial location and size of the view in its superview's coordinates. Text (for the given font, font size, etc.) that does not fit in this frame will automatically scroll. - Returns: An initialized `MarqueeLabel` object or nil if the object couldn't be created. */ convenience public override init(frame: CGRect) { self.init(frame: frame, duration:7.0, fadeLength:0.0) } fileprivate func setup() { // Create sublabel sublabel = UILabel(frame: self.bounds) sublabel.tag = 700 sublabel.layer.anchorPoint = CGPoint.zero // Add sublabel addSubview(sublabel) // Configure self super.clipsToBounds = true super.numberOfLines = 1 // Add notification observers // Custom class notifications NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartForViewController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Restart.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.labelizeForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Labelize.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.animateForController(_:)), name: NSNotification.Name(rawValue: MarqueeKeys.Animate.rawValue), object: nil) // UIApplication state notifications NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.restartLabel), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MarqueeLabel.shutdownLabel), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) } override open func awakeFromNib() { super.awakeFromNib() forwardPropertiesToSublabel() } fileprivate func forwardPropertiesToSublabel() { /* Note that this method is currently ONLY called from awakeFromNib, i.e. when text properties are set via a Storyboard. As the Storyboard/IB doesn't currently support attributed strings, there's no need to "forward" the super attributedString value. */ // Since we're a UILabel, we actually do implement all of UILabel's properties. // We don't care about these values, we just want to forward them on to our sublabel. let properties = ["baselineAdjustment", "enabled", "highlighted", "highlightedTextColor", "minimumFontSize", "shadowOffset", "textAlignment", "userInteractionEnabled", "adjustsFontSizeToFitWidth", "lineBreakMode", "numberOfLines"] // Iterate through properties sublabel.text = super.text sublabel.font = super.font sublabel.textColor = super.textColor sublabel.backgroundColor = super.backgroundColor ?? UIColor.clear sublabel.shadowColor = super.shadowColor sublabel.shadowOffset = super.shadowOffset for prop in properties { let value: AnyObject! = super.value(forKey: prop) as AnyObject sublabel.setValue(value, forKeyPath: prop) } } // // MARK: - MarqueeLabel Heavy Lifting // override open func layoutSubviews() { super.layoutSubviews() updateAndScroll(true) } override open func willMove(toWindow newWindow: UIWindow?) { if newWindow == nil { shutdownLabel() } } override open func didMoveToWindow() { if self.window == nil { shutdownLabel() } else { updateAndScroll() } } fileprivate func updateAndScroll() { updateAndScroll(true) } fileprivate func updateAndScroll(_ shouldBeginScroll: Bool) { // Check if scrolling can occur if !labelReadyForScroll() { return } // Calculate expected size let expectedLabelSize = sublabelSize() // Invalidate intrinsic size invalidateIntrinsicContentSize() // Move label to home returnLabelToHome() // Check if label should scroll // Note that the holdScrolling propery does not affect this if !labelShouldScroll() { // Set text alignment and break mode to act like a normal label sublabel.textAlignment = super.textAlignment sublabel.lineBreakMode = super.lineBreakMode var labelFrame = CGRect.zero switch type { case .continuousReverse, .rightLeft: (_, labelFrame) = bounds.divided(atDistance: leadingBuffer, from: .maxXEdge) labelFrame = labelFrame.integral default: labelFrame = CGRect(x: leadingBuffer, y: 0.0, width: bounds.size.width - leadingBuffer, height: bounds.size.height).integral } homeLabelFrame = labelFrame awayOffset = 0.0 // Remove an additional sublabels (for continuous types) repliLayer.instanceCount = 1; // Set the sublabel frame to calculated labelFrame sublabel.frame = labelFrame // Configure fade applyGradientMask(fadeLength, animated: !labelize) return } // Label DOES need to scroll // Spacing between primary and second sublabel must be at least equal to leadingBuffer, and at least equal to the fadeLength let minTrailing = max(max(leadingBuffer, trailingBuffer), fadeLength) switch type { case .continuous, .continuousReverse: if (type == .continuous) { homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = -(homeLabelFrame.size.width + minTrailing) } else { // .ContinuousReverse homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = (homeLabelFrame.size.width + minTrailing) } // Set frame and text sublabel.frame = homeLabelFrame // Configure replication repliLayer.instanceCount = 2 repliLayer.instanceTransform = CATransform3DMakeTranslation(-awayOffset, 0.0, 0.0) case .rightLeft: homeLabelFrame = CGRect(x: bounds.size.width - (expectedLabelSize.width + leadingBuffer), y: 0.0, width: expectedLabelSize.width, height: bounds.size.height).integral awayOffset = (expectedLabelSize.width + trailingBuffer + leadingBuffer) - bounds.size.width // Set frame and text sublabel.frame = homeLabelFrame // Remove any replication repliLayer.instanceCount = 1 // Enforce text alignment for this type sublabel.textAlignment = NSTextAlignment.right case .leftRight: homeLabelFrame = CGRect(x: leadingBuffer, y: 0.0, width: expectedLabelSize.width, height: expectedLabelSize.height).integral awayOffset = bounds.size.width - (expectedLabelSize.width + leadingBuffer + trailingBuffer) // Set frame and text sublabel.frame = homeLabelFrame // Remove any replication self.repliLayer.instanceCount = 1 // Enforce text alignment for this type sublabel.textAlignment = NSTextAlignment.left // Default case not required } // Recompute the animation duration animationDuration = { switch self.speed { case .rate(let rate): return CGFloat(fabs(self.awayOffset) / rate) case .duration(let duration): return duration } }() // Configure gradient for current condition applyGradientMask(fadeLength, animated: !self.labelize) if !tapToScroll && !holdScrolling && shouldBeginScroll { beginScroll() } } func sublabelSize() -> CGSize { // Bound the expected size let maximumLabelSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) // Calculate the expected size var expectedLabelSize = sublabel.sizeThatFits(maximumLabelSize) // Sanitize width to 5461.0 (largest width a UILabel will draw on an iPhone 6S Plus) expectedLabelSize.width = min(expectedLabelSize.width, 5461.0) // Adjust to own height (make text baseline match normal label) expectedLabelSize.height = bounds.size.height return expectedLabelSize } override open func sizeThatFits(_ size: CGSize) -> CGSize { var fitSize = sublabel.sizeThatFits(size) fitSize.width += leadingBuffer return fitSize } // // MARK: - Animation Handling // fileprivate func labelShouldScroll() -> Bool { // Check for nil string if sublabel.text == nil { return false } // Check for empty string if sublabel.text!.isEmpty { return false } // Check if the label string fits let labelTooLarge = (sublabelSize().width + leadingBuffer) > self.bounds.size.width let animationHasDuration = speed.value > 0.0 return (!labelize && labelTooLarge && animationHasDuration) } fileprivate func labelReadyForScroll() -> Bool { // Check if we have a superview if superview == nil { return false } // Check if we are attached to a window if window == nil { return false } // Check if our view controller is ready let viewController = firstAvailableViewController() if viewController != nil { if !viewController!.isViewLoaded { return false } } return true } fileprivate func beginScroll() { beginScroll(true) } fileprivate func beginScroll(_ delay: Bool) { switch self.type { case .leftRight, .rightLeft: scrollAway(animationDuration, delay: animationDelay) default: scrollContinuous(animationDuration, delay: animationDelay) } } fileprivate func returnLabelToHome() { // Remove any gradient animation maskLayer?.removeAllAnimations() // Remove all sublabel position animations sublabel.layer.removeAllAnimations() } // Define animation completion closure type fileprivate typealias MLAnimationCompletion = (_ finished: Bool) -> () fileprivate func scroll(_ interval: CGFloat, delay: CGFloat = 0.0, scroller: Scroller, fader: CAKeyframeAnimation?) { var scroller = scroller // Check for conditions which would prevent scrolling if !labelReadyForScroll() { return } // Call pre-animation hook labelWillBeginScroll() // Start animation transactions CATransaction.begin() let transDuration = transactionDurationType(type, interval: interval, delay: delay) CATransaction.setAnimationDuration(transDuration) // Create gradient animation, if needed let gradientAnimation: CAKeyframeAnimation? if fadeLength > 0.0 { // Remove any setup animation, but apply final values if let setupAnim = maskLayer?.animation(forKey: "setupFade") as? CABasicAnimation, let finalColors = setupAnim.toValue as? [CGColor] { maskLayer?.colors = finalColors } maskLayer?.removeAnimation(forKey: "setupFade") // Generate animation if needed if let previousAnimation = fader { gradientAnimation = previousAnimation } else { gradientAnimation = keyFrameAnimationForGradient(fadeLength, interval: interval, delay: delay) } // Apply scrolling animation maskLayer?.add(gradientAnimation!, forKey: "gradient") } else { // No animation needed gradientAnimation = nil } let completion = CompletionBlock<MLAnimationCompletion>({ (finished: Bool) -> () in guard finished else { // Do not continue into the next loop return } // Call returned home function self.labelReturnedToHome(true) // Check to ensure that: // 1) We don't double fire if an animation already exists // 2) The instance is still attached to a window - this completion block is called for // many reasons, including if the animation is removed due to the view being removed // from the UIWindow (typically when the view controller is no longer the "top" view) guard self.window != nil else { return } guard self.sublabel.layer.animation(forKey: "position") == nil else { return } // Begin again, if conditions met if (self.labelShouldScroll() && !self.tapToScroll && !self.holdScrolling) { // Perform completion callback self.scroll(interval, delay: delay, scroller: scroller, fader: gradientAnimation) } }) // Call scroller let scrolls = scroller.generate(interval, delay: delay) // Perform all animations in scrolls for (index, scroll) in scrolls.enumerated() { let layer = scroll.layer let anim = scroll.anim // Add callback to single animation if index == 0 { anim.setValue(completion as AnyObject, forKey: MarqueeKeys.CompletionClosure.rawValue) anim.delegate = self } // Add animation layer.add(anim, forKey: "position") } CATransaction.commit() } fileprivate func scrollAway(_ interval: CGFloat, delay: CGFloat = 0.0) { // Create scroller, which defines the animation to perform let homeOrigin = homeLabelFrame.origin let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset) let scroller = Scroller(generator: {(interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in // Create animation for position let values: [NSValue] = [ NSValue(cgPoint: homeOrigin), // Start at home NSValue(cgPoint: homeOrigin), // Stay at home for delay NSValue(cgPoint: awayOrigin), // Move to away NSValue(cgPoint: awayOrigin), // Stay at away for delay NSValue(cgPoint: homeOrigin) // Move back to home ] let layer = self.sublabel.layer let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay) return [(layer: layer, anim: anim)] }) // Scroll scroll(interval, delay: delay, scroller: scroller, fader: nil) } fileprivate func scrollContinuous(_ interval: CGFloat, delay: CGFloat) { // Create scroller, which defines the animation to perform let homeOrigin = homeLabelFrame.origin let awayOrigin = offsetCGPoint(homeLabelFrame.origin, offset: awayOffset) let scroller = Scroller(generator: { (interval: CGFloat, delay: CGFloat) -> [(layer: CALayer, anim: CAKeyframeAnimation)] in // Create animation for position let values: [NSValue] = [ NSValue(cgPoint: homeOrigin), // Start at home NSValue(cgPoint: homeOrigin), // Stay at home for delay NSValue(cgPoint: awayOrigin) // Move to away ] // Generate animation let layer = self.sublabel.layer let anim = self.keyFrameAnimationForProperty("position", values: values, interval: interval, delay: delay) return [(layer: layer, anim: anim)] }) // Scroll scroll(interval, delay: delay, scroller: scroller, fader: nil) } fileprivate func applyGradientMask(_ fadeLength: CGFloat, animated: Bool) { // Remove any in-flight animations maskLayer?.removeAllAnimations() // Check for zero-length fade if (fadeLength <= 0.0) { removeGradientMask() return } // Configure gradient mask without implicit animations CATransaction.begin() CATransaction.setDisableActions(true) // Determine if gradient mask needs to be created let gradientMask: CAGradientLayer if let currentMask = self.maskLayer { // Mask layer already configured gradientMask = currentMask } else { // No mask exists, create new mask gradientMask = CAGradientLayer() gradientMask.shouldRasterize = true gradientMask.rasterizationScale = UIScreen.main.scale gradientMask.startPoint = CGPoint(x: 0.0, y: 0.5) gradientMask.endPoint = CGPoint(x: 1.0, y: 0.5) // Adjust stops based on fade length let leftFadeStop = fadeLength/self.bounds.size.width let rightFadeStop = fadeLength/self.bounds.size.width gradientMask.locations = [0.0, NSNumber(value: Float(leftFadeStop)), NSNumber(value: (1.0 - Double(rightFadeStop))), 1.0,] } // Set up colors let transparent = UIColor.clear.cgColor let opaque = UIColor.black.cgColor // Set mask self.layer.mask = gradientMask gradientMask.bounds = self.layer.bounds gradientMask.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY) // Determine colors for non-scrolling label (i.e. at home) let adjustedColors: [CGColor] let trailingFadeNeeded = self.labelShouldScroll() switch (type) { case .continuousReverse, .rightLeft: adjustedColors = [(trailingFadeNeeded ? transparent : opaque), opaque, opaque, opaque] // .MLContinuous, .MLLeftRight default: adjustedColors = [opaque, opaque, opaque, (trailingFadeNeeded ? transparent : opaque)] break } if (animated) { // Finish transaction CATransaction.commit() // Create animation for color change let colorAnimation = GradientAnimation(keyPath: "colors") colorAnimation.fromValue = gradientMask.colors colorAnimation.toValue = adjustedColors colorAnimation.fillMode = kCAFillModeForwards colorAnimation.isRemovedOnCompletion = false colorAnimation.delegate = self gradientMask.add(colorAnimation, forKey: "setupFade") } else { gradientMask.colors = adjustedColors CATransaction.commit() } } fileprivate func removeGradientMask() { self.layer.mask = nil } fileprivate func keyFrameAnimationForGradient(_ fadeLength: CGFloat, interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation { // Setup let values: [[CGColor]] let keyTimes: [CGFloat] let transp = UIColor.clear.cgColor let opaque = UIColor.black.cgColor // Create new animation let animation = CAKeyframeAnimation(keyPath: "colors") // Get timing function let timingFunction = timingFunctionForAnimationCurve(animationCurve) // Define keyTimes switch (type) { case .leftRight, .rightLeft: // Calculate total animation duration let totalDuration = 2.0 * (delay + interval) keyTimes = [ 0.0, // 1) Initial gradient delay/totalDuration, // 2) Begin of LE fade-in, just as scroll away starts (delay + 0.4)/totalDuration, // 3) End of LE fade in [LE fully faded] (delay + interval - 0.4)/totalDuration, // 4) Begin of TE fade out, just before scroll away finishes (delay + interval)/totalDuration, // 5) End of TE fade out [TE fade removed] (delay + interval + delay)/totalDuration, // 6) Begin of TE fade back in, just as scroll home starts (delay + interval + delay + 0.4)/totalDuration, // 7) End of TE fade back in [TE fully faded] (totalDuration - 0.4)/totalDuration, // 8) Begin of LE fade out, just before scroll home finishes 1.0 // 9) End of LE fade out, just as scroll home finishes ] // .MLContinuous, .MLContinuousReverse default: // Calculate total animation duration let totalDuration = delay + interval // Find when the lead label will be totally offscreen let offsetDistance = awayOffset let startFadeFraction = fabs((sublabel.bounds.size.width + leadingBuffer) / offsetDistance) // Find when the animation will hit that point let startFadeTimeFraction = timingFunction.durationPercentageForPositionPercentage(startFadeFraction, duration: totalDuration) let startFadeTime = delay + CGFloat(startFadeTimeFraction) * interval keyTimes = [ 0.0, // Initial gradient delay/totalDuration, // Begin of fade in (delay + 0.2)/totalDuration, // End of fade in, just as scroll away starts startFadeTime/totalDuration, // Begin of fade out, just before scroll home completes (startFadeTime + 0.1)/totalDuration, // End of fade out, as scroll home completes 1.0 // Buffer final value (used on continuous types) ] break } // Define values // Get current layer values let mask = maskLayer?.presentation() let currentValues = mask?.colors as? [CGColor] switch (type) { case .continuousReverse: values = [ currentValues ?? [transp, opaque, opaque, opaque], // Initial gradient [transp, opaque, opaque, opaque], // Begin of fade in [transp, opaque, opaque, transp], // End of fade in, just as scroll away starts [transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes [transp, opaque, opaque, opaque], // End of fade out, as scroll home completes [transp, opaque, opaque, opaque] // Final "home" value ] break case .rightLeft: values = [ currentValues ?? [transp, opaque, opaque, opaque], // 1) [transp, opaque, opaque, opaque], // 2) [transp, opaque, opaque, transp], // 3) [transp, opaque, opaque, transp], // 4) [opaque, opaque, opaque, transp], // 5) [opaque, opaque, opaque, transp], // 6) [transp, opaque, opaque, transp], // 7) [transp, opaque, opaque, transp], // 8) [transp, opaque, opaque, opaque] // 9) ] break case .continuous: values = [ currentValues ?? [opaque, opaque, opaque, transp], // Initial gradient [opaque, opaque, opaque, transp], // Begin of fade in [transp, opaque, opaque, transp], // End of fade in, just as scroll away starts [transp, opaque, opaque, transp], // Begin of fade out, just before scroll home completes [opaque, opaque, opaque, transp], // End of fade out, as scroll home completes [opaque, opaque, opaque, transp] // Final "home" value ] break case .leftRight: values = [ currentValues ?? [opaque, opaque, opaque, transp], // 1) [opaque, opaque, opaque, transp], // 2) [transp, opaque, opaque, transp], // 3) [transp, opaque, opaque, transp], // 4) [transp, opaque, opaque, opaque], // 5) [transp, opaque, opaque, opaque], // 6) [transp, opaque, opaque, transp], // 7) [transp, opaque, opaque, transp], // 8) [opaque, opaque, opaque, transp] // 9) ] break } animation.values = values animation.keyTimes = keyTimes as [NSNumber] animation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction] return animation } fileprivate func keyFrameAnimationForProperty(_ property: String, values: [NSValue], interval: CGFloat, delay: CGFloat) -> CAKeyframeAnimation { // Create new animation let animation = CAKeyframeAnimation(keyPath: property) // Get timing function let timingFunction = timingFunctionForAnimationCurve(animationCurve) // Calculate times based on marqueeType let totalDuration: CGFloat switch (type) { case .leftRight, .rightLeft: //NSAssert(values.count == 5, @"Incorrect number of values passed for MLLeftRight-type animation") totalDuration = 2.0 * (delay + interval) // Set up keyTimes animation.keyTimes = [ 0.0, // Initial location, home NSNumber(value: Float(delay/totalDuration)), // Initial delay, at home NSNumber(value: Float((delay + interval)/totalDuration)), // Animation to away NSNumber(value: Float((delay + interval + delay)/totalDuration)), // Delay at away 1.0 // Animation to home ] animation.timingFunctions = [ timingFunction, timingFunction, timingFunction, timingFunction ] // .Continuous // .ContinuousReverse default: //NSAssert(values.count == 3, @"Incorrect number of values passed for MLContinous-type animation") totalDuration = delay + interval // Set up keyTimes animation.keyTimes = [ 0.0, // Initial location, home NSNumber(value: Float(delay/totalDuration)), // Initial delay, at home 1.0 // Animation to away ] animation.timingFunctions = [ timingFunction, timingFunction ] } // Set values animation.values = values return animation } fileprivate func timingFunctionForAnimationCurve(_ curve: UIViewAnimationCurve) -> CAMediaTimingFunction { let timingFunction: String? switch curve { case .easeIn: timingFunction = kCAMediaTimingFunctionEaseIn case .easeInOut: timingFunction = kCAMediaTimingFunctionEaseInEaseOut case .easeOut: timingFunction = kCAMediaTimingFunctionEaseOut default: timingFunction = kCAMediaTimingFunctionLinear } return CAMediaTimingFunction(name: timingFunction!) } fileprivate func transactionDurationType(_ labelType: Type, interval: CGFloat, delay: CGFloat) -> TimeInterval { switch (labelType) { case .leftRight, .rightLeft: return TimeInterval(2.0 * (delay + interval)) default: return TimeInterval(delay + interval) } } open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if anim is GradientAnimation { if let setupAnim = maskLayer?.animation(forKey: "setupFade") as? CABasicAnimation, let finalColors = setupAnim.toValue as? [CGColor] { maskLayer?.colors = finalColors } // Remove regardless, since we set removeOnCompletion = false maskLayer?.removeAnimation(forKey: "setupFade") } else { let completion = anim.value(forKey: MarqueeKeys.CompletionClosure.rawValue) as? CompletionBlock<MLAnimationCompletion> completion?.f(flag) } } // // MARK: - Private details // fileprivate var sublabel = UILabel() fileprivate var animationDuration: CGFloat = 0.0 fileprivate var homeLabelFrame = CGRect.zero fileprivate var awayOffset: CGFloat = 0.0 override open class var layerClass : AnyClass { return CAReplicatorLayer.self } fileprivate var repliLayer: CAReplicatorLayer { return self.layer as! CAReplicatorLayer } fileprivate var maskLayer: CAGradientLayer? { return self.layer.mask as! CAGradientLayer? } override open func draw(_ layer: CALayer, in ctx: CGContext) { // Do NOT call super, to prevent UILabel superclass from drawing into context // Label drawing is handled by sublabel and CAReplicatorLayer layer class // Draw only background color if let bgColor = backgroundColor { ctx.setFillColor(bgColor.cgColor); ctx.fill(layer.bounds); } } fileprivate enum MarqueeKeys: String { case Restart = "MLViewControllerRestart" case Labelize = "MLShouldLabelize" case Animate = "MLShouldAnimate" case CompletionClosure = "MLAnimationCompletion" } class fileprivate func notifyController(_ controller: UIViewController, message: MarqueeKeys) { NotificationCenter.default.post(name: Notification.Name(rawValue: message.rawValue), object: nil, userInfo: ["controller" : controller]) } @objc open func restartForViewController(_ notification: Notification) { if let controller = notification.userInfo?["controller"] as? UIViewController { if controller === self.firstAvailableViewController() { self.restartLabel() } } } @objc open func labelizeForController(_ notification: Notification) { if let controller = notification.userInfo?["controller"] as? UIViewController { if controller === self.firstAvailableViewController() { self.labelize = true } } } @objc open func animateForController(_ notification: Notification) { if let controller = notification.userInfo?["controller"] as? UIViewController { if controller === self.firstAvailableViewController() { self.labelize = false } } } // // MARK: - Label Control // /** Overrides any non-size condition which is preventing the receiver from automatically scrolling, and begins a scroll animation. Currently the only non-size conditions which can prevent a label from scrolling are the `tapToScroll` and `holdScrolling` properties. This method will not force a label with a string that fits inside the label bounds (i.e. that would not automatically scroll) to begin a scroll animation. Upon the completion of the first forced scroll animation, the receiver will not automatically continue to scroll unless the conditions preventing scrolling have been removed. - Note: This method has no effect if called during an already in-flight scroll animation. - SeeAlso: restartLabel */ open func triggerScrollStart() { if labelShouldScroll() && !awayFromHome { beginScroll() } } /** Immediately resets the label to the home position, cancelling any in-flight scroll animation, and restarts the scroll animation if the appropriate conditions are met. - SeeAlso: resetLabel - SeeAlso: triggerScrollStart */ @objc open func restartLabel() { // Shutdown the label shutdownLabel() // Restart scrolling if appropriate if labelShouldScroll() && !tapToScroll && !holdScrolling { beginScroll() } } /** Resets the label text, recalculating the scroll animation. The text is immediately returned to the home position, and the scroll animation positions are cleared. Scrolling will not resume automatically after a call to this method. To re-initiate scrolling, use either a call to `restartLabel` or make a change to a UILabel property such as text, bounds/frame, font, font size, etc. - SeeAlso: restartLabel */ open func resetLabel() { returnLabelToHome() homeLabelFrame = CGRect.null awayOffset = 0.0 } /** Immediately resets the label to the home position, cancelling any in-flight scroll animation. The text is immediately returned to the home position. Scrolling will not resume automatically after a call to this method. To re-initiate scrolling use a call to `restartLabel` or `triggerScrollStart`, or make a change to a UILabel property such as text, bounds/frame, font, font size, etc. - SeeAlso: restartLabel - SeeAlso: triggerScrollStart */ @objc open func shutdownLabel() { // Bring label to home location returnLabelToHome() // Apply gradient mask for home location applyGradientMask(fadeLength, animated: false) } /** Pauses the text scrolling animation, at any point during an in-progress animation. - Note: This method has no effect if a scroll animation is NOT already in progress. To prevent automatic scrolling on a newly-initialized label prior to its presentation onscreen, see the `holdScrolling` property. - SeeAlso: holdScrolling - SeeAlso: unpauseLabel */ open func pauseLabel() { // Prevent pausing label while not in scrolling animation, or when already paused guard (!isPaused && awayFromHome) else { return } // Pause sublabel position animations let labelPauseTime = sublabel.layer.convertTime(CACurrentMediaTime(), from: nil) sublabel.layer.speed = 0.0 sublabel.layer.timeOffset = labelPauseTime // Pause gradient fade animation let gradientPauseTime = maskLayer?.convertTime(CACurrentMediaTime(), from:nil) maskLayer?.speed = 0.0 maskLayer?.timeOffset = gradientPauseTime! } /** Un-pauses a previously paused text scrolling animation. This method has no effect if the label was not previously paused using `pauseLabel`. - SeeAlso: pauseLabel */ open func unpauseLabel() { // Only unpause if label was previously paused guard (isPaused) else { return } // Unpause sublabel position animations let labelPausedTime = sublabel.layer.timeOffset sublabel.layer.speed = 1.0 sublabel.layer.timeOffset = 0.0 sublabel.layer.beginTime = 0.0 sublabel.layer.beginTime = sublabel.layer.convertTime(CACurrentMediaTime(), from:nil) - labelPausedTime // Unpause gradient fade animation let gradientPauseTime = maskLayer?.timeOffset maskLayer?.speed = 1.0 maskLayer?.timeOffset = 0.0 maskLayer?.beginTime = 0.0 maskLayer?.beginTime = maskLayer!.convertTime(CACurrentMediaTime(), from:nil) - gradientPauseTime! } @objc open func labelWasTapped(_ recognizer: UIGestureRecognizer) { if labelShouldScroll() && !awayFromHome { beginScroll(true) } } /** Called when the label animation is about to begin. The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions just as the label animation begins. This is only called in the event that the conditions for scrolling to begin are met. */ open func labelWillBeginScroll() { // Default implementation does nothing - override to customize return } /** Called when the label animation has finished, and the label is at the home position. The default implementation of this method does nothing. Subclasses may override this method in order to perform any custom actions jas as the label animation completes, and before the next animation would begin (assuming the scroll conditions are met). - Parameter finished: A Boolean that indicates whether or not the scroll animation actually finished before the completion handler was called. - Warning: This method will be called, and the `finished` parameter will be `NO`, when any property changes are made that would cause the label scrolling to be automatically reset. This includes changes to label text and font/font size changes. */ open func labelReturnedToHome(_ finished: Bool) { // Default implementation does nothing - override to customize return } // // MARK: - Modified UILabel Functions/Getters/Setters // #if os(iOS) override open func forBaselineLayout() -> UIView { // Use subLabel view for handling baseline layouts return sublabel } open override var forLastBaselineLayout: UIView { // Use subLabel view for handling baseline layouts return sublabel } #endif open override var text: String? { get { return sublabel.text } set { if sublabel.text == newValue { return } sublabel.text = newValue updateAndScroll() super.text = text } } open override var attributedText: NSAttributedString? { get { return sublabel.attributedText } set { if sublabel.attributedText == newValue { return } sublabel.attributedText = newValue updateAndScroll() super.attributedText = attributedText } } open override var font: UIFont! { get { return sublabel.font } set { if sublabel.font == newValue { return } sublabel.font = newValue super.font = newValue updateAndScroll() } } open override var textColor: UIColor! { get { return sublabel.textColor } set { sublabel.textColor = newValue super.textColor = newValue } } open override var backgroundColor: UIColor? { get { return sublabel.backgroundColor } set { sublabel.backgroundColor = newValue super.backgroundColor = newValue } } open override var shadowColor: UIColor? { get { return sublabel.shadowColor } set { sublabel.shadowColor = newValue super.shadowColor = newValue } } open override var shadowOffset: CGSize { get { return sublabel.shadowOffset } set { sublabel.shadowOffset = newValue super.shadowOffset = newValue } } open override var highlightedTextColor: UIColor? { get { return sublabel.highlightedTextColor } set { sublabel.highlightedTextColor = newValue super.highlightedTextColor = newValue } } open override var isHighlighted: Bool { get { return sublabel.isHighlighted } set { sublabel.isHighlighted = newValue super.isHighlighted = newValue } } open override var isEnabled: Bool { get { return sublabel.isEnabled } set { sublabel.isEnabled = newValue super.isEnabled = newValue } } open override var numberOfLines: Int { get { return super.numberOfLines } set { // By the nature of MarqueeLabel, this is 1 super.numberOfLines = 1 } } open override var adjustsFontSizeToFitWidth: Bool { get { return super.adjustsFontSizeToFitWidth } set { // By the nature of MarqueeLabel, this is false super.adjustsFontSizeToFitWidth = false } } open override var minimumScaleFactor: CGFloat { get { return super.minimumScaleFactor } set { super.minimumScaleFactor = 0.0 } } open override var baselineAdjustment: UIBaselineAdjustment { get { return sublabel.baselineAdjustment } set { sublabel.baselineAdjustment = newValue super.baselineAdjustment = newValue } } open override var intrinsicContentSize : CGSize { var content = sublabel.intrinsicContentSize content.width += leadingBuffer return content } // // MARK: - Support // fileprivate func offsetCGPoint(_ point: CGPoint, offset: CGFloat) -> CGPoint { return CGPoint(x: point.x + offset, y: point.y) } // // MARK: - Deinit // deinit { NotificationCenter.default.removeObserver(self) } } // // MARK: - Support // // Solution from: http://stackoverflow.com/a/24760061/580913 private class CompletionBlock<T> { let f : T init (_ f: T) { self.f = f } } private class GradientAnimation: CABasicAnimation { } private struct Scroller { typealias Scroll = (layer: CALayer, anim: CAKeyframeAnimation) init(generator gen: @escaping (_ interval: CGFloat, _ delay: CGFloat) -> [Scroll]) { self.generator = gen } let generator: (_ interval: CGFloat, _ delay: CGFloat) -> [Scroll] var scrolls: [Scroll]? = nil mutating func generate(_ interval: CGFloat, delay: CGFloat) -> [Scroll] { if let existing = scrolls { return existing } else { scrolls = generator(interval, delay) return scrolls! } } } private extension UIResponder { // Thanks to Phil M // http://stackoverflow.com/questions/1340434/get-to-uiviewcontroller-from-uiview-on-iphone func firstAvailableViewController() -> UIViewController? { // convenience function for casting and to "mask" the recursive function return self.traverseResponderChainForFirstViewController() } func traverseResponderChainForFirstViewController() -> UIViewController? { if let nextResponder = self.next { if nextResponder.isKind(of: UIViewController.self) { return nextResponder as? UIViewController } else if (nextResponder.isKind(of: UIView.self)) { return nextResponder.traverseResponderChainForFirstViewController() } else { return nil } } return nil } } private extension CAMediaTimingFunction { func durationPercentageForPositionPercentage(_ positionPercentage: CGFloat, duration: CGFloat) -> CGFloat { // Finds the animation duration percentage that corresponds with the given animation "position" percentage. // Utilizes Newton's Method to solve for the parametric Bezier curve that is used by CAMediaAnimation. let controlPoints = self.controlPoints() let epsilon: CGFloat = 1.0 / (100.0 * CGFloat(duration)) // Find the t value that gives the position percentage we want let t_found = solveTforY(positionPercentage, epsilon: epsilon, controlPoints: controlPoints) // With that t, find the corresponding animation percentage let durationPercentage = XforCurveAt(t_found, controlPoints: controlPoints) return durationPercentage } func solveTforY(_ y_0: CGFloat, epsilon: CGFloat, controlPoints: [CGPoint]) -> CGFloat { // Use Newton's Method: http://en.wikipedia.org/wiki/Newton's_method // For first guess, use t = y (i.e. if curve were linear) var t0 = y_0 var t1 = y_0 var f0, df0: CGFloat for _ in 0..<15 { // Base this iteration of t1 calculated from last iteration t0 = t1 // Calculate f(t0) f0 = YforCurveAt(t0, controlPoints:controlPoints) - y_0 // Check if this is close (enough) if (fabs(f0) < epsilon) { // Done! return t0 } // Else continue Newton's Method df0 = derivativeCurveYValueAt(t0, controlPoints:controlPoints) // Check if derivative is small or zero ( http://en.wikipedia.org/wiki/Newton's_method#Failure_analysis ) if (fabs(df0) < 1e-6) { break } // Else recalculate t1 t1 = t0 - f0/df0 } // Give up - shouldn't ever get here...I hope print("MarqueeLabel: Failed to find t for Y input!") return t0 } func YforCurveAt(_ t: CGFloat, controlPoints:[CGPoint]) -> CGFloat { let P0 = controlPoints[0] let P1 = controlPoints[1] let P2 = controlPoints[2] let P3 = controlPoints[3] // Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves let y0 = (pow((1.0 - t),3.0) * P0.y) let y1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.y) let y2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.y) let y3 = (pow(t, 3.0) * P3.y) return y0 + y1 + y2 + y3 } func XforCurveAt(_ t: CGFloat, controlPoints: [CGPoint]) -> CGFloat { let P0 = controlPoints[0] let P1 = controlPoints[1] let P2 = controlPoints[2] let P3 = controlPoints[3] // Per http://en.wikipedia.org/wiki/Bezier_curve#Cubic_B.C3.A9zier_curves let x0 = (pow((1.0 - t),3.0) * P0.x) let x1 = (3.0 * pow(1.0 - t, 2.0) * t * P1.x) let x2 = (3.0 * (1.0 - t) * pow(t, 2.0) * P2.x) let x3 = (pow(t, 3.0) * P3.x) return x0 + x1 + x2 + x3 } func derivativeCurveYValueAt(_ t: CGFloat, controlPoints: [CGPoint]) -> CGFloat { let P0 = controlPoints[0] let P1 = controlPoints[1] let P2 = controlPoints[2] let P3 = controlPoints[3] let dy0 = (P0.y + 3.0 * P1.y + 3.0 * P2.y - P3.y) * -3.0 let dy1 = t * (6.0 * P0.y + 6.0 * P2.y) let dy2 = (-3.0 * P0.y + 3.0 * P1.y) return dy0 * pow(t, 2.0) + dy1 + dy2 } func controlPoints() -> [CGPoint] { // Create point array to point to var point: [Float] = [0.0, 0.0] var pointArray = [CGPoint]() for i in 0...3 { self.getControlPoint(at: i, values: &point) pointArray.append(CGPoint(x: CGFloat(point[0]), y: CGFloat(point[1]))) } return pointArray } }
mit
0be46b3e02308eaf5bebcc7ff921f60c
37.505432
283
0.597526
5.186047
false
false
false
false
wyp767363905/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/foodMaterial/model/CBMaterialModel.swift
1
2769
// // CBMaterialModel.swift // TestKitchen // // Created by qianfeng on 16/8/23. // Copyright © 2016年 1606. All rights reserved. // import UIKit import SwiftyJSON class CBMaterialModel: NSObject { var code: String? var msg: String? var version: String? var timestamp: NSNumber? var data: CBMaterialDataModel? class func parseModelWithData(data: NSData) -> CBMaterialModel { let model = CBMaterialModel() let jsonData = JSON(data: data) model.code = jsonData["code"].string model.msg = jsonData["msg"].string model.version = jsonData["version"].string model.timestamp = jsonData["timestamp"].number let dataJSON = jsonData["data"] model.data = CBMaterialDataModel.parseModel(dataJSON) return model } } class CBMaterialDataModel: NSObject { var id: NSNumber? var text: String? var name: String? var data: Array<CBMaterialTypeModel>? class func parseModel(jsonData: JSON) -> CBMaterialDataModel { let model = CBMaterialDataModel() model.id = jsonData["id"].number model.text = jsonData["text"].string model.name = jsonData["name"].string var array = Array<CBMaterialTypeModel>() for (_,subjson) in jsonData["data"] { let typeModel = CBMaterialTypeModel.parseModel(subjson) array.append(typeModel) } model.data = array return model } } class CBMaterialTypeModel: NSObject { var id: String? var text: String? var image: String? var data: Array<CBMaterialSubtypeModel>? class func parseModel(jsonData: JSON) -> CBMaterialTypeModel { let model = CBMaterialTypeModel() model.id = jsonData["id"].string model.text = jsonData["text"].string model.image = jsonData["image"].string var array = Array<CBMaterialSubtypeModel>() for (_,subjson) in jsonData["data"] { let subtypeModel = CBMaterialSubtypeModel.parseModel(subjson) array.append(subtypeModel) } model.data = array return model } } class CBMaterialSubtypeModel: NSObject { var id: String? var text: String? var image: String? class func parseModel(jsonData: JSON) -> CBMaterialSubtypeModel { let model = CBMaterialSubtypeModel() model.id = jsonData["id"].string model.text = jsonData["text"].string model.image = jsonData["image"].string return model } }
mit
335b66252561480c9267d446b963f7c3
20.44186
73
0.579899
4.648739
false
false
false
false
ErAbhishekChandani/ACProgressHUD
Source/ACProgressView.swift
1
7341
/* MIT License Copyright (c) 2017 Er Abhishek Chandnai 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. */ // // ACProgressView.swift // ACProgressHUD // // Created by Er. Abhishek Chandani on 02/04/17. // Copyright © 2017 Abhishek. All rights reserved. // import UIKit final class ACProgressView: UIView { //MARK: - Outlets @IBOutlet internal weak var blurView: UIVisualEffectView! @IBOutlet internal weak var hudView: UIView! @IBOutlet internal weak var textLabel: UILabel! @IBOutlet internal weak var activityIndicator: UIActivityIndicatorView! //MARK: - Variables var view: UIView! fileprivate let progressHud = ACProgressHUD.shared fileprivate class var reuseIdentifier: String { return String(describing: self) } //MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } override func awakeFromNib() { super.awakeFromNib() xibSetup() } //MARK:- SHOW HUD func show(){ DispatchQueue.main.async { let allWindows = UIApplication.shared.windows.reversed() for window in allWindows { if (window.windowLevel == UIWindow.Level.normal) { window.addSubview(self.view) self.view.frame = window.bounds break } } //BACKGROUND ANIMATION if self.progressHud.enableBackground { self.view.backgroundColor = self.view.backgroundColor?.withAlphaComponent(0) UIView.animate(withDuration: 0.30, delay: 0, options: .curveLinear, animations: { self.view.backgroundColor = self.view.backgroundColor?.withAlphaComponent(self.progressHud.backgroundColorAlpha) }, completion: nil) } // HUD ANIMATION switch self.progressHud.showHudAnimation { case .growIn : self.growIn() break case .shrinkIn : self.shrinkIn() break case .bounceIn : self.bounceIn() break case .zoomInOut : self.zoomInZoomOut() break case .slideFromTop : self.slideFromTop() break case .bounceFromTop : self.bounceFromTop() break default : break } } } //MARK:- HIDE HUD func hide() { DispatchQueue.main.async { //BACKGROUND ANIMATION if self.progressHud.enableBackground { self.view.backgroundColor = self.view.backgroundColor?.withAlphaComponent(self.progressHud.backgroundColorAlpha) UIView.animate(withDuration: 0.30, delay: 0, options: .curveLinear, animations: { self.view.backgroundColor = self.view.backgroundColor?.withAlphaComponent(0) }, completion: nil) } switch self.progressHud.dismissHudAnimation { case .growOut : self.growOut() break case .shrinkOut : self.shrinkOut() break case .fadeOut : self.fadeOut() break case .bounceOut : self.bounceOut() break case .slideToTop : self.slideToTop() break case .slideToBottom : self.slideToBottom() break case .bounceToTop : self.bounceToTop() break case .bounceToBottom : self.bounceToBottom() break default : self.view.removeFromSuperview() break } } } } //MARK:- Private Methods fileprivate extension ACProgressView { // Loading Xib func xibSetup() { view = loadViewFromNib() self.addSubview(view) view.frame = bounds appeareance() } func loadViewFromNib() -> UIView { let bundle = Bundle(for: ACProgressView.self) let nib = UINib(nibName: ACProgressView.reuseIdentifier, bundle: bundle) guard let view = nib.instantiate(withOwner: self, options: nil)[0] as? UIView else { fatalError("ERROR loading ACProgressView.\n\(#file)\n\(#line)") } return view } /// Customization HUD appeareance func appeareance(){ self.textLabel.text = progressHud.progressText self.textLabel.textColor = progressHud.progressTextColor self.textLabel.font = progressHud.progressTextFont self.activityIndicator.color = progressHud.indicatorColor self.hudView.backgroundColor = progressHud.hudBackgroundColor self.hudView.layer.cornerRadius = progressHud.cornerRadius self.hudView.layer.shadowColor = progressHud.shadowColor.cgColor self.hudView.layer.shadowRadius = progressHud.shadowRadius self.hudView.layer.shadowOpacity = 0.7 self.hudView.layer.shadowOffset = CGSize(width: 1, height: 1) self.view.backgroundColor = progressHud.enableBackground == true ? progressHud.backgroundColor.withAlphaComponent(progressHud.backgroundColorAlpha) : .clear self.blurView.isHidden = progressHud.enableBlurBackground == true ? false : true if !self.blurView.isHidden { self.view.backgroundColor = progressHud.blurBackgroundColor } } } //MARK: - Orientation //Window will not change Orientation when ACProgressHUD is being Shown. extension UINavigationController { open override var shouldAutorotate: Bool { if ACProgressHUD.shared.isBeingShown { return false } else { return true } } }
mit
338a72f1baae3c16c7efcbf88c7a3e9f
31.622222
165
0.587602
5.38518
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Services/SwiftyJSON_old.swift
1
13983
// SwiftyJSON.swift // // Copyright (c) 2014年 Ruoyu Fu, Denis Lebedev. // // 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 JSONValue { // // // case JNumber(NSNumber) // case JString(String) // case JBool(Bool) // case JNull // case JArray(Array<JSONValue>) // case JObject(Dictionary<String,JSONValue>) // case JInvalid(NSError) // // var string: String? { // switch self { // case .JString(let value): // return value // default: // return nil // } // } // // var url: NSURL? { // switch self { // case .JString(let value): // return NSURL(string: value) // default: // return nil // } // } // var number: NSNumber? { // switch self { // case .JNumber(let value): // return value // default: // return nil // } // } // // var double: Double? { // switch self { // case .JNumber(let value): // return value.doubleValue // case .JString(let value): // return (value as NSString).doubleValue // default: // return nil // } // } // // var integer: Int? { // switch self { // case .JBool(let value): // return Int(value) // case .JNumber(let value): // return value.integerValue // case .JString(let value): // return (value as NSString).integerValue // default: // return nil // } // } // // var bool: Bool? { // switch self { // case .JBool(let value): // return value // case .JNumber(let value): // return value.boolValue // case .JString(let value): // return (value as NSString).boolValue // default: // return nil // } // } // // var array: Array<JSONValue>? { // switch self { // case .JArray(let value): // return value // default: // return nil // } // } // // var object: Dictionary<String, JSONValue>? { // switch self { // case .JObject(let value): // return value // default: // return nil // } // } // // var first: JSONValue? { // switch self { // case .JArray(let jsonArray) where jsonArray.count > 0: // return jsonArray[0] // case .JObject(let jsonDictionary) where jsonDictionary.count > 0 : // let (_, value) = jsonDictionary[jsonDictionary.startIndex] // return value // default: // return nil // } // } // // var last: JSONValue? { // switch self { // case .JArray(let jsonArray) where jsonArray.count > 0: // return jsonArray[jsonArray.count-1] // case .JObject(let jsonDictionary) where jsonDictionary.count > 0 : // let (_, value) = jsonDictionary[jsonDictionary.endIndex] // return value // default: // return nil // } // } // // init (_ data: NSData!){ // if let value = data{ // var error:NSError? = nil // if let jsonObject : AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) { // self = JSONValue(jsonObject) // }else{ // self = JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1001, userInfo: [NSLocalizedDescriptionKey:"JSON Parser Error: Invalid Raw JSON Data"])) // } // }else{ // self = JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1000, userInfo: [NSLocalizedDescriptionKey:"JSON Init Error: Invalid Value Passed In init()"])) // } // // } // // init (_ rawObject: AnyObject) { // switch rawObject { // case let value as NSNumber: // if String.fromCString(value.objCType) == "c" { // self = .JBool(value.boolValue) // return // } // self = .JNumber(value) // case let value as NSString: // self = .JString(value) // case let value as NSNull: // self = .JNull // case let value as NSArray: // var jsonValues = [JSONValue]() // for possibleJsonValue : AnyObject in value { // let jsonValue = JSONValue(possibleJsonValue) // if jsonValue { // jsonValues.append(jsonValue) // } // } // self = .JArray(jsonValues) // case let value as NSDictionary: // var jsonObject = Dictionary<String, JSONValue>() // for (possibleJsonKey : AnyObject, possibleJsonValue : AnyObject) in value { // if let key = possibleJsonKey as? NSString { // let jsonValue = JSONValue(possibleJsonValue) // if jsonValue { // jsonObject[key] = jsonValue // } // } // } // self = .JObject(jsonObject) // default: // self = .JInvalid(NSError(domain: "JSONErrorDomain", code: 1000, userInfo: [NSLocalizedDescriptionKey:"JSON Init Error: Invalid Value Passed In init()"])) // } // } // // subscript(index: Int) -> JSONValue { // get { // switch self { // case .JArray(let jsonArray) where jsonArray.count > index: // return jsonArray[index] // case .JInvalid(let error): // if let userInfo = error.userInfo{ // if let breadcrumb = userInfo["JSONErrorBreadCrumbKey"] as? NSString{ // let newBreadCrumb = (breadcrumb as String) + "/\(index)" // let newUserInfo = [NSLocalizedDescriptionKey: "JSON Keypath Error: Incorrect Keypath \"\(newBreadCrumb)\"", // "JSONErrorBreadCrumbKey": newBreadCrumb] // return JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1002, userInfo: newUserInfo)) // } // } // return self // default: // let breadcrumb = "\(index)" // let newUserInfo = [NSLocalizedDescriptionKey: "JSON Keypath Error: Incorrect Keypath \"\(breadcrumb)\"", // "JSONErrorBreadCrumbKey": breadcrumb] // return JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1002, userInfo: newUserInfo)) // } // } // } // // subscript(key: String) -> JSONValue { // get { // switch self { // case .JObject(let jsonDictionary): // if let value = jsonDictionary[key] { // return value // }else { // let breadcrumb = "\(key)" // let newUserInfo = [NSLocalizedDescriptionKey: "JSON Keypath Error: Incorrect Keypath \"\(breadcrumb)\"", // "JSONErrorBreadCrumbKey": breadcrumb] // return JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1002, userInfo: newUserInfo)) // } // case .JInvalid(let error): // if let userInfo = error.userInfo{ // if let breadcrumb = userInfo["JSONErrorBreadCrumbKey"] as? NSString{ // let newBreadCrumb = (breadcrumb as String) + "/\(key)" // let newUserInfo = [NSLocalizedDescriptionKey: "JSON Keypath Error: Incorrect Keypath \"\(newBreadCrumb)\"", // "JSONErrorBreadCrumbKey": newBreadCrumb] // return JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1002, userInfo: newUserInfo)) // } // } // return self // default: // let breadcrumb = "/\(key)" // let newUserInfo = [NSLocalizedDescriptionKey: "JSON Keypath Error: Incorrect Keypath \"\(breadcrumb)\"", // "JSONErrorBreadCrumbKey": breadcrumb] // return JSONValue.JInvalid(NSError(domain: "JSONErrorDomain", code: 1002, userInfo: newUserInfo)) // } // } // } //} // //extension JSONValue: Printable { // var description: String { // switch self { // case .JInvalid(let error): // return error.localizedDescription // default: // return _printableString("") // } // } // // var rawJSONString: String { // switch self { // case .JNumber(let value): // return "\(value)" // case .JBool(let value): // return "\(value)" // case .JString(let value): // let jsonAbleString = value.stringByReplacingOccurrencesOfString("\"", withString: "\\\"", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // return "\"\(jsonAbleString)\"" // case .JNull: // return "null" // case .JArray(let array): // var arrayString = "" // for (index, value) in enumerate(array) { // if index != array.count - 1 { // arrayString += "\(value.rawJSONString)," // }else{ // arrayString += "\(value.rawJSONString)" // } // } // return "[\(arrayString)]" // case .JObject(let object): // var objectString = "" // var (index, count) = (0, object.count) // for (key, value) in object { // if index != count - 1 { // objectString += "\"\(key)\":\(value.rawJSONString)," // } else { // objectString += "\"\(key)\":\(value.rawJSONString)" // } // index += 1 // } // return "{\(objectString)}" // case .JInvalid: // return "INVALID_JSON_VALUE" // } // } // // func _printableString(indent: String) -> String { // switch self { // case .JObject(let object): // var objectString = "{\n" // var index = 0 // for (key, value) in object { // let valueString = value._printableString(indent + " ") // if index != object.count - 1 { // objectString += "\(indent) \"\(key)\":\(valueString),\n" // } else { // objectString += "\(indent) \"\(key)\":\(valueString)\n" // } // index += 1 // } // objectString += "\(indent)}" // return objectString // case .JArray(let array): // var arrayString = "[\n" // for (index, value) in enumerate(array) { // let valueString = value._printableString(indent + " ") // if index != array.count - 1 { // arrayString += "\(indent) \(valueString),\n" // }else{ // arrayString += "\(indent) \(valueString)\n" // } // } // arrayString += "\(indent)]" // return arrayString // default: // return rawJSONString // } // } //} // //extension JSONValue: BooleanType { // var boolValue: Bool { // switch self { // case .JInvalid: // return false // default: // return true // } // } //} // //extension JSONValue : Equatable { // //} // //func ==(lhs: JSONValue, rhs: JSONValue) -> Bool { // switch lhs { // case .JNumber(let lvalue): // switch rhs { // case .JNumber(let rvalue): // return rvalue == lvalue // default: // return false // } // case .JString(let lvalue): // switch rhs { // case .JString(let rvalue): // return rvalue == lvalue // default: // return false // } // case .JBool(let lvalue): // switch rhs { // case .JBool(let rvalue): // return rvalue == lvalue // default: // return false // } // case .JNull: // switch rhs { // case .JNull: // return true // default: // return false // } // case .JArray(let lvalue): // switch rhs { // case .JArray(let rvalue): // return rvalue == lvalue // default: // return false // } // case .JObject(let lvalue): // switch rhs { // case .JObject(let rvalue): // return rvalue == lvalue // default: // return false // } // default: // return false // } //}
mit
2f6c8d5d0092c667b6f6d2a0dfd721dd
34.577608
176
0.49975
4.214953
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/LegalHoldDetailsViewControllerSnapshotTests.swift
1
2225
// // Wire // Copyright (C) 2019 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 XCTest import SnapshotTesting @testable import Wire final class LegalHoldDetailsViewControllerSnapshotTests: ZMSnapshotTestCase { var sut: LegalHoldDetailsViewController! var selfUser: MockUserType! override func setUp() { super.setUp() SelfUser.setupMockSelfUser(inTeam: UUID()) selfUser = (SelfUser.current as! MockUserType) selfUser.handle = nil } override func tearDown() { sut = nil SelfUser.provider = nil super.tearDown() } func testSelfUserUnderLegalHold() { let conversation = MockGroupDetailsConversation() selfUser.isUnderLegalHold = true conversation.sortedActiveParticipantsUserTypes = [selfUser] let createSut: () -> UIViewController = { self.sut = LegalHoldDetailsViewController(conversation: conversation) return self.sut.wrapInNavigationController() } verifyInAllColorSchemes(createSut: createSut) } func testOtherUserUnderLegalHold() { let conversation = MockGroupDetailsConversation() let otherUser = SwiftMockLoader.mockUsers().first! otherUser.isUnderLegalHold = true conversation.sortedActiveParticipantsUserTypes = [otherUser] let createSut: () -> UIViewController = { self.sut = LegalHoldDetailsViewController(conversation: conversation) return self.sut.wrapInNavigationController() } verifyInAllColorSchemes(createSut: createSut) } }
gpl-3.0
a9874f794103eb2d6ecca9d1ad4c78fd
30.785714
81
0.702022
5
false
true
false
false
michaelborgmann/handshake
Handshake/MainView.swift
1
1123
// // LoginView.swift // Handshake // // Created by Michael Borgmann on 25/06/15. // Copyright (c) 2015 Michael Borgmann. All rights reserved. // import UIKit class MainView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clearColor() } override func drawRect(rect: CGRect) { let bounds = self.bounds let image = UIImage(named: "marinha.jpeg") let percent = (bounds.size.width / bounds.size.height) * 100 let width = 3000 * (bounds.size.width / bounds.size.height) let cutout = CGRectMake(image!.size.width / 2 - width/2, 0, width, image!.size.height) let reference = CGImageCreateWithImageInRect(image!.CGImage, cutout) let frame = UIImage(CGImage: reference) frame!.drawInRect(CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)) } }
gpl-2.0
2f4651b2d8d2110b85eef824ead4f08d
27.820513
99
0.608192
4.083636
false
false
false
false
roblabs/playgrounds
JsonPlayground.playground/Pages/GeoJson.xcplaygroundpage/Contents.swift
1
3392
//: Playground for consuming GeoJson using [swift-json](https://github.com/dankogai/swift-json) import UIKit var filePath = "" var optData = NSData() //: 'cout' for convenience infix operator => { associativity left precedence 95 } func => <A,R> (lhs:A, rhs:A->R)->R { return rhs(lhs) } var counter = 0; func cout(a: Any) { print("\(counter):\t\(a)") counter += 1 } //: This is what a new .geojson from [GeoJson.io](http://geojson.io) looks like let geojsonio:[String:AnyObject] = [ "type": "FeatureCollection", "features": [] ] var json = JSON(geojsonio) let jstr = json.toString() jstr => cout //: ### Simple GeoJson //: Example from [Mapbox simplestyle-spec](https://raw.githubusercontent.com/mapbox/simplestyle-spec/master/1.1.0/example.geojson) //: #### Json in the cloud var example = "https://raw.githubusercontent.com/mapbox/simplestyle-spec/master/1.1.0/example.geojson" JSON(url:example).toString(true) => cout //: #### Json on disk filePath = NSBundle.mainBundle().pathForResource("example", ofType:"geojson")! optData = NSData(contentsOfFile:filePath)! do { let directions = try NSJSONSerialization.JSONObjectWithData(optData as NSData, options: .MutableContainers) as! NSDictionary json = JSON(directions) json["features"][0]["properties"] => cout json["features"][0]["geometry"]["type"] => cout json["features"][0]["geometry"]["coordinates"] => cout } catch { print("error: \(error)") } //: ### Mapbox Directions //: Example call using [Command line interface to Mapbox Web Services](https://github.com/mapbox/mapbox-cli-py) //: //: ```mapbox directions "[-117.25955512721029, 32.79567733656968]" "[-117.25657591544467, 32.79634186493631]" --profile mapbox.walking --geojson``` //: filePath = NSBundle.mainBundle().pathForResource("Pacific-Beach", ofType:"geojson")! optData = NSData(contentsOfFile:filePath)! do { let directions = try NSJSONSerialization.JSONObjectWithData(optData as NSData, options: .MutableContainers) as! NSDictionary json = JSON(directions) json["features"][0]["properties"] => cout json["features"][0]["properties"]["distance"] => cout json["features"][0]["properties"]["summary"] => cout } catch { print("error: \(error)") } //: ### Traverse two points from a .geojson file on disk filePath = NSBundle.mainBundle().pathForResource("two-points", ofType:"geojson")! optData = NSData(contentsOfFile:filePath)! do { let twoPoints = try NSJSONSerialization.JSONObjectWithData(optData as NSData, options: .MutableContainers) as! NSDictionary json = JSON(twoPoints) // Iterate over all key value pairs for (k, v) in json["features"] { "[\"object\"][\"\(k)\"] =>\t\(v)" => cout } for (key, value) in json["features"] { "[\"object\"][\"\(key)\"] =>\t\(value["geometry"]["coordinates"])" => cout "[\"object\"][\"\(key)\"] =>\t\(value["geometry"]["coordinates"][0])" => cout "[\"object\"][\"\(key)\"] =>\t\(value["geometry"]["coordinates"][1])" => cout } // or Traverse manually json["features"][0]["geometry"]["type"] => cout json["features"][0]["geometry"]["coordinates"] => cout json["features"][0]["geometry"]["coordinates"][0] => cout json["features"][0]["geometry"]["coordinates"][1] => cout } catch { print("error: \(error)") }
apache-2.0
f95f12b1cc527a807f29d467a8a0ef1d
31.304762
148
0.643573
3.678959
false
false
false
false
RedMadRobot/DAO
Example/DAO/Classes/Business Logic/Helper/DAO/CoreDataTranslator/CDFolderTranslator.swift
1
1051
// // CDFolderTranslator.swift // DAO // // Created by Ivan Vavilov on 5/2/17. // Copyright © 2017 RedMadRobot LLC. All rights reserved. // import DAO import CoreData class CDFolderTranslator: CoreDataTranslator<Folder, CDFolder> { required init() {} override func fill(_ entity: Folder, fromEntry entry: CDFolder) { entity.entityId = entry.entryId entity.name = entry.name CDMessageTranslator().fill(&entity.messages, fromEntries: entry.messages as? Set<CDMessage>) } override func fill( _ entry: CDFolder, fromEntity entity: Folder, in context: NSManagedObjectContext) { entry.entryId = entity.entityId entry.name = entity.name var messages = Set<CDMessage>() CDMessageTranslator().fill(&messages, fromEntities: entity.messages, in: context) if let m = entry.messages { entry.removeFromMessages(m) } entry.addToMessages(messages as NSSet) } }
mit
251319b656127bf4c9cf4d2ed20ac800
23.418605
100
0.617143
4.338843
false
false
false
false
rsahara/dopamine
Dopamine/Optimizer/RmsPropOptimizer.swift
1
1829
// // RmsPropOptimizer.swift // Dopamine // // Created by Runo Sahara on 2017/05/02. // Copyright © 2017 Runo Sahara. All rights reserved. // import Foundation public class RmsPropOptimizer: Optimizer { public init(learnRate: Float = 0.001, decayRate: Float = 0.9) { _learnRate = learnRate _decayRate = decayRate _tempBuffer1 = FloatBuffer(1, _initialCapacity) _tempBuffer2 = FloatBuffer(1, _initialCapacity) _iterationNum = 0 } public func initialize(context: inout AnyObject?, rows: Int, columns: Int) { let h = FloatBuffer(rows, columns) h.fillZero() context = h as AnyObject } public func release(context: inout AnyObject?) { context = nil } public func updateIteration() { _iterationNum += 1 } public func optimize(input: FloatBuffer, gradient: FloatBuffer, context: inout AnyObject?) { // TODO: optimize let h = context as! FloatBuffer assert(h._rows == gradient._rows) assert(h._columns == gradient._columns) h.mul(_decayRate) // Reallocate if needed. // TODO: optimize if _tempBuffer1.capacity < gradient.capacity { _tempBuffer1 = FloatBuffer(like: gradient) } if _tempBuffer2.capacity < gradient.capacity { _tempBuffer2 = FloatBuffer(like: gradient) } _tempBuffer1.copy(from: gradient) _tempBuffer1.mul(gradient) _tempBuffer1.mul(1.0 - _decayRate) h.add(_tempBuffer1) _tempBuffer2.copy(from: h) _tempBuffer2.sqrt() _tempBuffer2.add(0.000001) _tempBuffer1.copy(from: gradient) _tempBuffer1.mul(_learnRate) _tempBuffer1.div(_tempBuffer2) input.sub(_tempBuffer1) } // MARK: - Hidden private let _initialCapacity: Int = 1024 * 1024 private var _iterationNum: Int private let _learnRate: Float private let _decayRate: Float private var _tempBuffer1: FloatBuffer private var _tempBuffer2: FloatBuffer }
mit
69ada9ef66ba77104058e0690910229b
22.435897
111
0.703501
3.103565
false
false
false
false
WickedColdfront/Slide-iOS
Slide for Reddit/LeftTransition.swift
1
1978
// // LeftTransition.swift // Slide for Reddit // // Created by Carlos Crane on 8/3/17. // Copyright © 2017 Haptic Apps. All rights reserved. // // Code based on https://stackoverflow.com/a/33960412/3697225 import UIKit class LeftTransition: NSObject ,UIViewControllerAnimatedTransitioning { var dismiss = false func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.0 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning){ // Get the two view controllers let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)! let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)! let containerView = transitionContext.containerView var originRect = containerView.bounds originRect.origin = CGPoint.init(x: (originRect).width, y:0) containerView.addSubview(fromVC.view) containerView.addSubview(toVC.view) if dismiss{ containerView.bringSubview(toFront: fromVC.view) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in fromVC.view.frame = originRect }, completion: { (_ ) -> Void in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true ) }) }else{ toVC.view.frame = originRect UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { () -> Void in toVC.view.center = containerView.center }) { (_) -> Void in fromVC.view.removeFromSuperview() transitionContext.completeTransition(true ) } } } }
apache-2.0
d143409e9a7e86bb8dc9a209995c072f
37.019231
114
0.632777
5.763848
false
false
false
false
cotsog/BankLogo
BankLogo/BankCard.swift
2
2591
// // BankFromNumber.swift // BankLogo // // Created by Quanlong He on 8/20/15. // Copyright © 2015 com.cybertk. All rights reserved. // import Foundation // Bool.initWithInt() extension Bool { init?<T : IntegerType>(_ integer: T?){ guard let integer = integer else { return nil } self.init(integer != 0) } } public enum ParseError: ErrorType { case Network case EmptyResponse case InvalidResponse case InvalidKey case InvalidCardNumber } public struct BankCard { public var bank: String = "" public var type: String = "" public var stat: String = "" public static func parse(cardNumber number: String, completionHandler: (BankCard?, ParseError?) -> Void) { let url = NSURL(string: "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=\(number)&cardBinCheck=true") // {"bank":"ICBC","validated":true,"cardType":"SCC","stat":"ok","messages":[],"key":"1438154967062-7837-10.208.0.17-796459287"} let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in guard error == nil else { print("NSURLSession \(error!.description)") return completionHandler(nil, ParseError.Network) } guard let data = data else { print("dataTaskWithURL error: nil") return completionHandler(nil, ParseError.EmptyResponse) } do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) guard let validated = Bool(json["validated"] as? Int) where validated == true else { print("Invalid card number: \(json)") return completionHandler(nil, ParseError.InvalidCardNumber) } guard let bank = json["bank"] as? String, type = json["cardType"] as? String, stat = json["stat"] as? String else { print("Invalid Json: \(json)") return completionHandler(nil, ParseError.InvalidKey) } let card = BankCard(bank: bank, type: type, stat: stat) return completionHandler(card, nil) } catch { print("JSONObjectWithData error: \(error)") return completionHandler(nil, ParseError.InvalidResponse) } } task.resume() } }
mit
34cdec854181d038a4bf35fec063883f
29.470588
147
0.566795
4.796296
false
false
false
false
yrchen/edx-app-ios
Source/SegmentAnalyticsTracker.swift
1
3131
// // SegmentAnalyticsTracker.swift // edX // // Created by Akiva Leffert on 9/15/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation class SegmentAnalyticsTracker : NSObject, OEXAnalyticsTracker { private let GoogleCategoryKey = "category"; private let GoogleLabelKey = "label"; private let GoogleActionKey = "action"; var currentOrientationValue : String { return UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) ? OEXAnalyticsValueOrientationPortrait : OEXAnalyticsValueOrientationLandscape } var currentOutlineModeValue : String { switch CourseDataManager.currentOutlineMode { case .Full: return OEXAnalyticsValueNavigationModeFull case .Video: return OEXAnalyticsValueNavigationModeVideo } } func identifyUser(user : OEXUserDetails) { if let userID = user.userId { var traits : [String:AnyObject] = [:] if let email = user.email { traits[key_email] = email } if let username = user.username { traits[key_username] = username } SEGAnalytics.sharedAnalytics().identify(userID.description, traits:traits) } } func clearIdentifiedUser() { SEGAnalytics.sharedAnalytics().reset() } func trackEvent(event: OEXAnalyticsEvent, forComponent component: String?, withProperties properties: [String : AnyObject]) { var context = [key_app_name : value_app_name] if let component = component { context[key_component] = component } if let courseID = event.courseID { context[key_course_id] = courseID } if let browserURL = event.openInBrowserURL { context[key_open_in_browser] = browserURL } var info : [String : AnyObject] = [ key_data : properties, key_context : context, key_name : event.name, OEXAnalyticsKeyOrientation : currentOrientationValue, OEXAnalyticsKeyNavigationMode : currentOutlineModeValue ] info[GoogleCategoryKey] = event.category info[GoogleLabelKey] = event.label SEGAnalytics.sharedAnalytics().track(event.displayName, properties: info) } func trackScreenWithName(screenName: String, courseID : String?, value : String?) { var properties: [String:NSObject] = [ key_context: [ key_app_name: value_app_name ] ] if let value = value { properties[GoogleActionKey] = value } SEGAnalytics.sharedAnalytics().screen(screenName, properties: properties) let event = OEXAnalyticsEvent() event.displayName = screenName event.label = screenName event.category = OEXAnalyticsCategoryScreen event.name = OEXAnalyticsEventScreen; event.courseID = courseID trackEvent(event, forComponent: nil, withProperties: properties) } }
apache-2.0
a5fa353f509d0e0710a213ade288c6c7
33.417582
183
0.626956
5.244556
false
false
false
false
KeithPiTsui/Pavers
Pavers/Sources/FRP/ReactiveSwift/Flatten.swift
1
46489
// // Flatten.swift // ReactiveSwift // // Created by Neil Pankey on 11/30/15. // Copyright © 2015 GitHub. All rights reserved. // /// Describes how a stream of inner streams should be flattened into a stream of values. public struct FlattenStrategy { fileprivate enum Kind { case concurrent(limit: UInt) case latest case race } fileprivate let kind: Kind private init(kind: Kind) { self.kind = kind } /// The stream of streams is merged, so that any value sent by any of the inner /// streams is forwarded immediately to the flattened stream of values. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let merge = FlattenStrategy(kind: .concurrent(limit: .max)) /// The stream of streams is concatenated, so that only values from one inner stream /// are forwarded at a time, in the order the inner streams are received. /// /// In other words, if an inner stream is received when a previous inner stream has /// yet terminated, the received stream would be enqueued. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let concat = FlattenStrategy(kind: .concurrent(limit: 1)) /// The stream of streams is merged with the given concurrency cap, so that any value /// sent by any of the inner streams on the fly is forwarded immediately to the /// flattened stream of values. /// /// In other words, if an inner stream is received when a previous inner stream has /// yet terminated, the received stream would be enqueued. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. /// /// - precondition: `limit > 0`. public static func concurrent(limit: UInt) -> FlattenStrategy { return FlattenStrategy(kind: .concurrent(limit: limit)) } /// Forward only values from the latest inner stream sent by the stream of streams. /// The active inner stream is disposed of as a new inner stream is received. /// /// The flattened stream of values completes only when the stream of streams, and all /// the inner streams it sent, have completed. /// /// Any interruption of inner streams is treated as completion, and does not interrupt /// the flattened stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let latest = FlattenStrategy(kind: .latest) /// Forward only events from the first inner stream that sends an event. Any other /// in-flight inner streams is disposed of when the winning inner stream is /// determined. /// /// The flattened stream of values completes only when the stream of streams, and the /// winning inner stream, have completed. /// /// Any interruption of inner streams is propagated immediately to the flattened /// stream of values. /// /// Any failure from the inner streams is propagated immediately to the flattened /// stream of values. public static let race = FlattenStrategy(kind: .race) } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` or an active inner producer fails, the returned /// signal will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension Signal where Value: SignalProducerConvertible, Error == Never { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` or an active inner producer fails, the returned /// signal will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> { return self .promoteError(Value.Error.self) .flatten(strategy) } } extension Signal where Value: SignalProducerConvertible, Error == Never, Value.Error == Never { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Value.Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension Signal where Value: SignalProducerConvertible, Value.Error == Never { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` fails, the returned signal will forward that failure /// immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> Signal<Value.Value, Error> { return self.flatMap(strategy) { $0.producer.promoteError(Error.self) } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - note: If `producer` or an active inner producer fails, the returned /// producer will forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Never { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - note: If an active inner producer fails, the returned producer will /// forward that failure immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> { return self .promoteError(Value.Error.self) .flatten(strategy) } } extension SignalProducer where Value: SignalProducerConvertible, Error == Never, Value.Error == Never { /// Flattens the inner producers sent upon `producer` (into a single /// producer of values), according to the semantics of the given strategy. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Value.Error> { switch strategy.kind { case .concurrent(let limit): return self.concurrent(limit: limit) case .latest: return self.switchToLatest() case .race: return self.race() } } } extension SignalProducer where Value: SignalProducerConvertible, Value.Error == Never { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// - note: If `signal` fails, the returned signal will forward that failure /// immediately. /// /// - warning: `interrupted` events on inner producers will be treated like /// `completed` events on inner producers. /// /// - parameters: /// - strategy: Strategy used when flattening signals. public func flatten(_ strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> { return self.flatMap(strategy) { $0.producer.promoteError(Error.self) } } } extension Signal where Value: Sequence { /// Flattens the `sequence` value sent by `signal`. public func flatten() -> Signal<Value.Iterator.Element, Error> { return self.flatMap(.merge, SignalProducer.init) } } extension SignalProducer where Value: Sequence { /// Flattens the `sequence` value sent by `signal`. public func flatten() -> SignalProducer<Value.Iterator.Element, Error> { return self.flatMap(.merge, SignalProducer<Value.Iterator.Element, Never>.init) } } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { fileprivate func concurrent(limit: UInt) -> Signal<Value.Value, Error> { precondition(limit > 0, "The concurrent limit must be greater than zero.") return Signal<Value.Value, Error> { relayObserver, lifetime in lifetime += self.observeConcurrent(relayObserver, limit, lifetime) } } fileprivate func observeConcurrent(_ observer: Signal<Value.Value, Error>.Observer, _ limit: UInt, _ lifetime: Lifetime) -> Disposable? { let state = Atomic(ConcurrentFlattenState<Value.Value, Error>(limit: limit)) func startNextIfNeeded() { while let producer = state.modify({ $0.dequeue() }) { let producerState = UnsafeAtomicState<ProducerState>(.starting) let deinitializer = ScopedDisposable(AnyDisposable(producerState.deinitialize)) producer.startWithSignal { signal, inner in let handle = lifetime += inner signal.observe { event in switch event { case .completed, .interrupted: handle?.dispose() let shouldComplete: Bool = state.modify { state in state.activeCount -= 1 return state.shouldComplete } withExtendedLifetime(deinitializer) { if shouldComplete { observer.sendCompleted() } else if producerState.is(.started) { startNextIfNeeded() } } case .value, .failed: observer.send(event) } } } withExtendedLifetime(deinitializer) { producerState.setStarted() } } } return observe { event in switch event { case let .value(value): state.modify { $0.queue.append(value.producer) } startNextIfNeeded() case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { state in state.isOuterCompleted = true return state.shouldComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { fileprivate func concurrent(limit: UInt) -> SignalProducer<Value.Value, Error> { precondition(limit > 0, "The concurrent limit must be greater than zero.") return SignalProducer<Value.Value, Error> { relayObserver, lifetime in self.startWithSignal { signal, interruptHandle in lifetime += interruptHandle _ = signal.observeConcurrent(relayObserver, limit, lifetime) } } } } extension SignalProducer { /// `concat`s `next` onto `self`. /// /// - parameters: /// - next: A follow-up producer to concat `self` with. /// /// - returns: A producer that will start `self` and then on completion of /// `self` - will start `next`. public func concat(_ next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return SignalProducer<SignalProducer<Value, Error>, Error>([ self, next ]).flatten(.concat) } /// `concat`s `next` onto `self`. /// /// - parameters: /// - next: A follow-up producer to concat `self` with. /// /// - returns: A producer that will start `self` and then on completion of /// `self` - will start `next`. public func concat<Next: SignalProducerConvertible>(_ next: Next) -> SignalProducer<Value, Error> where Next.Value == Value, Next.Error == Error { return concat(next.producer) } /// `concat`s `value` onto `self`. /// /// - parameters: /// - value: A value to concat onto `self`. /// /// - returns: A producer that, when started, will emit own values and on /// completion will emit a `value`. public func concat(value: Value) -> SignalProducer<Value, Error> { return concat(SignalProducer(value: value)) } /// `concat`s `error` onto `self`. /// /// - parameters: /// - error: An error to concat onto `self`. /// /// - returns: A producer that, when started, will emit own values and on /// completion will emit an `error`. public func concat(error: Error) -> SignalProducer<Value, Error> { return concat(SignalProducer(error: error)) } /// `concat`s `self` onto initial `previous`. /// /// - parameters: /// - previous: A producer to start before `self`. /// /// - returns: A signal producer that, when started, first emits values from /// `previous` producer and then from `self`. public func prefix(_ previous: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return previous.concat(self) } /// `concat`s `self` onto initial `previous`. /// /// - parameters: /// - previous: A producer to start before `self`. /// /// - returns: A signal producer that, when started, first emits values from /// `previous` producer and then from `self`. public func prefix<Previous: SignalProducerConvertible>(_ previous: Previous) -> SignalProducer<Value, Error> where Previous.Value == Value, Previous.Error == Error { return prefix(previous.producer) } /// `concat`s `self` onto initial `value`. /// /// - parameters: /// - value: A first value to emit. /// /// - returns: A producer that, when started, first emits `value`, then all /// values emited by `self`. public func prefix(value: Value) -> SignalProducer<Value, Error> { return prefix(SignalProducer(value: value)) } } private final class ConcurrentFlattenState<Value, Error: Swift.Error> { typealias Producer = PaversFRP.SignalProducer<Value, Error> /// The limit of active producers. let limit: UInt /// The number of active producers. var activeCount: UInt = 0 /// The producers waiting to be started. var queue: [Producer] = [] /// Whether the outer producer has completed. var isOuterCompleted = false /// Whether the flattened signal should complete. var shouldComplete: Bool { return isOuterCompleted && activeCount == 0 && queue.isEmpty } init(limit: UInt) { self.limit = limit } /// Dequeue the next producer if one should be started. /// /// - returns: The `Producer` to start or `nil` if no producer should be /// started. func dequeue() -> Producer? { if activeCount < limit, !queue.isEmpty { activeCount += 1 return queue.removeFirst() } else { return nil } } } private enum ProducerState: Int32 { case starting case started } extension UnsafeAtomicState where State == ProducerState { fileprivate func setStarted() { precondition(tryTransition(from: .starting, to: .started), "The transition is not supposed to fail.") } } extension Signal { /// Merges the given signals into a single `Signal` that will emit all /// values from each of them, and complete when all of them have completed. /// /// - parameters: /// - signals: A sequence of signals to merge. public static func merge<Seq: Sequence>(_ signals: Seq) -> Signal<Value, Error> where Seq.Iterator.Element == Signal<Value, Error> { return SignalProducer<Signal<Value, Error>, Error>(signals) .flatten(.merge) .startAndRetrieveSignal() } /// Merges the given signals into a single `Signal` that will emit all /// values from each of them, and complete when all of them have completed. /// /// - parameters: /// - signals: A list of signals to merge. public static func merge(_ signals: Signal<Value, Error>...) -> Signal<Value, Error> { return Signal.merge(signals) } } extension SignalProducer { /// Merges the given producers into a single `SignalProducer` that will emit /// all values from each of them, and complete when all of them have /// completed. /// /// - parameters: /// - producers: A sequence of producers to merge. public static func merge<Seq: Sequence>(_ producers: Seq) -> SignalProducer<Value, Error> where Seq.Iterator.Element == SignalProducer<Value, Error> { return SignalProducer<Seq.Iterator.Element, Never>(producers).flatten(.merge) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible>(_ a: A, _ b: B) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error { return SignalProducer.merge([a.producer, b.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error, F.Value == Value, F.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer, f.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error, F.Value == Value, F.Error == Error, G.Value == Value, G.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error, F.Value == Value, F.Error == Error, G.Value == Value, G.Error == Error, H.Value == Value, H.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error, F.Value == Value, F.Error == Error, G.Value == Value, G.Error == Error, H.Value == Value, H.Error == Error, I.Value == Value, I.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer]) } /// Merge the values of all the given producers, in the manner described by `merge(_:)`. public static func merge<A: SignalProducerConvertible, B: SignalProducerConvertible, C: SignalProducerConvertible, D: SignalProducerConvertible, E: SignalProducerConvertible, F: SignalProducerConvertible, G: SignalProducerConvertible, H: SignalProducerConvertible, I: SignalProducerConvertible, J: SignalProducerConvertible>(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H, _ i: I, _ j: J) -> SignalProducer<Value, Error> where A.Value == Value, A.Error == Error, B.Value == Value, B.Error == Error, C.Value == Value, C.Error == Error, D.Value == Value, D.Error == Error, E.Value == Value, E.Error == Error, F.Value == Value, F.Error == Error, G.Value == Value, G.Error == Error, H.Value == Value, H.Error == Error, I.Value == Value, I.Error == Error, J.Value == Value, J.Error == Error { return SignalProducer.merge([a.producer, b.producer, c.producer, d.producer, e.producer, f.producer, g.producer, h.producer, i.producer, j.producer]) } } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// - warning: An error sent on `signal` or the latest inner signal will be /// sent on the returned signal. /// /// - note: The returned signal completes when `signal` and the latest inner /// signal have both completed. fileprivate func switchToLatest() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer, lifetime in let serial = SerialDisposable() lifetime += serial lifetime += self.observeSwitchToLatest(observer, serial) } } fileprivate func observeSwitchToLatest(_ observer: Signal<Value.Value, Error>.Observer, _ latestInnerDisposable: SerialDisposable) -> Disposable? { let state = Atomic(LatestState<Value, Error>()) return self.observe { event in switch event { case let .value(p): p.producer.startWithSignal { innerSignal, innerDisposable in state.modify { // When we replace the disposable below, this prevents // the generated Interrupted event from doing any work. $0.replacingInnerSignal = true } latestInnerDisposable.inner = innerDisposable state.modify { $0.replacingInnerSignal = false $0.innerSignalComplete = false } innerSignal.observe { event in switch event { case .interrupted: // If interruption occurred as a result of a new // producer arriving, we don't want to notify our // observer. let shouldComplete: Bool = state.modify { state in if !state.replacingInnerSignal { state.innerSignalComplete = true } return !state.replacingInnerSignal && state.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .completed: let shouldComplete: Bool = state.modify { $0.innerSignalComplete = true return $0.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .value, .failed: observer.send(event) } } } case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { $0.outerSignalComplete = true return $0.innerSignalComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// - warning: An error sent on `self` or the latest inner producer will be /// sent on the returned producer. /// /// - note: The returned producer completes when `self` and the latest inner /// producer have both completed. /// /// - returns: A producer that forwards values from the latest producer sent /// on `self`, ignoring values sent on previous inner producer. fileprivate func switchToLatest() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, lifetime in let latestInnerDisposable = SerialDisposable() lifetime += latestInnerDisposable self.startWithSignal { signal, signalDisposable in lifetime += signalDisposable lifetime += signal.observeSwitchToLatest(observer, latestInnerDisposable) } } } } private struct LatestState<Value, Error: Swift.Error> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false } extension Signal where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a signal that forwards values from the "first input signal to send an event" /// (winning signal) that is sent on `self`, ignoring values sent from other inner signals. /// /// An error sent on `self` or the winning inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `self` and the winning inner signal have both completed. fileprivate func race() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer, lifetime in let relayDisposable = CompositeDisposable() lifetime += relayDisposable lifetime += self.observeRace(observer, relayDisposable) } } fileprivate func observeRace(_ observer: Signal<Value.Value, Error>.Observer, _ relayDisposable: CompositeDisposable) -> Disposable? { let state = Atomic(RaceState()) return self.observe { event in switch event { case let .value(innerProducer): // Ignore consecutive `innerProducer`s if any `innerSignal` already sent an event. guard !relayDisposable.isDisposed else { return } innerProducer.producer.startWithSignal { innerSignal, innerDisposable in state.modify { $0.innerSignalComplete = false } let disposableHandle = relayDisposable.add(innerDisposable) var isWinningSignal = false innerSignal.observe { event in if !isWinningSignal { isWinningSignal = state.modify { state in guard !state.isActivated else { return false } state.isActivated = true return true } // Ignore non-winning signals. guard isWinningSignal else { return } // The disposals would be run exactly once immediately after // the winning signal flips `state.isActivated`. disposableHandle?.dispose() relayDisposable.dispose() } switch event { case .completed: let shouldComplete: Bool = state.modify { state in state.innerSignalComplete = true return state.outerSignalComplete } if shouldComplete { observer.sendCompleted() } case .value, .failed, .interrupted: observer.send(event) } } } case let .failed(error): observer.send(error: error) case .completed: let shouldComplete: Bool = state.modify { state in state.outerSignalComplete = true return state.innerSignalComplete } if shouldComplete { observer.sendCompleted() } case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer where Value: SignalProducerConvertible, Error == Value.Error { /// Returns a producer that forwards values from the "first input producer to send an event" /// (winning producer) that is sent on `self`, ignoring values sent from other inner producers. /// /// An error sent on `self` or the winning inner producer will be sent on the /// returned producer. /// /// The returned producer completes when `self` and the winning inner producer have both completed. fileprivate func race() -> SignalProducer<Value.Value, Error> { return SignalProducer<Value.Value, Error> { observer, lifetime in let relayDisposable = CompositeDisposable() lifetime += relayDisposable self.startWithSignal { signal, signalDisposable in lifetime += signalDisposable lifetime += signal.observeRace(observer, relayDisposable) } } } } private struct RaceState { var outerSignalComplete = false var innerSignalComplete = true var isActivated = false } extension Signal { /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` or any of the created producers fail, the /// returned signal will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Error>) -> Signal<U, Error>{ return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` or any of the created producers fail, the /// returned signal will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == Error { return flatMap(strategy) { transform($0).producer } } /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` fails, the returned signal will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Never>) -> Signal<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If `signal` fails, the returned signal will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Error> where Inner.Error == Never { return flatMap(strategy) { transform($0).producer } } } extension Signal where Error == Never { /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created signals emit an error, the returned /// signal will forward that error immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U, F>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, F>) -> Signal<U, F> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created signals emit an error, the returned /// signal will forward that error immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Inner.Error> { return flatMap(strategy) { transform($0).producer } } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Never>) -> Signal<U, Never> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> Signal<Inner.Value, Never> where Inner.Error == Never { return flatMap(strategy) { transform($0).producer } } } extension SignalProducer { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` or any of the created producers fail, the returned /// producer will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` or any of the created producers fail, the returned /// producer will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error { return flatMap(strategy) { transform($0).producer } } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` fails, the returned producer will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Never>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If `self` fails, the returned producer will forward that /// failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Never { return flatMap(strategy) { transform($0).producer } } } extension SignalProducer where Error == Never { /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, Error>) -> SignalProducer<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Error> where Inner.Error == Error { return flatMap(strategy) { transform($0).producer } } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created producers fail, the returned producer /// will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<U, F>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> SignalProducer<U, F>) -> SignalProducer<U, F> { return map(transform).flatten(strategy) } /// Maps each event from `self` to a new producer, then flattens the /// resulting producers (into a producer of values), according to the /// semantics of the given strategy. /// /// - warning: If any of the created producers fail, the returned producer /// will forward that failure immediately. /// /// - parameters: /// - strategy: Strategy used when flattening signals. /// - transform: A closure that takes a value emitted by `self` and /// returns a signal producer with transformed value. public func flatMap<Inner: SignalProducerConvertible>(_ strategy: FlattenStrategy, _ transform: @escaping (Value) -> Inner) -> SignalProducer<Inner.Value, Inner.Error> { return flatMap(strategy) { transform($0).producer } } } extension Signal { /// Catches any failure that may occur on the input signal, mapping to a new /// producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> Signal<Value, F> { return Signal<Value, F> { observer, lifetime in lifetime += self.observeFlatMapError(transform, observer, SerialDisposable()) } } /// Catches any failure that may occur on the input signal, mapping to a new /// producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<Inner: SignalProducerConvertible>(_ transform: @escaping (Error) -> Inner) -> Signal<Value, Inner.Error> where Inner.Value == Value { return flatMapError { transform($0).producer } } fileprivate func observeFlatMapError<Inner: SignalProducerConvertible>( _ handler: @escaping (Error) -> Inner, _ observer: Signal<Value, Inner.Error>.Observer, _ serialDisposable: SerialDisposable) -> Disposable? where Inner.Value == Value { return self.observe { event in switch event { case let .value(value): observer.send(value: value) case let .failed(error): handler(error).producer.startWithSignal { signal, disposable in serialDisposable.inner = disposable signal.observe(observer) } case .completed: observer.sendCompleted() case .interrupted: observer.sendInterrupted() } } } } extension SignalProducer { /// Catches any failure that may occur on the input producer, mapping to a /// new producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<F>(_ transform: @escaping (Error) -> SignalProducer<Value, F>) -> SignalProducer<Value, F> { return SignalProducer<Value, F> { observer, lifetime in let serialDisposable = SerialDisposable() lifetime += serialDisposable self.startWithSignal { signal, signalDisposable in serialDisposable.inner = signalDisposable _ = signal.observeFlatMapError(transform, observer, serialDisposable) } } } /// Catches any failure that may occur on the input producer, mapping to a /// new producer that starts in its place. /// /// - parameters: /// - transform: A closure that accepts emitted error and returns a signal /// producer with a different type of error. public func flatMapError<Inner: SignalProducerConvertible>(_ transform: @escaping (Error) -> Inner) -> SignalProducer<Value, Inner.Error> where Inner.Value == Value { return flatMapError { transform($0).producer } } }
mit
b8893ca0681dcf6d6e090d52dc3a6676
40.067138
804
0.690845
4.02947
false
false
false
false
woohyuknrg/GithubTrending
github/View Controllers/RepositoryViewController.swift
1
2652
import UIKit import RxSwift import RxCocoa import SafariServices class RepositoryViewController: UIViewController { var viewModel: RepositoryViewModel? @IBOutlet weak fileprivate var titleLabel: UILabel! @IBOutlet weak fileprivate var descriptionLabel: UILabel! @IBOutlet weak fileprivate var forksCountLabel: UILabel! @IBOutlet weak fileprivate var starsCountLabel: UILabel! @IBOutlet weak fileprivate var tableView: UITableView! @IBOutlet weak fileprivate var readMeButton: UIButton! fileprivate var datasource = [RepositorySectionViewModel]() fileprivate let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() bindToRx() configureTableView() } func bindToRx() { guard let vm = viewModel else { return } title = vm.fullName titleLabel.text = vm.fullName descriptionLabel.text = vm.description forksCountLabel.text = vm.forksCounts starsCountLabel.text = vm.starsCount readMeButton.rx.tap.bind(to: vm.readMeTaps).disposed(by: disposeBag) vm.readMeURLObservable.subscribe(onNext: { [weak self] url in let svc = SFSafariViewController(url: url, entersReaderIfAvailable: true) self?.present(svc, animated: true, completion: nil) }) .disposed(by: disposeBag) vm.dataObservable.drive(onNext: { [weak self] data in self?.datasource = data self?.tableView.reloadData() }) .disposed(by: disposeBag) } } extension RepositoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return datasource[section].header } func numberOfSections(in tableView: UITableView) -> Int { return datasource.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasource[section].items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "RepositoryCell", for: indexPath) let item = datasource[indexPath.section].items[indexPath.row] cell.textLabel?.text = item.title cell.detailTextLabel?.text = item.subtitle return cell } } // MARK: UI stuff extension RepositoryViewController { fileprivate func configureTableView() { tableView.tableFooterView = UIView() // Removes separators in empty cells } }
mit
0924c688c51172b459f98117248fdcd0
33
100
0.676848
5.261905
false
false
false
false
Sahilberi/SwiftyDropDataListing
Pods/SwiftyDropbox/Source/SwiftyDropbox/Platform/SwiftyDropbox_iOS/OAuthMobile.swift
1
10027
/// /// Copyright (c) 2016 Dropbox, Inc. All rights reserved. /// import Foundation import SafariServices import UIKit import WebKit extension DropboxClientsManager { public static func authorizeFromController(_ sharedApplication: UIApplication, controller: UIViewController?, openURL: @escaping ((URL) -> Void)) { precondition(DropboxOAuthManager.sharedOAuthManager != nil, "Call `DropboxClientsManager.setupWithAppKey` or `DropboxClientsManager.setupWithTeamAppKey` before calling this method") let sharedMobileApplication = MobileSharedApplication(sharedApplication: sharedApplication, controller: controller, openURL: openURL) MobileSharedApplication.sharedMobileApplication = sharedMobileApplication DropboxOAuthManager.sharedOAuthManager.authorizeFromSharedApplication(sharedMobileApplication) } public static func setupWithAppKey(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManager(appKey, oAuthManager: DropboxMobileOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithAppKeyMultiUser(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUser(appKey, oAuthManager: DropboxMobileOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } public static func setupWithTeamAppKey(_ appKey: String, transportClient: DropboxTransportClient? = nil) { setupWithOAuthManagerTeam(appKey, oAuthManager: DropboxMobileOAuthManager(appKey: appKey), transportClient: transportClient) } public static func setupWithTeamAppKeyMultiUser(_ appKey: String, transportClient: DropboxTransportClient? = nil, tokenUid: String?) { setupWithOAuthManagerMultiUserTeam(appKey, oAuthManager: DropboxMobileOAuthManager(appKey: appKey), transportClient: transportClient, tokenUid: tokenUid) } } open class DropboxMobileOAuthManager: DropboxOAuthManager { var dauthRedirectURL: URL public override init(appKey: String, host: String) { self.dauthRedirectURL = URL(string: "db-\(appKey)://1/connect")! super.init(appKey: appKey, host:host) self.urls.append(self.dauthRedirectURL) } internal override func extractFromUrl(_ url: URL) -> DropboxOAuthResult { let result: DropboxOAuthResult if url.host == "1" { // dauth result = extractfromDAuthURL(url) } else { result = extractFromRedirectURL(url) } return result } internal override func checkAndPresentPlatformSpecificAuth(_ sharedApplication: SharedApplication) -> Bool { if !self.hasApplicationQueriesSchemes() { let message = "DropboxSDK: unable to link; app isn't registered to query for URL schemes dbapi-2 and dbapi-8-emm. Add a dbapi-2 entry and a dbapi-8-emm entry to LSApplicationQueriesSchemes" let title = "SwiftyDropbox Error" sharedApplication.presentErrorMessage(message, title: title) return true } if let scheme = dAuthScheme(sharedApplication) { let nonce = UUID().uuidString UserDefaults.standard.set(nonce, forKey: kDBLinkNonce) UserDefaults.standard.synchronize() sharedApplication.presentExternalApp(dAuthURL(scheme, nonce: nonce)) return true } return false } open override func handleRedirectURL(_ url: URL) -> DropboxOAuthResult? { if let sharedMobileApplication = MobileSharedApplication.sharedMobileApplication { sharedMobileApplication.dismissAuthController() } let result = super.handleRedirectURL(url) return result } fileprivate func dAuthURL(_ scheme: String, nonce: String?) -> URL { var components = URLComponents() components.scheme = scheme components.host = "1" components.path = "/connect" if let n = nonce { let state = "oauth2:\(n)" components.queryItems = [ URLQueryItem(name: "k", value: self.appKey), URLQueryItem(name: "s", value: ""), URLQueryItem(name: "state", value: state), ] } return components.url! } fileprivate func dAuthScheme(_ sharedApplication: SharedApplication) -> String? { if sharedApplication.canPresentExternalApp(dAuthURL("dbapi-2", nonce: nil)) { return "dbapi-2" } else if sharedApplication.canPresentExternalApp(dAuthURL("dbapi-8-emm", nonce: nil)) { return "dbapi-8-emm" } else { return nil } } func extractfromDAuthURL(_ url: URL) -> DropboxOAuthResult { switch url.path { case "/connect": var results = [String: String]() let pairs = url.query?.components(separatedBy: "&") ?? [] for pair in pairs { let kv = pair.components(separatedBy: "=") results.updateValue(kv[1], forKey: kv[0]) } let state = results["state"]?.components(separatedBy: "%3A") ?? [] let nonce = UserDefaults.standard.object(forKey: kDBLinkNonce) as? String if state.count == 2 && state[0] == "oauth2" && state[1] == nonce! { let accessToken = results["oauth_token_secret"]! let uid = results["uid"]! return .success(DropboxAccessToken(accessToken: accessToken, uid: uid)) } else { return .error(.unknown, "Unable to verify link request") } default: return .error(.accessDenied, "User cancelled Dropbox link") } } fileprivate func hasApplicationQueriesSchemes() -> Bool { let queriesSchemes = Bundle.main.object(forInfoDictionaryKey: "LSApplicationQueriesSchemes") as? [String] ?? [] var foundApi2 = false var foundApi8Emm = false for scheme in queriesSchemes { if scheme == "dbapi-2" { foundApi2 = true } else if scheme == "dbapi-8-emm" { foundApi8Emm = true } if foundApi2 && foundApi8Emm { return true } } return false } } open class MobileSharedApplication: SharedApplication { open static var sharedMobileApplication: MobileSharedApplication? let sharedApplication: UIApplication let controller: UIViewController? let openURL: ((URL) -> Void) public init(sharedApplication: UIApplication, controller: UIViewController?, openURL: @escaping ((URL) -> Void)) { // fields saved for app-extension safety self.sharedApplication = sharedApplication self.controller = controller self.openURL = openURL } open func presentErrorMessage(_ message: String, title: String) { let alertController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) if let controller = controller { controller.present(alertController, animated: true, completion: { fatalError(message) }) } } open func presentErrorMessageWithHandlers(_ message: String, title: String, buttonHandlers: Dictionary<String, () -> Void>) { let alertController = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel) { (_) in if let handler = buttonHandlers["Cancel"] { handler() } }) alertController.addAction(UIAlertAction(title: "Retry", style: .default) { (_) in if let handler = buttonHandlers["Retry"] { handler() } }) if let controller = controller { controller.present(alertController, animated: true, completion: {}) } } open func presentPlatformSpecificAuth(_ authURL: URL) -> Bool { presentExternalApp(authURL) return true } open func presentAuthChannel(_ authURL: URL, tryIntercept: @escaping ((URL) -> Bool), cancelHandler: @escaping (() -> Void)) { if let controller = self.controller { let safariViewController = MobileSafariViewController(url: authURL, cancelHandler: cancelHandler) controller.present(safariViewController, animated: true, completion: nil) } } open func presentExternalApp(_ url: URL) { self.openURL(url) } open func canPresentExternalApp(_ url: URL) -> Bool { return self.sharedApplication.canOpenURL(url) } open func dismissAuthController() { if let controller = self.controller { if let presentedViewController = controller.presentedViewController { if presentedViewController.isBeingDismissed == false && presentedViewController is MobileSafariViewController { controller.dismiss(animated: true, completion: nil) } } } } } open class MobileSafariViewController: SFSafariViewController, SFSafariViewControllerDelegate { var cancelHandler: (() -> Void) = {} public init(url: URL, cancelHandler: @escaping (() -> Void)) { super.init(url: url, entersReaderIfAvailable: false) self.cancelHandler = cancelHandler self.delegate = self; } public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { if (!didLoadSuccessfully) { controller.dismiss(animated: true, completion: nil) } } public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { self.cancelHandler() } }
mit
7085ccf7b7a4d13a3a5913417a055581
39.269076
201
0.644859
5.157922
false
false
false
false
laszlokorte/reform-swift
ReformMath/ReformMath/Line2d.swift
1
787
// // Line2d.swift // ReformMath // // Created by Laszlo Korte on 23.09.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public struct Line2d : Equatable { public let from: Vec2d public let direction: Vec2d public init?(from: Vec2d, direction: Vec2d) { guard let dir = normalize(direction) else { return nil } self.from = from self.direction = dir } public init(from: Vec2d, angle: Angle) { self.from = from self.direction = Vec2d(radius: 1, angle: angle) } } public func ==(lhs: Line2d, rhs: Line2d) -> Bool { return lhs.from == rhs.from && lhs.direction == rhs.direction } extension Line2d { public var angle : Angle { return ReformMath.angle(direction) } }
mit
e786605c22771de6803eb367b2bbf6ba
20.861111
65
0.60687
3.477876
false
false
false
false
xuduo/socket.io-push-ios
source/PushIdGeneratorBase.swift
1
1325
// // PushIdGeneratorBase.swift // MisakaKeepAlive // // Created by crazylhf on 15/10/26. // Copyright © 2015年 crazylhf. All rights reserved. // import Foundation public class PushIdGeneratorBase : NSObject { private let pushGeneratorKey = "SharedPreferencePushGenerator" public static func randomAlphaNumeric(count:Int) -> String { var cnt = count var randomStr = ""; while (cnt >= 0) { cnt = cnt - 1 randomStr = randomStr + String(self.oneRandomAlphaNumeric()); } return randomStr } public static func oneRandomAlphaNumeric() -> Character { let randomVal = arc4random() % 5; if (0 == randomVal || 2 == randomVal || 4 == randomVal) { return Character(UnicodeScalar(97 + (arc4random() % 26))); } else { return Character(UnicodeScalar(48 + (arc4random() % 10))); } } public func generatePushId() -> String { var strPushID = StorageUtil.sharedInstance().getItem(pushGeneratorKey) as? String if (nil == strPushID) { strPushID = PushIdGeneratorBase.randomAlphaNumeric(32); StorageUtil.sharedInstance().setItem(strPushID, forKey: pushGeneratorKey) } return strPushID!; } }
mit
3d114f01c6884d50418b12c37987836e
27.73913
89
0.597579
4.306189
false
false
false
false
llxyls/DYTV
DYTV/DYTV/Classes/Main/View/CollectionViewBaseCell.swift
1
1056
// // CollectionViewBaseCell.swift // DYTV // // Created by liuqi on 16/10/13. // Copyright © 2016年 liuqi. All rights reserved. // import UIKit import Kingfisher class CollectionViewBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! var anchor: AnchorModel? { didSet{ guard let anchor = anchor else {return} var onlineStr: String = "" if anchor.online >= 10000 { onlineStr = "\(anchor.online/10000)万在线" } else { onlineStr = "\(anchor.online)在线" } // 在线人数 onlineBtn.setTitle(onlineStr, for: .normal) // 昵称的显示 nickNameLabel.text = anchor.nickname // 图片 guard let iconURL = URL(string: anchor.vertical_src) else {return} iconImageView.kf.setImage(with: iconURL) } } }
mit
ddb33a7cd13e440f7e6db9aea8d4c601
25.868421
79
0.568071
4.640909
false
false
false
false
sameertotey/LimoService
LimoService/DateSelectionTableViewCell.swift
1
3675
// // DateSelectionTableViewCell.swift // LimoService // // Created by Sameer Totey on 4/13/15. // Copyright (c) 2015 Sameer Totey. All rights reserved. // import UIKit class DateSelectionTableViewCell: UITableViewCell { @IBOutlet weak var dateButton: UIButton! @IBOutlet weak var datePicker: UIDatePicker! var savedDatePicker: UIDatePicker! var savedDateButton: UIButton! weak var delegate: DateSelectionDelegate? var date: NSDate? { didSet { if date != nil { datePicker.minimumDate = date!.earlierDate(NSDate()) datePicker.date = date! dateString = dateFormatter.stringFromDate(date!) updateDatePickerLabel() } } } var dateString: String? var enabled: Bool = true { didSet { dateButton.enabled = enabled datePicker.enabled = enabled } } override func awakeFromNib() { super.awakeFromNib() // Initialization code savedDatePicker = datePicker savedDateButton = dateButton } func configureDatePicker() { datePicker.datePickerMode = .DateAndTime // Set min/max date for the date picker. // As an example we will limit the date between now and 15 days from now. let now = NSDate() datePicker.minimumDate = now date = now let currentCalendar = NSCalendar.currentCalendar() let dateComponents = NSDateComponents() dateComponents.day = 15 let fifteenDaysFromNow = currentCalendar.dateByAddingComponents(dateComponents, toDate: now, options: nil) datePicker.maximumDate = fifteenDaysFromNow datePicker.minuteInterval = 2 datePicker.addTarget(self, action: "updateDatePickerLabel", forControlEvents: .ValueChanged) updateDatePickerLabel() } /// A date formatter to format the `date` property of `datePicker`. lazy var dateFormatter: NSDateFormatter = { let dateFormatter = NSDateFormatter() dateFormatter.dateStyle = .MediumStyle dateFormatter.timeStyle = .ShortStyle return dateFormatter }() func updateDatePickerLabel() { dateButton.setTitle(dateFormatter.stringFromDate(datePicker.date), forState: .Normal) } var viewExpanded = true { didSet { self.hideDatePicker(!viewExpanded) } } func hideDatePicker(setting: Bool) { var viewsDict = Dictionary <String, UIView>() viewsDict["dateButton"] = dateButton viewsDict["datePicker"] = datePicker contentView.subviews.map({ $0.removeFromSuperview() }) contentView.addSubview(dateButton) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[dateButton]-|", options: nil, metrics: nil, views: viewsDict)) if setting { contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[dateButton]-|", options: nil, metrics: nil, views: viewsDict)) } else { contentView.addSubview(datePicker) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[datePicker]-|", options: nil, metrics: nil, views: viewsDict)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[dateButton]-[datePicker]-|", options: nil, metrics: nil, views: viewsDict)) } } // MARK: - Actions @IBAction func buttonTouched(sender: UIButton) { delegate?.dateButtonToggled(self) } }
mit
05f4fac4503a694be5e5525b831a63db
32.409091
167
0.640272
5.526316
false
false
false
false
Ferrick90/Fusuma
Example/FusumaExample/ViewController.swift
2
2328
// // ViewController.swift // Fusuma // // Created by ytakzk on 01/31/2016. // Copyright (c) 2016 ytakzk. All rights reserved. // import UIKit class ViewController: UIViewController, FusumaDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var showButton: UIButton! @IBOutlet weak var fileUrlLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() showButton.layer.cornerRadius = 2.0 self.fileUrlLabel.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showButtonPressed(_ sender: AnyObject) { // Show Fusuma let fusuma = FusumaViewController() // fusumaCropImage = false fusuma.delegate = self self.present(fusuma, animated: true, completion: nil) } // MARK: FusumaDelegate Protocol func fusumaImageSelected(_ image: UIImage) { print("Image selected") imageView.image = image } func fusumaVideoCompleted(withFileURL fileURL: URL) { print("video completed and output to file: \(fileURL)") self.fileUrlLabel.text = "file output to: \(fileURL.absoluteString)" } func fusumaDismissedWithImage(_ image: UIImage) { print("Called just after dismissed FusumaViewController") } func fusumaCameraRollUnauthorized() { print("Camera roll unauthorized") let alert = UIAlertController(title: "Access Requested", message: "Saving image needs to access your photo album", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (action) -> Void in if let url = URL(string:UIApplicationOpenSettingsURLString) { UIApplication.shared.openURL(url) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in })) self.present(alert, animated: true, completion: nil) } func fusumaClosed() { print("Called when the close button is pressed") } }
mit
40fc6300ab1030d3ee57d241e8b48f9c
26.388235
146
0.60567
5.116484
false
false
false
false
brentdax/swift
stdlib/public/core/Hasher.swift
1
15725
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // // Defines the Hasher struct, representing Swift's standard hash function. // //===----------------------------------------------------------------------===// import SwiftShims // FIXME: Remove @usableFromInline once Hasher is resilient. // rdar://problem/38549901 @usableFromInline internal protocol _HasherCore { init(rawSeed: (UInt64, UInt64)) mutating func compress(_ value: UInt64) mutating func finalize(tailAndByteCount: UInt64) -> UInt64 } extension _HasherCore { @inline(__always) internal init() { self.init(rawSeed: Hasher._executionSeed) } @inline(__always) internal init(seed: Int) { let executionSeed = Hasher._executionSeed // Prevent sign-extending the supplied seed; this makes testing slightly // easier. let seed = UInt(bitPattern: seed) self.init(rawSeed: ( executionSeed.0 ^ UInt64(truncatingIfNeeded: seed), executionSeed.1)) } } @inline(__always) internal func _loadPartialUnalignedUInt64LE( _ p: UnsafeRawPointer, byteCount: Int ) -> UInt64 { var result: UInt64 = 0 switch byteCount { case 7: result |= UInt64(p.load(fromByteOffset: 6, as: UInt8.self)) &<< 48 fallthrough case 6: result |= UInt64(p.load(fromByteOffset: 5, as: UInt8.self)) &<< 40 fallthrough case 5: result |= UInt64(p.load(fromByteOffset: 4, as: UInt8.self)) &<< 32 fallthrough case 4: result |= UInt64(p.load(fromByteOffset: 3, as: UInt8.self)) &<< 24 fallthrough case 3: result |= UInt64(p.load(fromByteOffset: 2, as: UInt8.self)) &<< 16 fallthrough case 2: result |= UInt64(p.load(fromByteOffset: 1, as: UInt8.self)) &<< 8 fallthrough case 1: result |= UInt64(p.load(fromByteOffset: 0, as: UInt8.self)) fallthrough case 0: return result default: _sanityCheckFailure() } } /// This is a buffer for segmenting arbitrary data into 8-byte chunks. Buffer /// storage is represented by a single 64-bit value in the format used by the /// finalization step of SipHash. (The least significant 56 bits hold the /// trailing bytes, while the most significant 8 bits hold the count of bytes /// appended so far, modulo 256. The count of bytes currently stored in the /// buffer is in the lower three bits of the byte count.) // FIXME: Remove @usableFromInline and @_fixed_layout once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @_fixed_layout internal struct _HasherTailBuffer { // msb lsb // +---------+-------+-------+-------+-------+-------+-------+-------+ // |byteCount| tail (<= 56 bits) | // +---------+-------+-------+-------+-------+-------+-------+-------+ internal var value: UInt64 @inline(__always) internal init() { self.value = 0 } @inline(__always) internal init(tail: UInt64, byteCount: UInt64) { // byteCount can be any value, but we only keep the lower 8 bits. (The // lower three bits specify the count of bytes stored in this buffer.) // FIXME: This should be a single expression, but it causes exponential // behavior in the expression type checker <rdar://problem/42672946>. let shiftedByteCount: UInt64 = ((byteCount & 7) << 3) let mask: UInt64 = (1 << shiftedByteCount - 1) _sanityCheck(tail & ~mask == 0) self.value = (byteCount &<< 56 | tail) } @inline(__always) internal init(tail: UInt64, byteCount: Int) { self.init(tail: tail, byteCount: UInt64(truncatingIfNeeded: byteCount)) } internal var tail: UInt64 { @inline(__always) get { return value & ~(0xFF &<< 56) } } internal var byteCount: UInt64 { @inline(__always) get { return value &>> 56 } } @inline(__always) internal mutating func append(_ bytes: UInt64) -> UInt64 { let c = byteCount & 7 if c == 0 { value = value &+ (8 &<< 56) return bytes } let shift = c &<< 3 let chunk = tail | (bytes &<< shift) value = (((value &>> 56) &+ 8) &<< 56) | (bytes &>> (64 - shift)) return chunk } @inline(__always) internal mutating func append(_ bytes: UInt64, count: UInt64) -> UInt64? { _sanityCheck(count >= 0 && count < 8) _sanityCheck(bytes & ~((1 &<< (count &<< 3)) &- 1) == 0) let c = byteCount & 7 let shift = c &<< 3 if c + count < 8 { value = (value | (bytes &<< shift)) &+ (count &<< 56) return nil } let chunk = tail | (bytes &<< shift) value = ((value &>> 56) &+ count) &<< 56 if c + count > 8 { value |= bytes &>> (64 - shift) } return chunk } } // FIXME: Remove @usableFromInline and @_fixed_layout once Hasher is resilient. // rdar://problem/38549901 @usableFromInline @_fixed_layout internal struct _BufferingHasher<RawCore: _HasherCore> { private var _buffer: _HasherTailBuffer private var _core: RawCore @inline(__always) internal init(core: RawCore) { self._buffer = _HasherTailBuffer() self._core = core } @inline(__always) internal init() { self.init(core: RawCore()) } @inline(__always) internal init(seed: Int) { self.init(core: RawCore(seed: seed)) } @inline(__always) internal mutating func combine(_ value: UInt) { #if arch(i386) || arch(arm) combine(UInt32(truncatingIfNeeded: value)) #else combine(UInt64(truncatingIfNeeded: value)) #endif } @inline(__always) internal mutating func combine(_ value: UInt64) { _core.compress(_buffer.append(value)) } @inline(__always) internal mutating func combine(_ value: UInt32) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 4) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt16) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 2) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(_ value: UInt8) { let value = UInt64(truncatingIfNeeded: value) if let chunk = _buffer.append(value, count: 1) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UInt64, count: Int) { _sanityCheck(count >= 0 && count < 8) let count = UInt64(truncatingIfNeeded: count) if let chunk = _buffer.append(bytes, count: count) { _core.compress(chunk) } } @inline(__always) internal mutating func combine(bytes: UnsafeRawBufferPointer) { var remaining = bytes.count guard remaining > 0 else { return } var data = bytes.baseAddress! // Load first unaligned partial word of data do { let start = UInt(bitPattern: data) let end = _roundUp(start, toAlignment: MemoryLayout<UInt64>.alignment) let c = min(remaining, Int(end - start)) if c > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: c) combine(bytes: chunk, count: c) data += c remaining -= c } } _sanityCheck( remaining == 0 || Int(bitPattern: data) & (MemoryLayout<UInt64>.alignment - 1) == 0) // Load as many aligned words as there are in the input buffer while remaining >= MemoryLayout<UInt64>.size { combine(UInt64(littleEndian: data.load(as: UInt64.self))) data += MemoryLayout<UInt64>.size remaining -= MemoryLayout<UInt64>.size } // Load last partial word of data _sanityCheck(remaining >= 0 && remaining < 8) if remaining > 0 { let chunk = _loadPartialUnalignedUInt64LE(data, byteCount: remaining) combine(bytes: chunk, count: remaining) } } @inline(__always) internal mutating func finalize() -> UInt64 { return _core.finalize(tailAndByteCount: _buffer.value) } } /// The universal hash function used by `Set` and `Dictionary`. /// /// `Hasher` can be used to map an arbitrary sequence of bytes to an integer /// hash value. You can feed data to the hasher using a series of calls to /// mutating `combine` methods. When you've finished feeding the hasher, the /// hash value can be retrieved by calling `finalize()`: /// /// var hasher = Hasher() /// hasher.combine(23) /// hasher.combine("Hello") /// let hashValue = hasher.finalize() /// /// Within the execution of a Swift program, `Hasher` guarantees that finalizing /// it will always produce the same hash value as long as it is fed the exact /// same sequence of bytes. However, the underlying hash algorithm is designed /// to exhibit avalanche effects: slight changes to the seed or the input byte /// sequence will typically produce drastic changes in the generated hash value. /// /// - Note: Do not save or otherwise reuse hash values across executions of your /// program. `Hasher` is usually randomly seeded, which means it will return /// different values on every new execution of your program. The hash /// algorithm implemented by `Hasher` may itself change between any two /// versions of the standard library. @_fixed_layout // FIXME: Should be resilient (rdar://problem/38549901) public struct Hasher { // FIXME: Remove @usableFromInline once Hasher is resilient. // rdar://problem/38549901 @usableFromInline internal typealias RawCore = _SipHash13Core // FIXME: Remove @usableFromInline once Hasher is resilient. // rdar://problem/38549901 @usableFromInline internal typealias Core = _BufferingHasher<RawCore> internal var _core: Core /// Creates a new hasher. /// /// The hasher uses a per-execution seed value that is set during process /// startup, usually from a high-quality random source. @_effects(releasenone) public init() { self._core = Core() } /// Initialize a new hasher using the specified seed value. /// The provided seed is mixed in with the global execution seed. @usableFromInline @_effects(releasenone) internal init(_seed: Int) { self._core = Core(seed: _seed) } /// Initialize a new hasher using the specified seed value. @usableFromInline // @testable @_effects(releasenone) internal init(_rawSeed: (UInt64, UInt64)) { self._core = Core(core: RawCore(rawSeed: _rawSeed)) } /// Indicates whether we're running in an environment where hashing needs to /// be deterministic. If this is true, the hash seed is not random, and hash /// tables do not apply per-instance perturbation that is not repeatable. /// This is not recommended for production use, but it is useful in certain /// test environments where randomization may lead to unwanted nondeterminism /// of test results. @inlinable internal static var _isDeterministic: Bool { @inline(__always) get { return _swift_stdlib_Hashing_parameters.deterministic } } /// The 128-bit hash seed used to initialize the hasher state. Initialized /// once during process startup. @inlinable // @testable internal static var _executionSeed: (UInt64, UInt64) { @inline(__always) get { // The seed itself is defined in C++ code so that it is initialized during // static construction. Almost every Swift program uses hash tables, so // initializing the seed during the startup seems to be the right // trade-off. return ( _swift_stdlib_Hashing_parameters.seed0, _swift_stdlib_Hashing_parameters.seed1) } } /// Adds the given value to this hasher, mixing its essential parts into the /// hasher state. /// /// - Parameter value: A value to add to the hasher. @inlinable @inline(__always) public mutating func combine<H: Hashable>(_ value: H) { value.hash(into: &self) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt64) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt32) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt16) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(_ value: UInt8) { _core.combine(value) } @_effects(releasenone) @usableFromInline internal mutating func _combine(bytes value: UInt64, count: Int) { _core.combine(bytes: value, count: count) } /// Adds the contents of the given buffer to this hasher, mixing it into the /// hasher state. /// /// - Parameter bytes: A raw memory buffer. @_effects(releasenone) public mutating func combine(bytes: UnsafeRawBufferPointer) { _core.combine(bytes: bytes) } /// Finalize the hasher state and return the hash value. /// Finalizing invalidates the hasher; additional bits cannot be combined /// into it, and it cannot be finalized again. @_effects(releasenone) @usableFromInline internal mutating func _finalize() -> Int { return Int(truncatingIfNeeded: _core.finalize()) } /// Finalizes the hasher state and returns the hash value. /// /// Finalizing consumes the hasher: it is illegal to finalize a hasher you /// don't own, or to perform operations on a finalized hasher. (These may /// become compile-time errors in the future.) /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. /// /// - Returns: The hash value calculated by the hasher. @_effects(releasenone) public __consuming func finalize() -> Int { var core = _core return Int(truncatingIfNeeded: core.finalize()) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt64) -> Int { var core = RawCore(seed: seed) core.compress(value) let tbc = _HasherTailBuffer(tail: 0, byteCount: 8) return Int(truncatingIfNeeded: core.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash(seed: Int, _ value: UInt) -> Int { var core = RawCore(seed: seed) #if arch(i386) || arch(arm) _sanityCheck(UInt.bitWidth < UInt64.bitWidth) let tbc = _HasherTailBuffer( tail: UInt64(truncatingIfNeeded: value), byteCount: UInt.bitWidth &>> 3) #else _sanityCheck(UInt.bitWidth == UInt64.bitWidth) core.compress(UInt64(truncatingIfNeeded: value)) let tbc = _HasherTailBuffer(tail: 0, byteCount: 8) #endif return Int(truncatingIfNeeded: core.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes value: UInt64, count: Int) -> Int { _sanityCheck(count >= 0 && count < 8) var core = RawCore(seed: seed) let tbc = _HasherTailBuffer(tail: value, byteCount: count) return Int(truncatingIfNeeded: core.finalize(tailAndByteCount: tbc.value)) } @_effects(readnone) @usableFromInline internal static func _hash( seed: Int, bytes: UnsafeRawBufferPointer) -> Int { var core = Core(seed: seed) core.combine(bytes: bytes) return Int(truncatingIfNeeded: core.finalize()) } }
apache-2.0
08c4cb0cb10100d84fd667e0b1c4dd56
30.961382
80
0.651828
4.043456
false
false
false
false
anjlab/SafeURL
Pod/Classes/SwiftURL.swift
1
6465
import Foundation // Creates URLPathSegmentAllowedCharacterSet same as URLPathAllowedCharacterSet - "/" private func _createURLPathSegmentAllowedCharacterSet() -> CharacterSet { let pathSegmentCharacterSet = (CharacterSet.urlPathAllowed as NSCharacterSet) .mutableCopy() as! NSMutableCharacterSet pathSegmentCharacterSet.removeCharacters(in: "/") return pathSegmentCharacterSet as CharacterSet } // Global var with URLPathSegmentAllowedCharacterSet to reduce private let _URLPathSegmentAllowedCharacterSet = _createURLPathSegmentAllowedCharacterSet() private func _pathSegmentsToPath(_ segments: [Any]?) -> String? { guard let segments = segments else { return nil } return segments.map { "\($0)" .addingPercentEncoding(withAllowedCharacters: _URLPathSegmentAllowedCharacterSet) ?? "\($0)" }.joined(separator: "/") } // Encode complex key/value objects in NSRULQueryItem pairs private func _queryItems(_ key: String, _ value: Any?) -> [URLQueryItem] { var result = [] as [URLQueryItem] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { result += _queryItems("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { let arrKey = key + "[]" for value in array { result += _queryItems(arrKey, value) } } else if let _ = value as? NSNull { result.append(URLQueryItem(name: key, value: nil)) } else if let v = value { result.append(URLQueryItem(name: key, value: "\(v)")) } else { result.append(URLQueryItem(name: key, value: nil)) } return result } // Encodes complex [String: AnyObject] params into array of NSURLQueryItem private func _paramsToQueryItems(_ params: [String: Any]?) -> [URLQueryItem]? { guard let params = params else { return nil } var result = [] as [URLQueryItem] for (key, value) in params { result += _queryItems(key, value) } return result.sorted(by: { $0.name < $1.name }) } public extension URLComponents { // MARK: path as String @nonobjc init(path: String, query: String?, fragment: String? = nil) { self.init() self.path = path self.query = query self.fragment = fragment } @nonobjc init(path: String, queryItems: [URLQueryItem]?, fragment: String? = nil) { self.init() self.path = path self.queryItems = queryItems self.fragment = fragment } @nonobjc init(path: String, query: [String: Any]?, fragment: String? = nil) { self.init() self.path = path self.queryItems = _paramsToQueryItems(query) self.fragment = fragment } // MARK: path as array of segments @nonobjc init(path segments: [Any]?, query: String?, fragment: String? = nil) { self.init() if let encodedPath = _pathSegmentsToPath(segments) { self.percentEncodedPath = encodedPath } self.query = query self.fragment = fragment } @nonobjc init(path segments: [Any]?, query: [String: Any]?, fragment: String? = nil) { self.init() if let encodedPath = _pathSegmentsToPath(segments) { self.percentEncodedPath = encodedPath } self.queryItems = _paramsToQueryItems(query) self.fragment = fragment } } public extension URL { static func build(_ baseURL: URL? = nil, components: URLComponents) -> URL? { return components.url(relativeTo: baseURL)?.absoluteURL } func build(_ components: URLComponents) -> URL? { return components.url(relativeTo: self)?.absoluteURL } static func build(_ baseURL: URL? = nil, path: String, query: String, fragment: String? = nil) -> URL? { return build(baseURL, components: URLComponents(path: path, query: query, fragment: fragment)) } func build(_ path: String, query: String, fragment: String? = nil) -> URL? { return build(URLComponents(path: path, query: query, fragment: fragment)) } static func build(_ baseURL: URL? = nil, path: String, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { return build(baseURL, components: URLComponents(path: path, query: query, fragment: fragment)) } func build(_ path: String, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { return build(URLComponents(path: path, query: query, fragment: fragment)) } static func build(_ baseURL: URL? = nil, path: [Any]? = nil, query: String, fragment: String? = nil) -> URL? { return build(baseURL, components: URLComponents(path: path, query: query, fragment: fragment)) } func build(_ path: [Any]? = nil, query: String, fragment: String? = nil) -> URL? { return build(URLComponents(path: path, query: query, fragment: fragment)) } static func build(_ baseURL: URL? = nil, path: [Any]? = nil, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { return build(baseURL, components: URLComponents(path: path, query: query, fragment: fragment)) } func build(_ path: [Any]? = nil, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { return build(URLComponents(path: path, query: query, fragment: fragment)) } static func build(scheme: String?, host: String? = nil, port: Int? = nil, path: String, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { var components = URLComponents(path: path, query: query, fragment: fragment) components.scheme = scheme components.host = host components.port = port return components.url } static func build(scheme: String?, host: String? = nil, port: Int? = nil, path: [Any]? = nil, query: [String: Any]? = nil, fragment: String? = nil) -> URL? { var components = URLComponents(path: path, query: query, fragment: fragment) components.scheme = scheme components.host = host components.port = port return components.url } }
mit
1483f61d00caa6c68c1fed941b1146fe
32.324742
161
0.599072
4.391984
false
false
false
false
valdyr/WeatherForecast
WeatherForecast/Common/Extensions/Extensions.swift
1
1318
// // Extensions.swift // WeatherForecast // // Created by Valeriy Dyryavyy on 22/08/2016. // Copyright © 2016 Valeriy Dyryavyy. All rights reserved. // import UIKit // TODO: - Danger! Watch out for extensions file to grow exponentially and becoming a dump. Proper consideration and grouping by responsibility required. extension UIView { static func nibName() -> String { return NSStringFromClass(self).componentsSeparatedByString(".").last! } } extension NSDate { func defaultFormattedDateString() -> String { return NSDateFormatter.DefaultDateFormatter.stringFromDate(self) } func shortFormattedDateString() -> String { return NSDateFormatter.ShortDateFormatter.stringFromDate(self) } } extension String { func defautFormattedDate() -> NSDate? { return NSDateFormatter.DefaultDateFormatter.dateFromString(self) } } extension NSDateFormatter { private static let DefaultDateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() private static let ShortDateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateFormat = "MMM d, H:mm a" return formatter }() }
gpl-3.0
8dc0afde504cd75892ea3d3dd5fc59c3
26.4375
155
0.692483
4.73741
false
false
false
false
AugustRush/Stellar
Sources/TimingFunction.swift
1
5784
//Copyright (c) 2016 // //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 /// A set of preset bezier curves. public enum TimingFunctionType { /// Equivalent to `kCAMediaTimingFunctionDefault`. case `default` /// Equivalent to `kCAMediaTimingFunctionEaseIn`. case easeIn /// Equivalent to `kCAMediaTimingFunctionEaseOut`. case easeOut /// Equivalent to `kCAMediaTimingFunctionEaseInEaseOut`. case easeInEaseOut /// No easing. case linear /// Inspired by the default curve in Google Material Design. case swiftOut /// case backEaseIn /// case backEaseOut /// case backEaseInOut /// case bounceOut /// case sine /// case circ /// case exponentialIn /// case exponentialOut /// case elasticIn /// case bounceReverse /// case elasticOut /// custom case custom(Double, Double, Double, Double) func easing() -> TimingSolvable { switch self { case .default: return UnitBezier(p1x: 0.25, p1y: 0.1, p2x: 0.25, p2y: 1.0) case .easeIn: return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 1.0, p2y: 1.0) case .easeOut: return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 0.58, p2y: 1.0) case .easeInEaseOut: return UnitBezier(p1x: 0.42, p1y: 0.0, p2x: 0.58, p2y: 1.0) case .linear: return UnitBezier(p1x: 0.0, p1y: 0.0, p2x: 1.0, p2y: 1.0) case .swiftOut: return UnitBezier(p1x: 0.4, p1y: 0.0, p2x: 0.2, p2y: 1.0) case .backEaseIn: return EasingContainer(easing: { (t: Double) in return t * t * t - t * sin(t * .pi) }) case .backEaseOut: return EasingContainer(easing: { (t: Double) in let f = (1 - t); return 1 - (f * f * f - f * sin(f * .pi)); }) case .backEaseInOut: return EasingContainer(easing: { (t: Double) in if(t < 0.5) { let f = 2 * t; return 0.5 * (f * f * f - f * sin(f * .pi)); } else { let f = (1.0 - (2.0 * t - 1.0)); let cubic = f * f * f return 0.5 * (1.0 - (cubic - f * sin(f * .pi))) + 0.5; } }) case .bounceOut: return EasingContainer(easing: { (t: Double) in if(t < 4/11.0){ return (121 * t * t)/16.0; } else if(t < 8/11.0){ return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0; }else if(t < 9/10.0){ return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0; }else{ return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0; } }) case .sine: return EasingContainer(easing: { (t: Double) in return 1 - cos( t * .pi / 2.0) }) case .circ: return EasingContainer(easing: { (t: Double) in return 1 - sqrt( 1.0 - t * t ) }) case .exponentialIn: return EasingContainer(easing: { (t: Double) in return (t == 0.0) ? t : pow(2, 10 * (t - 1)) }) case .exponentialOut: return EasingContainer(easing: { (t: Double) in return (t == 1.0) ? t : 1 - pow(2, -10 * t) }) case .elasticIn: return EasingContainer(easing: { (t: Double) in return sin(13.0 * (.pi / 2.0) * t) * pow(2, 10 * (t - 1)) }) case .elasticOut: return EasingContainer(easing: { (t: Double) in return sin(-13.0 * (.pi / 2.0) * (t + 1)) * pow(2, -10 * t) + 1.0; }) case .bounceReverse: return EasingContainer(easing: { (t: Double) in var bounce: Double = 4.0 var pow2 = 0.0 repeat { bounce = bounce - 1.0 pow2 = pow(2, bounce) } while (t < (pow2 - 1.0 ) / 11.0) return 1 / pow( 4, 3 - bounce ) - 7.5625 * pow( ( pow2 * 3 - 2 ) / 22 - t, 2 ); }) case .custom(let p1x,let p1y,let p2x,let p2y): return UnitBezier(p1x: p1x, p1y: p1y, p2x: p2x, p2y: p2y) } } } class EasingContainer: TimingSolvable { let easing: (Double) -> Double init(easing: @escaping (Double) -> Double) { self.easing = easing } // func solveOn(_ time: Double, epslion: Double) -> Double { return self.easing(time) } }
mit
f6b1b52f01a3bb1f985760ea82043ea7
36.076923
462
0.51677
3.724404
false
false
false
false
dDetected/iosSeed
Project/Numbers/CameraTestViewController.swift
1
1264
// // CameraTestViewController.swift // Numbers // // Created by Michael Filippov on 17/11/2016. // Copyright © 2016 Anton Spivak. All rights reserved. // import Foundation import AVFoundation class CameraTestViewController : UIViewController { var camera: DMCameraProcessing? @IBOutlet weak var outputView: UIImageView! override func viewDidLoad() { super.viewDidLoad() camera = DMCameraProcessing(outputImageView: outputView) } override func viewWillAppear(_ animated: Bool) { checkPermission() { self.camera?.startCapture() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) camera?.stopCapture() } func checkPermission(withBlock block: @escaping () -> ()) { let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) if status == .notDetermined { AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted) in if granted { block() } }) } else if status == .authorized { block() } } }
apache-2.0
98aecfaa61b2f8011ad57b32d9fbb85d
23.764706
107
0.601742
5.284519
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Models/ReaderSaveForLaterTopic.swift
1
1404
/// Plese do not review this class. This is basically a mock at the moment. It models a mock topic, so that I can test that the topic gets rendered in the UI final class ReaderSaveForLaterTopic: ReaderAbstractTopic { init() { let managedObjectContext = ReaderSaveForLaterTopic.setUpInMemoryManagedObjectContext() let entity = NSEntityDescription.entity(forEntityName: "ReaderDefaultTopic", in: managedObjectContext) super.init(entity: entity!, insertInto: managedObjectContext) } override open class var TopicType: String { return "saveForLater" } /// TODO. This function will have to go away static func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext { let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])! let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil) } catch { print("Adding in-memory persistent store failed") } let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator return managedObjectContext } }
gpl-2.0
47fe8afb941ad9299d7cb2d804b16e0a
45.8
157
0.740741
6.104348
false
false
false
false
jairoeli/Habit
Zero/Sources/Views/Controllers/BaseViewController.swift
1
2189
// // BaseViewController.swift // Zero // // Created by Jairo Eli de Leon on 5/8/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import UIKit import RxSwift class BaseViewController: UIViewController { // MARK: - Properties lazy private(set) var className: String = { return type(of: self).description().components(separatedBy: ".").last ?? "" }() var automaticallyAdjustsLeftBarButtonItem = true // MARK: - Initializing init() { super.init(nibName: nil, bundle: nil) } required convenience init?(coder aDecoder: NSCoder) { self.init() } deinit { log.verbose("DEINIT: \(self.className)") } // MARK: - Rx var disposeBag = DisposeBag() // MARK: - View Lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.automaticallyAdjustsLeftBarButtonItem { self.adjustLeftBarButtonItem() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) dch_checkDeallocation() } // MARK: - Layout Constraints private(set) var didSetupConstraints = false override func viewDidLoad() { self.view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if !self.didSetupConstraints { self.setupConstraints() self.didSetupConstraints = true } super.updateViewConstraints() } func setupConstraints() { // Override point } // MARK: - Adjusting Navigation Item func adjustLeftBarButtonItem() { if self.navigationController?.viewControllers.count ?? 0 > 1 { // pushed self.navigationItem.rightBarButtonItem = nil } else if self.presentingViewController != nil { // presented self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "cancel"), style: .plain, target: self, action: #selector(cancelButtonDidTap)) } } @objc func cancelButtonDidTap() { self.dismiss(animated: true, completion: nil) } }
mit
5ab0114a3d2afa7d604abdd70eb832ac
24.729412
108
0.631001
4.914607
false
false
false
false
mvandervelden/iOSSystemIntegrationsDemo
SearchDemo/DataModel/DataFactory.swift
2
1260
import Foundation import CoreData class DataFactory { var managedObjectContext : NSManagedObjectContext { return DataController.sharedInstance.managedObjectContext } func createNote(timestamp: NSDate, text: String) -> Note { let note = NSEntityDescription.insertNewObjectForEntityForName("Note", inManagedObjectContext: managedObjectContext) as! Note note.timestamp = timestamp note.text = text note.id = NSUUID().UUIDString note.index() return note } func createImage(timestamp: NSDate, title: String, url: String) -> Image { let image = NSEntityDescription.insertNewObjectForEntityForName("Image", inManagedObjectContext: managedObjectContext) as! Image image.timestamp = timestamp image.title = title image.url = url image.index() return image } func createContact(name: String, phone: String, email: String) -> Contact { let contact = NSEntityDescription.insertNewObjectForEntityForName("Contact", inManagedObjectContext: managedObjectContext) as! Contact contact.name = name contact.phone = phone contact.email = email contact.index() return contact } }
mit
98cac8e74dfe48e0e9e1ded7e38466fe
35
142
0.680159
5.701357
false
false
false
false
skibadawid/DS-Stuff
DS Stuff/The Stuff/Helpers:Extensions/DSNavigationControllerHelper.swift
1
1929
// // NavigationControllerHelper.swift // Recipe Stack // // Created by Dawid Skiba on 3/26/17. // Copyright © 2017 Dawid Skiba. All rights reserved. // import Foundation extension UINavigationController { func dsBackViewController() -> UIViewController? { let count = self.viewControllers.count if (count < 2) { return nil } return self.viewControllers[count - 2] } } extension UINavigationItem { func dsAddToLeftSideBarButton(_ button: UIBarButtonItem, leftPosition: Bool, animated: Bool) { // check if let lefties = self.leftBarButtonItems { if lefties.contains(button) { return } } var leftButtons: [UIBarButtonItem] = self.leftBarButtonItems ?? [UIBarButtonItem]() if leftPosition { leftButtons.append(button) } else { leftButtons.insert(button, at: 0) } self.leftBarButtonItems = leftButtons } func dsAddToRightSideBarButton(_ button: UIBarButtonItem, leftPosition: Bool, animated: Bool) { // check if let righties = self.rightBarButtonItems { if righties.contains(button) { return } } var rightButtons: [UIBarButtonItem] = self.rightBarButtonItems ?? [UIBarButtonItem]() if leftPosition { rightButtons.append(button) } else { rightButtons.insert(button, at: 0) } self.rightBarButtonItems = rightButtons } func dsSetAllButtonsEnabled(_ enabled: Bool = true) { if let leftButtons = self.leftBarButtonItems { for left in leftButtons { left.isEnabled = enabled } } if let rightButtons = self.rightBarButtonItems { for right in rightButtons { right.isEnabled = enabled } } } }
mit
3f2b0d7d1f20a18b042cea15c00ff957
26.542857
99
0.588174
5.073684
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Graphic/PolygonGraphic.swift
1
5184
// // PolygonGraphic.swift // SwiftyEcharts // // Created by Pluto Y on 12/02/2017. // Copyright © 2017 com.pluto-y. All rights reserved. // /// 多边形类型的 `Graphic` public final class PolygonGraphic: Graphic { /// 多边形的位置和大小定义 public final class Shape { /// 是否平滑曲线 /// /// - val: 如果为 val:表示贝塞尔 (bezier) 差值平滑,smooth 指定了平滑等级,范围 [0, 1]。 /// - spline: 如果为 'spline':表示 Catmull-Rom spline 差值平滑。 public enum Smooth: Jsonable { case val(Float) case spline public var jsonString: String { switch self { case let .val(val): return "\(val)" case .spline: return "\"spline\"" } } } /// 点列表,用于定义形状,如 [[22, 44], [44, 55], [11, 44], ...] public var point: [Point]? /// 是否平滑曲线 public var smooth: Smooth? /// 是否将平滑曲线约束在包围盒中。smooth 为 number(bezier)时生效。 public var smoothConstraint: Bool? public init() {} } /// MARK: Graphic public var type: GraphicType { return .polygon } public var id: String? public var action: GraphicAction? public var left: Position? public var right: Position? public var top: Position? public var bottom: Position? public var bounding: GraphicBounding? public var z: Float? public var zlevel: Float? public var silent: Bool? public var invisible: Bool? public var cursor: String? public var draggable: Bool? public var progressive: Bool? /// 多边形的位置和大小定义 public var shape: Shape? /// 多边形的样式 public var style: CommonGraphicStyle? public init() {} } extension PolygonGraphic.Shape: Enumable { public enum Enums { case point([Point]), smooth(Smooth), smoothConstraint(Bool) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .point(point): self.point = point case let .smooth(smooth): self.smooth = smooth case let .smoothConstraint(smoothConstraint): self.smoothConstraint = smoothConstraint } } } } extension PolygonGraphic.Shape: Mappable { public func mapping(_ map: Mapper) { map["point"] = point map["smooth"] = smooth map["smoothConstraint"] = smoothConstraint } } extension PolygonGraphic: Enumable { public enum Enums { case id(String), action(GraphicAction), left(Position), right(Position), top(Position), bottom(Position), bounding(GraphicBounding), z(Float), zlevel(Float), silent(Bool), invisible(Bool), cursor(String), draggable(Bool), progressive(Bool), shape(Shape), style(CommonGraphicStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .id(id): self.id = id case let .action(action): self.action = action case let .left(left): self.left = left case let .right(right): self.right = right case let .top(top): self.top = top case let .bottom(bottom): self.bottom = bottom case let .bounding(bounding): self.bounding = bounding case let .z(z): self.z = z case let .zlevel(zlevel): self.zlevel = zlevel case let .silent(silent): self.silent = silent case let .invisible(invisible): self.invisible = invisible case let .cursor(cursor): self.cursor = cursor case let .draggable(draggable): self.draggable = draggable case let .progressive(progressive): self.progressive = progressive case let .shape(shape): self.shape = shape case let .style(style): self.style = style } } } } extension PolygonGraphic: Mappable { public func mapping(_ map: Mapper) { map["type"] = type map["id"] = id map["$action"] = action map["left"] = left map["right"] = right map["top"] = top map["bottom"] = bottom map["bounding"] = bounding map["z"] = z map["zlevel"] = zlevel map["silent"] = silent map["invisible"] = invisible map["cursor"] = cursor map["draggable"] = draggable map["progressive"] = progressive map["shape"] = shape map["style"] = style } }
mit
299030c90d9900d2e6941b5e2b6deb13
28.470238
288
0.530802
4.500909
false
false
false
false
roambotics/swift
test/Interop/Cxx/operators/non-member-inline-typechecker.swift
2
1157
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop import NonMemberInline let lhs = LoadableIntWrapper(value: 42) let rhs = LoadableIntWrapper(value: 23) let resultPlus = lhs + rhs let resultMinus = lhs - rhs let resultStar = lhs * rhs let resultSlash = lhs / rhs let resultPercent = lhs % rhs let resultCaret = lhs ^ rhs let resultAmp = lhs & rhs let resultPipe = lhs | rhs let resultLessLess = lhs << rhs let resultGreaterGreater = lhs >> rhs let resultLess = lhs < rhs let resultGreater = lhs > rhs let resultEqualEqual = lhs == rhs let resultExclaimEqual = lhs != rhs let resultLessEqual = lhs <= rhs let resultGreaterEqual = lhs >= rhs var lhsMutable = LoadableIntWrapper(value: 42) lhsMutable /= rhs public func ==(ptr: UnsafePointer<UInt8>, count: Int) -> Bool { let lhs = UnsafeBufferPointer<UInt8>(start: ptr, count: count) let rhs = UnsafeBufferPointer<UInt8>(start: ptr, count: count) return lhs.elementsEqual(rhs, by: ==) } var lhsBool = LoadableBoolWrapper(value: true) var rhsBool = LoadableBoolWrapper(value: false) let resultAmpAmp = lhsBool && rhsBool let resultPipePipe = lhsBool && rhsBool
apache-2.0
7edf301e0747edaf6c9c1bc65a491e3b
28.666667
84
0.73898
3.582043
false
false
false
false
ngageoint/mage-ios
Mage/Feed/FeedItemViewController.swift
1
7934
// // FeedItemViewViewController.swift // MAGE // // Created by Daniel Barela on 6/15/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import Kingfisher import UIKit import MaterialComponents import PureLayout final class IntrinsicTableView: UITableView { override var contentSize: CGSize { didSet { invalidateIntrinsicContentSize() } } override var intrinsicContentSize: CGSize { layoutIfNeeded() return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height) } } @objc class FeedItemViewController : UIViewController { var didSetupConstraints = false; let HEADER_SECTION = 0; let PROPERTIES_SECTION = 1; let cellReuseIdentifier = "propertyCell" let headerCellIdentifier = "headerCell" var scheme: MDCContainerScheming?; var feedItem : FeedItem? var properties: [String: Any]? let propertiesHeader: CardHeader = CardHeader(headerText: "PROPERTIES"); private lazy var propertiesCard: MDCCard = { let card = MDCCard(); card.addSubview(tableView); return card; }() private lazy var tableView : IntrinsicTableView = { let tableView = IntrinsicTableView(frame: CGRect.zero, style: .plain); tableView.allowsSelection = false; tableView.delegate = self tableView.dataSource = self tableView.isScrollEnabled = false; tableView.register(FeedItemPropertyCell.self, forCellReuseIdentifier: cellReuseIdentifier) return tableView; }() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView.newAutoLayout(); scrollView.accessibilityIdentifier = "card scroll"; scrollView.contentInset.bottom = 100; return scrollView; }() private lazy var stackView: UIStackView = { let stackView = UIStackView.newAutoLayout(); stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = 8 stackView.distribution = .fill stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8) stackView.isLayoutMarginsRelativeArrangement = true; return stackView; }() override func updateViewConstraints() { if (!didSetupConstraints) { scrollView.autoPinEdgesToSuperviewEdges(with: .zero); stackView.autoPinEdgesToSuperviewEdges(); stackView.autoMatch(.width, to: .width, of: view); tableView.autoPinEdgesToSuperviewEdges(); propertiesCard.autoMatch(.height, to: .height, of: tableView); didSetupConstraints = true; } super.updateViewConstraints(); } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect) { super.init(nibName: nil, bundle: nil); } @objc convenience public init(feedItem:FeedItem, scheme: MDCContainerScheming?) { self.init(frame: CGRect.zero); self.scheme = scheme; self.feedItem = feedItem self.properties = feedItem.properties as? [String: Any]; self.applyTheme(withScheme: scheme); } override func loadView() { view = UIView(); view.addSubview(scrollView); scrollView.addSubview(stackView); view.setNeedsUpdateConstraints(); } public func applyTheme(withScheme scheme: MDCContainerScheming? = nil) { guard let scheme = scheme else { return } self.view.backgroundColor = scheme.colorScheme.backgroundColor; propertiesHeader.applyTheme(withScheme: scheme); propertiesCard.applyTheme(withScheme: scheme); tableView.backgroundColor = .clear; } override func viewDidLoad() { super.viewDidLoad(); let cell: FeedItemCard = FeedItemCard(item: feedItem, actionsDelegate: self, hideSummaryImage: true); cell.applyTheme(withScheme: self.scheme); self.stackView.addArrangedSubview(cell); self.stackView.addArrangedSubview(propertiesHeader); self.stackView.addArrangedSubview(propertiesCard); } } extension FeedItemViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView(); } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension; } } extension FeedItemViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return properties?.count ?? 0; } func numberOfSections(in: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: FeedItemPropertyCell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! FeedItemPropertyCell; cell.applyTheme(withScheme: self.scheme); let key = properties?.keys.sorted()[indexPath.row] ?? "" if let itemPropertiesSchema = feedItem?.feed?.itemPropertiesSchema as? [String : Any], let propertySchema = itemPropertiesSchema["properties"] as? [String : Any], let keySchema = propertySchema[key] as? [String : Any] { cell.keyField.text = keySchema["title"] as? String } else { cell.keyField.text = key } cell.valueField.text = feedItem?.valueForKey(key: key) ?? ""; return cell } } extension FeedItemViewController: FeedItemActionsDelegate { func getDirectionsToFeedItem(_ feedItem: FeedItem, sourceView: UIView? = nil) { var extraActions: [UIAlertAction] = []; extraActions.append(UIAlertAction(title:"Bearing", style: .default, handler: { (action) in var image = UIImage.init(named: "observations")?.withRenderingMode(.alwaysTemplate).colorized(color: globalContainerScheme().colorScheme.primaryColor); if let url: URL = feedItem.iconURL { let size = 24; let processor = DownsamplingImageProcessor(size: CGSize(width: size, height: size)) KingfisherManager.shared.retrieveImage(with: url, options: [ .requestModifier(ImageCacheProvider.shared.accessTokenModifier), .processor(processor), .scaleFactor(UIScreen.main.scale), .transition(.fade(1)), .cacheOriginalImage ]) { result in switch result { case .success(let value): image = value.image.aspectResize(to: CGSize(width: size, height: size)); case .failure(_): image = UIImage.init(named: "observations")?.withRenderingMode(.alwaysTemplate).colorized(color: globalContainerScheme().colorScheme.primaryColor); } } } NotificationCenter.default.post(name: .StartStraightLineNavigation, object:StraightLineNavigationNotification(image: image, coordinate: feedItem.coordinate, feedItem: feedItem)) })); ObservationActionHandler.getDirections(latitude: feedItem.coordinate.latitude, longitude: feedItem.coordinate.longitude, title: feedItem.title ?? "Feed item", viewController: self, extraActions: extraActions, sourceView: sourceView); } func copyLocation(_ location: String) { UIPasteboard.general.string = location; MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Location \(location) copied to clipboard")) } }
apache-2.0
355f99e1581c1d05246392ead412ebc1
36.419811
241
0.650826
5.360135
false
false
false
false
silt-lang/silt
Sources/Boring/Optimize.swift
1
2424
/// Optimize.swift /// /// Copyright 2017-2018, The Silt Language Project. /// /// This project is released under the MIT license, a copy of which is /// available in the repository. import Foundation import Basic import SPMUtility import Mantle import Drill import OuterCore public final class OptimizeToolOptions: SiltToolOptions { public var passes: [String] = [] public var inputURLs: [Foundation.URL] = [] } public class SiltOptimizeTool: SiltTool<OptimizeToolOptions> { public convenience init(_ args: [String]) { self.init( toolName: "optimize", usage: "[options]", overview: "Run optimization pipelines on Silt source code", args: args ) } private func translateOptions() -> Options { return Options(mode: .dump(.girGen), colorsEnabled: false, shouldPrintTiming: false, inputURLs: self.options.inputURLs, target: nil, typeCheckerDebugOptions: []) } override func runImpl() throws { let invocation = Invocation(options: translateOptions()) let hadErrors = invocation.runToGIRGen { mod in let pipeliner = PassPipeliner(module: mod) pipeliner.addStage("User-Selected Passes") { p in for name in self.options.passes { guard let cls = NSClassFromString("OuterCore.\(name)") else { print("Could not find pass named '\(name)'") continue } guard let pass = cls as? OptimizerPass.Type else { print("Could not find pass named '\(name)'") continue } p.add(pass) } } pipeliner.execute() } if hadErrors { self.executionStatus = .failure } else { self.executionStatus = .success } } override class func defineArguments( parser: ArgumentParser, binder: ArgumentBinder<OptimizeToolOptions> ) { binder.bindArray( option: parser.add(option: "--pass", kind: [String].self), to: { opt, passes in return opt.passes.append(contentsOf: passes) }) binder.bindArray( positional: parser.add( positional: "", kind: [String].self, usage: "One or more input file(s)", completion: .filename), to: { opt, fs in let url = fs.map(URL.init(fileURLWithPath:)) return opt.inputURLs.append(contentsOf: url) }) } }
mit
45471986a2c25ab1ceaa4cd562f12ca4
26.862069
71
0.611386
4.328571
false
false
false
false
ajaybeniwal/SwiftTransportApp
TransitFare/TransitFare/RegisterViewController.swift
1
8367
// // RegisterViewController.swift // TransitFare // // Created by ajaybeniwal203 on 7/2/16. // Copyright © 2016 ajaybeniwal203. All rights reserved. // import UIKit import SnapKit import MBProgressHUD import Material import Parse class RegisterViewController: UIViewController { var backgroundImageView : UIImageView? var userNameTextField: UITextField? var phoneNumberTextField:UITextField? var passwordTextField:UITextField? var frostedView :UIView? var registerButton:RaisedButton? var isAlreadyLoggedinButton : UIButton? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() self.backgroundImageView = UIImageView(image: UIImage(named: "background-logo.jpg")) self.backgroundImageView!.frame = self.view.frame self.backgroundImageView!.contentMode = .ScaleToFill self.view.addSubview(self.backgroundImageView!) frostedView = UIView() frostedView!.frame = self.view.frame self.view.addSubview(frostedView!) self.userNameTextField = UITextField() self.userNameTextField!.textColor = UIColor.blackColor() self.userNameTextField!.backgroundColor = UIColor(white: 1, alpha: 0.6); self.userNameTextField!.layer.borderWidth = 0.5 self.userNameTextField!.keyboardType = .ASCIICapable self.userNameTextField!.layer.borderColor = UIColor(white: 1, alpha: 0.8).CGColor; self.userNameTextField!.placeholder = "UserName" self.userNameTextField!.clearButtonMode = .Always let userNameIconImageView = UIImageView(image: UIImage(named: "username")!.imageWithRenderingMode(.AlwaysTemplate)); userNameIconImageView.frame = CGRectMake(30, 10, 24, 24) userNameIconImageView.contentMode = .ScaleAspectFit userNameIconImageView.tintColor = MaterialColor.grey.base self.userNameTextField!.leftView = userNameIconImageView self.userNameTextField!.leftViewMode = .Always frostedView!.addSubview(self.userNameTextField!) self.userNameTextField!.snp_makeConstraints{ (make) -> Void in make.centerX.equalTo(self.frostedView!) make.top.equalTo(self.frostedView!).offset(150) make.trailing.equalTo(self.frostedView!) make.leading.equalTo(self.frostedView!) make.height.equalTo(50) } self.phoneNumberTextField = UITextField() self.phoneNumberTextField!.textColor = UIColor.blackColor() self.phoneNumberTextField!.backgroundColor = UIColor(white: 1, alpha: 0.6); self.phoneNumberTextField!.layer.borderWidth = 0.5 self.phoneNumberTextField!.keyboardType = .ASCIICapable self.phoneNumberTextField!.layer.borderColor = UIColor(white: 1, alpha: 0.8).CGColor; self.phoneNumberTextField!.placeholder = "Phone Number" self.phoneNumberTextField!.clearButtonMode = .Always let phoneIconImageView = UIImageView(image: UIImage(named: "phone")!.imageWithRenderingMode(.AlwaysTemplate)); phoneIconImageView.frame = CGRectMake(30, 10, 24, 24) phoneIconImageView.contentMode = .ScaleAspectFit phoneIconImageView.tintColor = MaterialColor.grey.base self.phoneNumberTextField!.leftView = phoneIconImageView self.phoneNumberTextField!.leftViewMode = .Always frostedView!.addSubview(self.phoneNumberTextField!) self.phoneNumberTextField!.snp_makeConstraints{ (make) -> Void in make.top.equalTo(self.userNameTextField!.snp_bottom).offset(0) make.centerX.equalTo(self.frostedView!) make.leading.equalTo(self.frostedView!) make.height.equalTo(50) } self.passwordTextField = UITextField() self.passwordTextField!.textColor = UIColor.blackColor() self.passwordTextField!.backgroundColor = UIColor(white: 1, alpha: 0.6); self.passwordTextField!.layer.borderWidth = 0.5 self.passwordTextField!.keyboardType = .ASCIICapable self.passwordTextField!.secureTextEntry = true self.passwordTextField!.layer.borderColor = UIColor(white: 1, alpha: 0.8).CGColor; self.passwordTextField!.placeholder = "Password" self.passwordTextField!.clearButtonMode = .Always let passwordIconImage = UIImageView(image: UIImage(named: "password")!.imageWithRenderingMode(.AlwaysTemplate)); passwordIconImage.frame = CGRectMake(30, 10, 24, 24) passwordIconImage.contentMode = .ScaleAspectFit passwordIconImage.tintColor = MaterialColor.grey.base self.passwordTextField!.leftView = passwordIconImage self.passwordTextField!.leftViewMode = .Always frostedView!.addSubview(self.passwordTextField!) self.passwordTextField!.snp_makeConstraints{ (make) -> Void in make.top.equalTo(self.phoneNumberTextField!.snp_bottom).offset(0) make.centerX.equalTo(self.frostedView!) make.leading.equalTo(self.frostedView!) make.height.equalTo(50) } self.registerButton = RaisedButton() self.registerButton!.setTitle("Register", forState: .Normal) self.registerButton!.backgroundColor = MaterialColor.pink.base self.registerButton!.alpha = 0.8 frostedView!.addSubview(self.registerButton!) self.registerButton?.addTarget(self, action: #selector(self.registerClick(_:)), forControlEvents: .TouchUpInside) self.registerButton!.snp_makeConstraints{ (make) -> Void in make.top.equalTo(self.passwordTextField!.snp_bottom).offset(20) make.centerX.equalTo(self.frostedView!) make.width.equalTo(250) make.height.equalTo(50) } self.isAlreadyLoggedinButton = UIButton() self.isAlreadyLoggedinButton?.setTitle("Is already logged in?", forState: .Normal) self.isAlreadyLoggedinButton?.addTarget(self, action: #selector(self.alreadyLoggedIn(_:)), forControlEvents: .TouchUpInside) self.isAlreadyLoggedinButton?.titleLabel?.textColor = UIColor.whiteColor() frostedView!.addSubview(self.isAlreadyLoggedinButton!) self.isAlreadyLoggedinButton!.snp_makeConstraints{ (make) -> Void in make.top.equalTo(self.registerButton!.snp_bottom).offset(20) make.centerX.equalTo(self.frostedView!) make.width.equalTo(250) make.height.equalTo(50) } // Do any additional setup after loading the view. } func alreadyLoggedIn(sender:UIButton){ self.dismissViewControllerAnimated(true, completion: nil) } func registerClick(sender:UIButton){ //dismissViewControllerAnimated(true, completion:nil) let progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true) let user = PFUser() user.username = userNameTextField?.text user.password = passwordTextField?.text user.email = userNameTextField?.text user["phone"] = phoneNumberTextField?.text user.signUpInBackgroundWithBlock { (success,error) -> Void in progressHUD.hide(true) if let _ = error{ self.showAlert("Error", message: "Error while creating user") } else{ self.showAlertWithActionCallback("Success", message: "User created successfully", callback: { (action) -> Void in self.dismissViewControllerAnimated(true, completion: nil) }) } } } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
acfcc1f2eeade91d4eca1c2c4ea3e2db
42.123711
132
0.666985
5.161012
false
false
false
false
n41l/OMChartView
Example/OMChartView/OMKeyFrameAnimation.Function.swift
1
6949
// // OMKeyFrameAnimation.Function.swift // OMFlowingDrawer // // Created by HuangKun on 15/12/4. // Copyright © 2015年 HuangKun. All rights reserved. // import UIKit typealias AnimationFunc = (t: CGFloat) -> CGFloat struct OMAnimationFuntion { /// Modeled after the line y = x static var Liner: AnimationFunc = { t in t } /// Modeled after the parabola y = x^2 static var QuadraticEaseIn: AnimationFunc = { t in t * t } /// Modeled after the parabola y = -x^2 + 2x static var QuadraticEaseOut: AnimationFunc = { t in -(t * (t - 2)) } /// Modeled after the piecewise quadratic /// y = (1/2)((2x)^2) ; [0, 0.5) /// y = -(1/2)((2x-1)*(2x-3) - 1); [0.5, 1] static var QuadraticEaseInOut: AnimationFunc = { t in if t < 0.5 { return 2 * t * t }else { return -2 * t * t + 4 * t - 1 } } /// Modeled after the cubic y = x^3 static var CubicEaseIn: AnimationFunc = { t in t * t * t } /// Modeled after the cubic y = (x - 1)^3 + 1 static var CubicEaseOut: AnimationFunc = { t in let delta = t - 1 return delta * delta * delta + 1 } /// Modeled after the piecewise cubic /// y = (1/2)((2x)^3) ; [0, 0.5) /// y = (1/2)((2x-2)^3 + 2); [0.5, 1] static var CubicEaseInOut: AnimationFunc = { t in if t < 0.5 { return 4 * t * t * t }else { let delta = ((2 * t) - 2) return 0.5 * t * t * t + 1 } } /// Modeled after the quartic x^4 static var QuarticEaseIn: AnimationFunc = { t in t * t * t * t } /// Modeled after the quartic y = 1 - (x - 1)^4 static var QuarticEaseOut: AnimationFunc = { t in let delta = t - 1 return delta * delta * delta * (1 - t) + 1 } /// Modeled after the piecewise quartic /// y = (1/2)((2x)^4) ; [0, 0.5) /// y = -(1/2)((2x-2)^4 - 2); [0.5, 1] static var QuarticEaseInOut: AnimationFunc = { t in if t < 0.5 { return 8 * t * t * t * t }else { let delta = t - 1 return -8 * delta * delta * delta * delta + 1 } } /// Modeled after the quintic y = x^5 static var QuinticEaseIn: AnimationFunc = { t in t * t * t * t * t } // Modeled after the quintic y = (x - 1)^5 + 1 static var QuinticEaseOut: AnimationFunc = { t in let delta = t - 1 return delta * delta * delta * delta * delta + 1 } /// Modeled after the piecewise quintic /// y = (1/2)((2x)^5) ; [0, 0.5) /// y = (1/2)((2x-2)^5 + 2); [0.5, 1] static var QuinticEaseInOut: AnimationFunc = { t in if t < 0.5 { return 16 * t * t * t * t * t }else { let delta = ((2 * t) - 2) return 0.5 * t * t * t * t * t + 1 } } /// Modeled after quarter-cycle of sine wave static var SineEaseIn: AnimationFunc = { t in sin((t - 1) * CGFloat(M_PI_2)) + 1 } /// Modeled after quarter-cycle of sine wave (different phase) static var SineEaseOut: AnimationFunc = { t in sin(t * CGFloat(M_PI_2)) } /// Modeled after half sine wave static var SineEaseInOut: AnimationFunc = { t in 0.5 * (1 - cos(t * CGFloat(M_PI_2))) } /// Modeled after shifted quadrant IV of unit circle static var CircularEaseIn: AnimationFunc = { t in 1 - sqrt(1 - (t * t)) } /// Modeled after shifted quadrant II of unit circle static var CircularEaseOut: AnimationFunc = { t in sqrt((2 - t) * t) } /// Modeled after the piecewise circular function /// y = (1/2)(1 - sqrt(1 - 4x^2)) ; [0, 0.5) /// y = (1/2)(sqrt(-(2x - 3)*(2x - 1)) + 1); [0.5, 1] static var CircularEaseInOut: AnimationFunc = { t in if t < 0.5 { return 0.5 * (1 - sqrt(1 - 4 * (t * t))) }else { return 0.5 * (sqrt(-((2 * t) - 3) * ((2 * t) - 1)) + 1) } } /// Modeled after the exponential function y = 2^(10(x - 1)) static var ExponentialEaseIn: AnimationFunc = { t in t == 0.0 ? t : pow(2, 10 * (t - 1)) } /// Modeled after the exponential function y = -2^(-10x) + 1 static var ExponentialEaseOut: AnimationFunc = { t in t == 1.0 ? t : pow(2, -10 * t) } /// Modeled after the piecewise exponential /// y = (1/2)2^(10(2x - 1)) ; [0, 0.5) /// y = -(1/2)*2^(-10(2x - 1))) + 1; [0.5, 1] static var ExponentialEaseInOut: AnimationFunc = { t in if t == 0.0 || t == 1.0 { return t } if t < 0.5 { return 0.5 * pow(2, 20 * t - 10) }else { return -0.5 * pow(2, (-20 * t) + 10) + 1 } } /// Modeled after the damped sine wave y = sin(13pi/2*x)*pow(2, 10 * (x - 1)) static var ElasticEaseIn: AnimationFunc = { t in sin(13 * CGFloat(M_PI_2) * t) * pow(2, 10 * (t - 1)) } /// Modeled after the damped sine wave y = sin(-13pi/2*(x + 1))*pow(2, -10x) + 1 static var ElasticEaseOut: AnimationFunc = { t in sin(-13 * CGFloat(M_PI_2) * (t + 1)) * pow(2, -10 * t) + 1 } /// Modeled after the piecewise exponentially-damped sine wave: /// y = (1/2)*sin(13pi/2*(2*x))*pow(2, 10 * ((2*x) - 1)) ; [0, 0.5) /// y = (1/2)*(sin(-13pi/2*((2x-1)+1))*pow(2,-10(2*x-1)) + 2); [0.5, 1] static var ElasticEaseInOut: AnimationFunc = { t in if t < 0.5 { return 0.5 * sin(13 * CGFloat(M_PI_2) * 2 * t) * pow(2, 10 * ((2 * t) - 1)) }else { return 0.5 * (sin(-13 * CGFloat(M_PI_2) * ((2 * t - 1) + 1)) * pow(2, -10 * (2 * t - 1)) + 2) } } /// Modeled after the overshooting cubic y = x^3-x*sin(x*pi) static var BackEaseIn: AnimationFunc = { t in t * t * t - t * sin(t * CGFloat(M_PI)) } /// Modeled after overshooting cubic y = 1-((1-x)^3-(1-x)*sin((1-x)*pi)) static var BackEaseOut: AnimationFunc = { t in let delta = 1 - t return 1 - (delta * delta * delta - delta * sin(delta * CGFloat(M_PI))) } /// Modeled after the piecewise overshooting cubic function: /// y = (1/2)*((2x)^3-(2x)*sin(2*x*pi)) ; [0, 0.5) /// y = (1/2)*(1-((1-x)^3-(1-x)*sin((1-x)*pi))+1); [0.5, 1] static var BackEaseInOut: AnimationFunc = { t in if t < 0.5 { let delta = 2 * t return 0.5 * (delta * delta * delta - delta * sin(delta * CGFloat(M_PI))) }else { let delta = 1 - (2 * t - 1) let temp1 = delta * delta * delta let temp2 = sin(delta * CGFloat(M_PI)) return 0.5 * (1 - (temp1 - delta * temp2)) + 0.5 } } static var BounceEaseOut: AnimationFunc = { t in if t < 4/11.0 { return (121 * t * t)/16.0 }else if t < 8/11.0 { return (363/40.0 * t * t) - (99/10.0 * t) + 17/5.0 }else if t < 9/10.0 { return (4356/361.0 * t * t) - (35442/1805.0 * t) + 16061/1805.0 }else { return (54/5.0 * t * t) - (513/25.0 * t) + 268/25.0 } } static var BounceEaseIn: AnimationFunc = { t in 1 - OMAnimationFuntion.BounceEaseOut(t: t) } static var BounceEaseInOut: AnimationFunc = { t in if t < 0.5 { return 0.5 * OMAnimationFuntion.BounceEaseIn(t: t * 2) }else { return 0.5 * OMAnimationFuntion.BounceEaseOut(t: t * 2 - 1) + 0.5 } } }
mit
6de763e4ecf0492f6fffb8226fdf6b44
31.919431
99
0.533257
2.818994
false
false
false
false
cornerstonecollege/402
boyoung_chae/GestureRecognizer/CustomViews/FirstCustomView.swift
2
1519
// // FirstCustomView.swift // CustomViews // // Created by Boyoung on 2016-10-13. // Copyright © 2016 Boyoung. All rights reserved. // import UIKit class FirstCustomView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.red // default background color let label = UILabel() label.text = "Name" label.sizeToFit() label.center = CGPoint(x: self.frame.size.width / 2, y: 10) self.addSubview(label) let txtFrame = CGRect(x: (self.frame.size.width - 40) / 2, y: 50, width: 40, height: 20) let textView = UITextField(frame: txtFrame) textView.backgroundColor = UIColor.white self.addSubview(textView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("touches began") } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { self.center = touches.first!.location(in: self.superview) print("touches moved") } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print("touches ended") } }
gpl-3.0
e2cd7d1ecb891a000acf96ca3be1c8b6
28.192308
96
0.61726
4.288136
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PremiumFeatureSlideView.swift
1
5937
// // PremiumFeatureSlideView.swift // Telegram // // Created by Mike Renoir on 13.06.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import TGUIKit import TelegramCore import AppKit protocol PremiumSlideView { func willAppear() func willDisappear() } extension PremiumDemoLegacyPhoneView : PremiumSlideView { func willAppear() { } func willDisappear() { } } extension ReactionCarouselView : PremiumSlideView { func willAppear() { self.animateIn() } func willDisappear() { self.animateOut() } } extension PremiumStickersDemoView : PremiumSlideView { func willAppear() { } func willDisappear() { } } final class PremiumFeatureSlideView : View, SlideViewProtocol { private let nameView: TextView = TextView() private let descView: TextView = TextView() private let bottom = View() private let content = View() private var view: (NSView & PremiumSlideView)? private var getView: ((PremiumFeatureSlideView)->(NSView & PremiumSlideView)?)? private var decorationView: (NSView & PremiumDecorationProtocol)? enum BackgroundDecoration { case none case dataRain case swirlStars case fasterStars case badgeStars } private var bgDecoration: BackgroundDecoration = .none required init(frame frameRect: NSRect) { super.init(frame: frameRect) bottom.addSubview(descView) bottom.addSubview(nameView) descView.userInteractionEnabled = false descView.isSelectable = false nameView.userInteractionEnabled = false nameView.isSelectable = false addSubview(bottom) addSubview(content) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup(context: AccountContext, type: PremiumValue, decoration: BackgroundDecoration, getView: @escaping(PremiumFeatureSlideView)->(NSView & PremiumSlideView)) { self.getView = getView self.bgDecoration = decoration let title = type.title(context.premiumLimits) let info = type.info(context.premiumLimits) let titleLayout = TextViewLayout(.initialize(string: title, color: theme.colors.text, font: .medium(.title)), alignment: .center) let infoLayout = TextViewLayout(.initialize(string: info, color: theme.colors.text, font: .normal(.text)), alignment: .center) titleLayout.measure(width: frame.width - 40) infoLayout.measure(width: frame.width - 40) nameView.update(titleLayout) descView.update(infoLayout) needsLayout = true } var decoration: PremiumDecorationProtocol? { return self.decorationView } func willAppear() { if self.view == nil { self.view = self.getView?(self) } guard let view = self.view else { return } view.willAppear() view.frame = bounds self.content.addSubview(view) switch bgDecoration { case .none: if let decorationView = decorationView { self.decorationView = decorationView performSubviewRemoval(decorationView, animated: true) } case .dataRain: let current: (NSView & PremiumDecorationProtocol) if let view = self.decorationView { current = view } else { current = DataRainView() ?? SwirlStarsView(frame: content.bounds) self.decorationView = current content.addSubview(current, positioned: .below, relativeTo: content.subviews.first) } current.setVisible(true) case .swirlStars: let current: (NSView & PremiumDecorationProtocol) if let view = self.decorationView { current = view } else { current = SwirlStarsView(frame: content.bounds) self.decorationView = current content.addSubview(current, positioned: .below, relativeTo: content.subviews.first) } current.setVisible(true) case .fasterStars: let current: (NSView & PremiumDecorationProtocol) if let view = self.decorationView { current = view } else { current = FasterStarsView(frame: content.bounds) self.decorationView = current content.addSubview(current, positioned: .below, relativeTo: content.subviews.first) } current.setVisible(true) case .badgeStars: let current: (NSView & PremiumDecorationProtocol) if let view = self.decorationView { current = view } else { current = BadgeStarsView(frame: content.bounds) self.decorationView = current content.addSubview(current, positioned: .below, relativeTo: content.subviews.first) } current.setVisible(true) } needsLayout = true } func willDisappear() { self.decorationView?.setVisible(false) self.view?.willDisappear() } deinit { var bp = 0 bp += 1 } override func layout() { super.layout() content.frame = NSMakeRect(0, 0, frame.width, frame.height - 114) bottom.frame = NSMakeRect(0, content.frame.height, frame.width, frame.height - content.frame.height) for subview in content.subviews { subview.frame = content.bounds } nameView.centerX(y: 20) descView.centerX(y: nameView.frame.maxY + 10) } }
gpl-2.0
a4022cd1662425f9b9c0bd06640a3612
28.829146
169
0.596698
4.869565
false
false
false
false
haginile/SwiftDate
SwiftDate/Thirty360.swift
1
5162
// // This file is derived from QuantLib. The license of QuantLib is available online at <http://quantlib.org/license.shtml>. // // Thirty360.swift // SHSLib // // Created by Helin Gai on 7/7/14. // Copyright (c) 2014 Helin Gai. All rights reserved. // import Foundation public class Thirty360 : DayCounter { public enum Convention { case USA, BondBasis, // 30/360 US - Bond Basis European, EurobondBasis, // 30/360E Italian, // 30/360 Italian PSA // 30/360 PSA } class US_Impl : DayCounter.Impl { override func name() -> String { return "30/360 (Bond Basis)" } override func shortName() -> String { return "30/360" } override func dayCount(date1: Date, date2: Date) -> Int { let dd1 : Int = date1.day() var dd2 : Int = date2.day() let mm1 : Int = date1.month() var mm2 : Int = date2.month() let yy1 : Int = date1.year() let yy2 : Int = date2.year() if (dd2 == 31 && dd1 < 30) { dd2 = 1 mm2 += 1 } var o = 360 * (yy2 - yy1) o += 30 * (mm2 - mm1 - 1) o += max(0, 30 - dd1) o += min(30, dd2) return o } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return Double(dayCount(date1, date2: date2)) / 360.0 } } class EU_Impl : DayCounter.Impl { override func name() -> String { return "30E/360 (Eurobond Basis)" } override func shortName() -> String { return "30/360" } override func dayCount(date1: Date, date2: Date) -> Int { let dd1 : Int = date1.day() let dd2 : Int = date2.day() let mm1 : Int = date1.month() let mm2 : Int = date2.month() let yy1 : Int = date1.year() let yy2 : Int = date2.year() var o = 360 * (yy2 - yy1) o += 30 * (mm2 - mm1 - 1) o += max(0, 30 - dd1) o += min(30, dd2) return o } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return Double(dayCount(date1, date2: date2)) / 360.0 } } class IT_Impl : DayCounter.Impl { override func name() -> String { return "30/360 (Italian)" } override func shortName() -> String { return "30/360" } override func dayCount(date1: Date, date2: Date) -> Int { var dd1 : Int = date1.day() var dd2 : Int = date2.day() let mm1 : Int = date1.month() let mm2 : Int = date2.month() let yy1 : Int = date1.year() let yy2 : Int = date2.year() if mm1 == 2 && dd1 > 27 { dd1 = 30 } if mm2 == 2 && dd2 > 27 { dd2 = 30 } var o = 360 * (yy2 - yy1) o += 30 * (mm2 - mm1 - 1) o += max(0, 30 - dd1) o += min(30, dd2) return o } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return Double(dayCount(date1, date2: date2)) / 360.0 } } class PSA_Impl : DayCounter.Impl { override func name() -> String { return "30/360 (PSA)" } override func shortName() -> String { return "30/360" } override func dayCount(date1: Date, date2: Date) -> Int { var dd1 : Int = date1.day() var dd2 : Int = date2.day() let mm1 : Int = date1.month() let mm2 : Int = date2.month() let yy1 : Int = date1.year() let yy2 : Int = date2.year() if dd1 == 31 || date2 == Date.endOfMonth(date2) { dd1 = 30 } if dd2 == 31 && dd1 == 30 { dd2 = 30 } var o = 360 * (yy2 - yy1) o += 30 * (mm2 - mm1) o += dd2 - dd1 return o } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { return Double(dayCount(date1, date2: date2)) / 360.0 } } public init(convention : Thirty360.Convention = Thirty360.Convention.BondBasis) { super.init() switch convention { case .USA, .BondBasis: impl = Thirty360.US_Impl() case .European, .EurobondBasis: impl = Thirty360.EU_Impl() case .Italian: impl = Thirty360.IT_Impl() case .PSA: impl = Thirty360.PSA_Impl() } } }
mit
a5513a053513aa509af451b82a2ef7e1
32.967105
148
0.469973
3.823704
false
false
false
false
danieltmbr/Bencode
Sources/Bencode/Bencoder.swift
1
4682
// // Bencoder.swift // Bencode // // Created by Daniel Tombor on 2018. 04. 30.. // import Foundation final public class Bencoder { // MARK: - Constants private struct Tokens { let i: UInt8 = 0x69 let l: UInt8 = 0x6c let d: UInt8 = 0x64 let e: UInt8 = 0x65 let zero: UInt8 = 0x30 let nine: UInt8 = 0x39 let colon: UInt8 = 0x3a } private let tokens = Tokens() // MARK: - Methods public init() {} /** Decoding from Bencoded string */ public func decode(bencodedString str: String) throws -> Bencode { return try decode(bytes: str.ascii) } /** Decoding bencoded file */ public func decode(file url: URL) throws -> Bencode { let data = try Data(contentsOf: url) return try decode(bytes: [Byte](data)) } /** Decoding from bytes */ public func decode(bytes: [UInt8]) throws -> Bencode { return try parse(bytes).bencode } /** Encoding to Bencode string */ public func encoded(bencode: Bencode) -> String { switch bencode { case .integer(let i): return "i\(i)e" case .string(let b): return "\(b.count):\(String(bytes: b, encoding: .ascii)!)" case .list(let l): let desc = l.map { $0.encoded }.joined() return "l\(desc)e" case .dictionary(let d): let desc = d.sorted(by: { $0.key < $1.key }) .map { "\(Bencode.string($0.key.ascii).encoded)\($1.encoded)" } .joined() return "d\(desc)e" } } /** Encoding to Bencoded Data */ public func asciiEncoding(bencode: Bencode) -> Data { return Data(encoded(bencode: bencode).ascii) } } // MARK: - Private decoding helpers private extension Bencoder { typealias ParseResult = (bencode: Bencode, index: Int) func parse(_ data: [Byte]) throws -> ParseResult { return try parse(ArraySlice(data), from: 0) } func parse(_ data: ArraySlice<Byte>, from index: Int) throws -> ParseResult { guard data.endIndex >= index + 1 else { throw BencoderError.indexOutOfBounds(end: data.endIndex, current: index + 1) } let nextIndex = index+1 let nextSlice = data[nextIndex...] switch data[index] { case tokens.i: return try parseInt(nextSlice, from: nextIndex) case tokens.zero...tokens.nine: return try parseString(data, from: index) case tokens.l: return try parseList(nextSlice, from: nextIndex) case tokens.d: return try parseDictionary(nextSlice, from: nextIndex) default: throw BencoderError.unknownToken(data[index]) } } func parseInt(_ data: ArraySlice<Byte>, from index: Int) throws -> ParseResult { guard let end = data.firstIndex(of: tokens.e) else { throw BencoderError.tokenNotFound(tokens.e) } guard let num = Array(data[..<end]).int else { throw BencoderError.invalidNumber } return (bencode: .integer(num), index: end+1) } func parseString(_ data: ArraySlice<Byte>, from index: Int) throws -> ParseResult { guard let sep = data.firstIndex(of: tokens.colon) else { throw BencoderError.tokenNotFound(tokens.colon) } guard let len = Array(data[..<sep]).int else { throw BencoderError.invalidNumber } let start = sep + 1 let end = data.index(start, offsetBy: len) return (bencode: .string(Array(data[start..<end])), index: end) } func parseList(_ data: ArraySlice<Byte>, from index: Int) throws -> ParseResult { var l: [Bencode] = [] var idx: Int = index while data[idx] != tokens.e { let result = try parse(data[idx...], from: idx) l.append(result.bencode) idx = result.index } return (bencode: .list(l), index: idx+1) } func parseDictionary(_ data: ArraySlice<Byte>, from index: Int) throws -> ParseResult { var d: [BencodeKey:Bencode] = [:] var idx: Int = index var order = 0 while data[idx] != tokens.e { let keyResult = try parseString(data[idx...], from: idx) guard case .string(let keyData) = keyResult.bencode, let key = keyData.string else { throw BencoderError.unexpectedKey(keyResult.bencode) } let valueResult = try parse(data[keyResult.index...], from: keyResult.index) d[BencodeKey(key, order: order)] = valueResult.bencode idx = valueResult.index order += 1 } return (bencode: .dictionary(d), index: idx+1) } }
mit
ecc897dff19b1749b4903757b4c71a69
32.205674
97
0.586074
3.93115
false
false
false
false
windaddict/ARFun
ARFun.playground/Pages/ARKit experiments .xcplaygroundpage/Contents.swift
1
7591
/* * Copyright 2017 John M. P. Knox * Licensed under the MIT License - see license file */ import UIKit import ARKit import PlaygroundSupport /** * A Simple starting point for AR experimentation in Swift Playgrounds 2 */ class ARFun: NSObject, ARSCNViewDelegate { var nodeDict = [UUID:SCNNode]() //mark: ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? { if let node = nodeDict[anchor.identifier] { return node } return nil } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { [weak self] in self?.debugView.log("updated node") } } let arSessionConfig = ARWorldTrackingConfiguration() let debugView = ARDebugView() var view:ARSCNView? = nil let scene = SCNScene() let useScenekit = true override init(){ super.init() let frame = CGRect(x: 0.0, y: 0, width: 100, height: 100) let arView = ARSCNView(frame: frame) //configure the ARSCNView arView.debugOptions = [ //ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints, // SCNDebugOptions.showLightInfluences, // SCNDebugOptions.showWireframe ] arView.showsStatistics = true arView.automaticallyUpdatesLighting = true debugView.translatesAutoresizingMaskIntoConstraints = false //add the debug view arView.addSubview(debugView) arView.leadingAnchor.constraint(equalTo: debugView.leadingAnchor) arView.topAnchor.constraint(equalTo: debugView.topAnchor) view = arView arView.scene = scene //setup session config if !ARWorldTrackingConfiguration.isSupported { return } arSessionConfig.planeDetection = .horizontal arSessionConfig.worldAlignment = .gravityAndHeading //y-axis points UP, x points E (longitude), z points S (latitude) arSessionConfig.isLightEstimationEnabled = true arView.session.run(arSessionConfig, options: [.resetTracking, .removeExistingAnchors]) arView.delegate = self let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped(gestureRecognizer:))) view?.addGestureRecognizer(gestureRecognizer) } let shouldAddAnchorsForNodes = true func addNode(node: SCNNode, worldTransform: matrix_float4x4) { let anchor = ARAnchor(transform: worldTransform) let position = vectorFrom(transform: worldTransform) node.position = position node.rotation = SCNVector4(x: 1, y: 1, z: 0, w: 0) nodeDict[anchor.identifier] = node if shouldAddAnchorsForNodes { view?.session.add(anchor: anchor) } else { scene.rootNode.addChildNode(node) } } func debug(sceneNode : SCNNode, prefix: String = "" ){ debugView.log(prefix + (sceneNode.name ?? "")) for child in sceneNode.childNodes{ debug(sceneNode: child, prefix: prefix + "-") } } func debug(scene: SCNScene, prefix: String = ""){ debug(sceneNode: scene.rootNode) } ///returns a new node with a scene, if one can be found for the scene file specified func nodeFromScene(named fileName: String, inDirectory directoryName: String)-> SCNNode? { let scene = SCNScene(named: fileName, inDirectory: directoryName) guard let theScene = scene else { debugView.log("no scene \(fileName) in \(directoryName)") return nil } let node = SCNNode() for child in theScene.rootNode.childNodes { debugView.log("examining \(String(describing: child.name))") child.geometry?.firstMaterial?.lightingModel = .physicallyBased child.movabilityHint = .movable node.addChildNode(child) } return node } ///adds a new torus to the scene's root node func addTorus(worldTransform: matrix_float4x4 = matrix_identity_float4x4) { let torus = SCNTorus(ringRadius: 0.1, pipeRadius: 0.02) torus.firstMaterial?.diffuse.contents = UIColor(red: 0.4, green: 0, blue: 0, alpha: 1) torus.firstMaterial?.specular.contents = UIColor.white let torusNode = SCNNode(geometry:torus) let spin = CABasicAnimation(keyPath: "rotation.w") spin.toValue = 2 * Double.pi spin.duration = 3 spin.repeatCount = HUGE torusNode.addAnimation(spin, forKey: "spin around") addNode(node: torusNode, worldTransform: worldTransform) } func makeLight()->SCNLight{ let light = SCNLight() light.intensity = 1 light.type = .omni light.color = UIColor.yellow light.attenuationStartDistance = 0.01 light.attenuationEndDistance = 1 return light } func makeLightNode()->SCNNode{ let light = makeLight() let node = SCNNode() var transform = matrix_identity_float4x4 transform.columns.3.y = 0.2 node.simdTransform = transform node.light = light node.simdTransform = transform return node } func addCandle(worldTransform: matrix_float4x4 = matrix_identity_float4x4) { guard let candleNode = nodeFromScene(named: "candle.scn", inDirectory: "Models.scnassets/candle") else { return } //candleNode.addChildNode(makeLightNode()) addNode(node: candleNode, worldTransform: worldTransform) } func addTrex(worldTransform: matrix_float4x4 = matrix_identity_float4x4) { debugView.log("addTrex") guard let node = nodeFromScene(named: "Tyrannosaurus_jmpk2.scn", inDirectory: "/") else { return } addNode(node: node, worldTransform: worldTransform) } ///add a node where the scene was tapped @objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){ print("got tap: \(gestureRecognizer.location(in: view))") let hitTypes:ARHitTestResult.ResultType = [ ARHitTestResult.ResultType.existingPlaneUsingExtent, //ARHitTestResult.ResultType.estimatedHorizontalPlane, //ARHitTestResult.ResultType.featurePoint ] if let hitTransform = view?.hitTest(gestureRecognizer.location(in: view), types: hitTypes).first?.worldTransform { addTrex(worldTransform: hitTransform) //addCandle(worldTransform: hitTransform) //TODO: use the anchor provided, if any? } else { debugView.log("no hit for tap") } } ///convert a transform matrix_float4x4 to a SCNVector3 func vectorFrom(transform: matrix_float4x4) -> SCNVector3 { return SCNVector3Make(transform.columns.3.x, transform.columns.3.y, transform.columns.3.z) } } ///vector addition and subtraction extension SCNVector3 { static func - (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x - right.x, left.y - right.y, left.z - right.z) } static func + (left: SCNVector3, right: SCNVector3) -> SCNVector3 { return SCNVector3Make(left.x + right.x, left.y + right.y, left.z + right.z) } } let arFun = ARFun() PlaygroundPage.current.liveView = arFun.view PlaygroundPage.current.needsIndefiniteExecution = true
mit
9810a7aba2150aa40dd0af1d57441570
36.029268
125
0.641681
4.473188
false
false
false
false
erik/sketches
projects/GithubNotify/GithubNotify/AppDelegate.swift
1
1245
import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { let STATUS_ITEM = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength) func applicationDidFinishLaunching(_ aNotification: Notification) { NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(AppDelegate.handleGetURL(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL)) if let button = STATUS_ITEM.button { button.image = NSImage(named: "MenuIconDefault") button.action = #selector(togglePopover(_:)) } InitGithub() } func applicationWillTerminate(_ aNotification: Notification) { } @objc func togglePopover(_ sender: Any?) { print("toggle popover") updateNotifications() } func handleGetURL(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) { if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) { if url.scheme == "github-notify" { HandleGithubOAuthURL(url: url) } } } }
agpl-3.0
f849df5cb28f0c0dc14e704aa95c4875
27.953488
215
0.675502
4.920949
false
false
false
false
JGiola/swift-package-manager
Sources/Basic/JSONMapper.swift
2
4898
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// A type which can be mapped from JSON. public protocol JSONMappable { /// Create an object from given JSON. init(json: JSON) throws } extension JSON { /// Describes an error occurred during JSON mapping. public enum MapError: Error { /// The key is missing in JSON. case missingKey(String) /// Got a different type than expected. case typeMismatch(key: String, expected: Any.Type, json: JSON) /// A custom error. Clients can use this in their mapping method. case custom(key: String?, message: String) } /// Returns a JSON mappable object from a given key. public func get<T: JSONMappable>(_ key: String) throws -> T { let object: JSON = try get(key) return try T(json: object) } public func get<T: JSONMappable>(_ type: T.Type, forKey key: String) throws -> T { let object: JSON = try get(key) return try T(json: object) } /// Returns an optional JSON mappable object from a given key. public func get<T: JSONMappable>(_ key: String) -> T? { return try? get(key) } /// Returns a JSON mappable array from a given key. public func get<T: JSONMappable>(_ key: String) throws -> [T] { let array: [JSON] = try get(key) return try array.map(T.init(json:)) } public func get<T: JSONMappable>(_ type: [T].Type, forKey key: String) throws -> [T] { let array: [JSON] = try get(key) return try array.map(T.init(json:)) } /// Returns a JSON mappable dictionary from a given key. public func get<T: JSONMappable>(_ key: String) throws -> [String: T] { let object: JSON = try get(key) guard case .dictionary(let value) = object else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: object) } return try Dictionary(items: value.map({ ($0.0, try T.init(json: $0.1)) })) } /// Returns a JSON mappable dictionary from a given key. public func get(_ key: String) throws -> [String: JSON] { let object: JSON = try get(key) guard case .dictionary(let value) = object else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: object) } return value } /// Returns JSON entry in the dictionary from a given key. public func get(_ key: String) throws -> JSON { guard case .dictionary(let dict) = self else { throw MapError.typeMismatch( key: key, expected: Dictionary<String, JSON>.self, json: self) } guard let object = dict[key] else { throw MapError.missingKey(key) } return object } public func getJSON(_ key: String) throws -> JSON { return try get(key) } /// Returns JSON array entry in the dictionary from a given key. public func get(_ key: String) throws -> [JSON] { let object: JSON = try get(key) guard case .array(let array) = object else { throw MapError.typeMismatch(key: key, expected: Array<JSON>.self, json: object) } return array } public func getArray(_ key: String) throws -> [JSON] { return try get(key) } public func getArray() throws -> [JSON] { guard case .array(let array) = self else { throw MapError.typeMismatch(key: "<self>", expected: Array<JSON>.self, json: self) } return array } } // MARK: - Conformance for basic JSON types. extension Int: JSONMappable { public init(json: JSON) throws { guard case .int(let int) = json else { throw JSON.MapError.custom(key: nil, message: "expected int, got \(json)") } self = int } } extension String: JSONMappable { public init(json: JSON) throws { guard case .string(let str) = json else { throw JSON.MapError.custom(key: nil, message: "expected string, got \(json)") } self = str } } extension Bool: JSONMappable { public init(json: JSON) throws { guard case .bool(let bool) = json else { throw JSON.MapError.custom(key: nil, message: "expected bool, got \(json)") } self = bool } } extension Double: JSONMappable { public init(json: JSON) throws { guard case .double(let double) = json else { throw JSON.MapError.custom(key: nil, message: "expected double, got \(json)") } self = double } }
apache-2.0
d9f8e8c2367b6f626559dfb62f7e33ca
31.437086
94
0.605145
4.105616
false
false
false
false
abecker3/SeniorDesignGroup7
ProvidenceWayfinding/ProvidenceWayfinding/ParkingPathViewController.swift
1
11591
// // ParkingPathViewController.swift // ProvidenceWayfinding // // Created by Derek Becker on 2/9/16. // Copyright © 2016 GU. All rights reserved. // import UIKit import Foundation class ParkingPathViewController: UIViewController, UITextFieldDelegate { var screenEdgeRecognizerRight: UIScreenEdgePanGestureRecognizer! var flag = 0 var building = [String()] var floor = [String()] var dateSave = [String()] var timeSave = [String()] var keyNum = Int() var indexFlag = Int() var saved = false //Variables var endLocation: Directory! var startLocation: Directory! let defaults = NSUserDefaults.standardUserDefaults() let dateFormatter: NSDateFormatter = { let df = NSDateFormatter(); df.dateStyle = NSDateFormatterStyle.MediumStyle; return df; }() //Outlets //@IBOutlet weak var nextBut: UIBarButtonItem! @IBOutlet weak var parkView: UIView! @IBOutlet weak var savedParkingTime: UILabel! @IBOutlet weak var savedParkingFloor: UILabel! @IBOutlet weak var savedParkingSpot: UILabel! @IBOutlet weak var savedParkingDate: UILabel! @IBOutlet weak var buildingButtons: UISegmentedControl! @IBOutlet weak var floorButtons: UISegmentedControl! var parkingLocationBuilding = String() var parkingLocationFloor = String() var pathFlag = Int() //Actions @IBAction func nextView(sender: AnyObject) { if (saved == false){ let alertTitle = "Caution!" let alertMessage = "Would you like to continue without saving your most current parking location?" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in alertController.dismissViewControllerAnimated(true, completion: nil) })) alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in self.performSegueWithIdentifier("onCampusView", sender: self) })) presentViewController(alertController, animated: false, completion: nil) }else{ self.performSegueWithIdentifier("onCampusView", sender: self) } } @IBAction func save(sender: AnyObject) { defaults.setInteger(1, forKey: "savedParkingEver") if (indexFlag == 0){ building.insert(parkingLocationBuilding, atIndex: 0) floor.insert(parkingLocationFloor, atIndex: 0) dateSave.insert(dateFormatter.stringFromDate(NSDate()), atIndex: 0) dateFormatter.dateFormat = "h:mm a" timeSave.insert(dateFormatter.stringFromDate(NSDate()) , atIndex: 0) dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle; } else{ building.insert(parkingLocationBuilding, atIndex: 0) floor.insert(parkingLocationFloor, atIndex: 0) dateSave.insert(dateFormatter.stringFromDate(NSDate()), atIndex: 0) dateFormatter.dateFormat = "h:mm a" timeSave.insert(dateFormatter.stringFromDate(NSDate()) , atIndex: 0) dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle; building.removeLast() floor.removeLast() timeSave.removeLast() dateSave.removeLast() } defaults.setObject(building, forKey: "buildingArray") defaults.setObject(floor, forKey: "floorArray") defaults.setObject(timeSave, forKey: "timeArray") defaults.setObject(dateSave, forKey: "dateArray") if(keyNum >= 8){ indexFlag = 1 keyNum = 0 }else{ keyNum += 1 } defaults.setObject(keyNum, forKey: "keyNum") defaults.setObject(indexFlag, forKey: "indexFlag") defaults.synchronize(); savedParkingSpot.text = building[0] savedParkingDate.text = dateSave[0] savedParkingFloor.text = floor[0] savedParkingTime.text = timeSave[0] saved = true parkingEntry = Directory(name: building[0] + " Parking " + floor[0], category: "Parking", floor: floor[0], hours: "NA", ext: "", notes: "") startLocation.name = building[0] + " Parking " + floor[0] } @IBAction func changedBuilding(sender: UISegmentedControl) { let title = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex) switch title{ case "Doctors"?: parkingLocationBuilding = "Doctors" setFloorOptions(0) case "Children's"?: parkingLocationBuilding = "Children's" setFloorOptions(1) case "Women's"?: parkingLocationBuilding = "Women's" setFloorOptions(2) default: parkingLocationBuilding = "Heart" setFloorOptions(3) } } func setFloorOptions(x: Int){ turnButtons(0, function: 1) switch x{ case 1: floorButtons.setTitle("L6", forSegmentAtIndex: 0) floorButtons.setTitle("L5", forSegmentAtIndex: 1) floorButtons.setTitle("L4", forSegmentAtIndex: 2) floorButtons.setTitle("UL4", forSegmentAtIndex:3) floorButtons.setTitle("L3", forSegmentAtIndex: 4) turnButtons(4,function: 0) parkingLocationFloor = "L6" floorButtons.selectedSegmentIndex = 0 case 2: floorButtons.setTitle("P2", forSegmentAtIndex: 0) floorButtons.setTitle("P3", forSegmentAtIndex: 1) floorButtons.setTitle("P4", forSegmentAtIndex: 2) floorButtons.setTitle("P5", forSegmentAtIndex: 3) turnButtons(3,function: 0) turnButtons(4,function: 1) parkingLocationFloor = "P2" floorButtons.selectedSegmentIndex = 0 case 3: floorButtons.setTitle("P1", forSegmentAtIndex: 0) floorButtons.setTitle("P2", forSegmentAtIndex: 1) floorButtons.setTitle("P3", forSegmentAtIndex: 2) floorButtons.setTitle("P4", forSegmentAtIndex: 3) floorButtons.setTitle("P5", forSegmentAtIndex: 4) turnButtons(4,function: 0) turnButtons(5,function: 1) parkingLocationFloor = "P1" floorButtons.selectedSegmentIndex = 0 default:floorButtons.setTitle("C", forSegmentAtIndex: 0) floorButtons.setTitle("D", forSegmentAtIndex: 1) floorButtons.setTitle("E", forSegmentAtIndex: 2) floorButtons.setTitle("F", forSegmentAtIndex: 3) floorButtons.setTitle("5", forSegmentAtIndex: 4) floorButtons.setTitle("6", forSegmentAtIndex: 5) floorButtons.setTitle("7", forSegmentAtIndex: 6) turnButtons(6,function: 0) turnButtons(7,function: 1) parkingLocationFloor = "C" floorButtons.selectedSegmentIndex = 0 } } func turnButtons(var amount: Int, function: Int){ if function == 0{ while amount > -1 { floorButtons.setEnabled(true, forSegmentAtIndex: amount) amount-- } } else{ while amount < 7 { floorButtons.setEnabled(false, forSegmentAtIndex: amount) floorButtons.setTitle("", forSegmentAtIndex: amount) amount++ } } } @IBAction func changedFloor(sender: UISegmentedControl) { parkingLocationFloor = sender.titleForSegmentAtIndex(sender.selectedSegmentIndex)! } override func viewDidLoad() { super.viewDidLoad() parkView.layer.borderWidth = 2 parkView.layer.cornerRadius = 10 parkView.layer.borderColor = UIColor(red: 6/255.0, green: 56/255.0, blue: 122/255.0, alpha: 1.0).CGColor //screenEdgeRecognizerRight = UIScreenEdgePanGestureRecognizer(target: self, action: "switchScreenGestureRight:") //screenEdgeRecognizerRight.edges = .Right //view.addGestureRecognizer(screenEdgeRecognizerRight) // Do any additional setup after loading the view. parkingLocationBuilding = "Doctors" parkingLocationFloor = "C" setFloorOptions(0) } override func viewDidAppear(animated: Bool) { //Load Saved Parking Spot/Date pathFlag = 1 defaults.setObject(pathFlag, forKey: "pathFlag") if(defaults.stringForKey("keyNum") != nil){ keyNum = Int(defaults.stringForKey("keyNum")!)! } else{ keyNum = 0 } if(defaults.stringForKey("indexFlag") != nil && defaults.stringForKey("indexFlag") != String(0)){ indexFlag = Int(defaults.stringForKey("indexFlag")!)! } else{ indexFlag = 0 } if (defaults.objectForKey("buildingArray") != nil){ building = defaults.objectForKey("buildingArray")! as! NSArray as! [String] floor = defaults.objectForKey("floorArray")! as! NSArray as! [String] timeSave = defaults.objectForKey("timeArray")! as! NSArray as! [String] dateSave = defaults.objectForKey("dateArray")! as! NSArray as! [String] } savedParkingSpot.text = building[0] savedParkingDate.text = dateSave[0] savedParkingFloor.text = floor[0] savedParkingTime.text = timeSave[0] if(resetToRootView == 1){ self.navigationController?.popToRootViewControllerAnimated(true) } } /*override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { if identifier == "onCampusView"{ if (saved == false){ let alertTitle = "Caution!" let alertMessage = "Would you like to continue without saving your most current parking location?" let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in return true })) alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in return false })) presentViewController(alertController, animated: false, completion: nil) }else{ return true } } return true //by default }*/ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let nextViewController = segue.destinationViewController as! OnCampusDirectionsViewController nextViewController.startLocation = self.startLocation nextViewController.endLocation = self.endLocation nextViewController.distanceToSurvey = 3 } /* func switchScreenGestureRight(sender: UIScreenEdgePanGestureRecognizer) { flag = flag + 1 if (flag % 2 == 1){ performSegueWithIdentifier("onCampusView", sender: nil) } }*/ }
apache-2.0
df17dc09c667a448cb07cf285fffe216
40.694245
147
0.617429
5.069991
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-swift-security
Source/mca/internal/RequestOptions.swift
3
1052
/* *     Copyright 2015 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ // Created by Ilan Klein on 12/21/2015. import Foundation import BMSCore internal class RequestOptions { internal var requestMethod : HttpMethod internal var timeout : Double = 0 internal var headers = [String : String]() internal var parameters = [String : String]() internal init(requestMethod : HttpMethod = HttpMethod.GET) { self.requestMethod = requestMethod } }
apache-2.0
f58a4c52763a0e1d0d69714e034b159a
34.275862
78
0.704501
4.258333
false
false
false
false
Turistforeningen/SjekkUT
ios/SjekkUt/views/onboarding/Onboarding.swift
1
2005
// // Onboarding.swift // // // Created by Henrik Hartz on 12/05/2017. // // import Foundation class OnboardingView: DntTrackViewController { @IBOutlet var pageControl: UIPageControl! @IBOutlet var scrollView: UIScrollView! @IBOutlet var loginButton: UIButton! @IBOutlet var browseButton: UIButton! @IBOutlet var browseButtonHeight: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() trackingIdentifier = "Appen viste onboarding" loginButton.layer.cornerRadius = 3 browseButton.layer.cornerRadius = 3 self.browseButtonHeight.constant = 0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: true) } } extension OnboardingView: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if let aPageControl = pageControl { updateCurrentPage(aPageControl) updateLoginButtonColors(aPageControl) } } func updateCurrentPage(_ aPageControl: UIPageControl) { aPageControl.numberOfPages = Int(scrollView.contentSize.width / scrollView.bounds.width) let currentPage = scrollView.contentOffset.x / scrollView.bounds.width aPageControl.currentPage = Int(currentPage.rounded()) } func updateLoginButtonColors(_ aPageControl: UIPageControl) { let lastPage = aPageControl.currentPage == (aPageControl.numberOfPages - 1) // only show the browse button after browsing to the last onboarding page self.browseButtonHeight.constant = lastPage ? 44 : 0 UIView.animate(withDuration: kSjekkUtConstantAnimationDuration, animations: { self.view.layoutIfNeeded() }) } }
mit
54d65b1efa86c830a0698bc38b45c2c3
28.057971
96
0.700249
5.114796
false
false
false
false
alexzatsepin/omim
iphone/Maps/UI/Discovery/DiscoveryOnlineTemplateCell.swift
1
1241
@objc(MWMDiscoveryOnlineTemplateType) enum DiscoveryOnlineTemplateType: Int { case locals } @objc(MWMDiscoveryOnlineTemplateCell) final class DiscoveryOnlineTemplateCell: MWMTableViewCell { @IBOutlet private weak var spinner: UIImageView! { didSet { let postfix = UIColor.isNightMode() ? "_dark" : "_light" let animationImagesCount = 12 var images = Array<UIImage>() for i in 1...animationImagesCount { images.append(UIImage(named: "Spinner_\(i)" + postfix)!) } spinner.animationDuration = 0.8 spinner.animationImages = images } } @IBOutlet private weak var title: UILabel! @IBOutlet private weak var subtitle: UILabel! typealias Tap = () -> () private var tap: Tap? @objc func config(type: DiscoveryOnlineTemplateType, needSpinner: Bool, tap: @escaping Tap) { switch type { case .locals: title.text = needSpinner ? L("discovery_button_other_loading_message") : L("discovery_button_other_error_message") subtitle.text = "" } spinner.isHidden = !needSpinner if (needSpinner) { spinner.startAnimating() } self.tap = tap } @IBAction private func onTap() { tap?() } }
apache-2.0
d8d76e471fc37b79dd80cbba5e4155c8
26.577778
95
0.647865
4.27931
false
false
false
false
benlangmuir/swift
test/IRGen/prespecialized-metadata/struct-extradata-no_field_offsets-trailing_flags.swift
14
3393
// RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: [[EXTRA_DATA_PATTERN:@[0-9]+]] = internal constant <{ i64 }> zeroinitializer, align [[ALIGNMENT]] // CHECK: @"$s4main4PairVMP" = internal constant <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16 // : }> <{ // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.type* ( // : %swift.type_descriptor*, // : i8**, // : i8* // : )* @"$s4main4PairVMi" to i64 // : ), // : i64 ptrtoint ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP" to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.metadata_response ( // : %swift.type*, // : i8*, // : i8** // : )* @"$s4main4PairVMr" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // : i32 0, // : i32 1 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 1073741827, // : i32 trunc ( // : i64 sub ( // : i64 ptrtoint ( // : %swift.vwtable* @"$s4main4PairVWV" to i64 // : ), // : i64 ptrtoint ( // : i32* getelementptr inbounds ( // : <{ i32, i32, i32, i32, i32, i16, i16 }>, // : <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // : i32 0, // : i32 3 // : ) to i64 // : ) // : ) to i32 // : ), // : i32 trunc ( // CHECK-SAME: [[INT]] sub ( // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: <{ // CHECK-SAME: i64 // CHECK-SAME: }>* [[EXTRA_DATA_PATTERN]] to [[INT]] // CHECK-SAME: ), // CHECK-SAME: [[INT]] ptrtoint ( // CHECK-SAME: i32* getelementptr inbounds ( // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>, // CHECK-SAME: <{ i32, i32, i32, i32, i32, i16, i16 }>* @"$s4main4PairVMP", // CHECK-SAME: i32 0, // CHECK-SAME: i32 4 // CHECK-SAME: ) to [[INT]] // CHECK-SAME: ) // CHECK-SAME: ) // : ), // : i16 5, // : i16 1 // : }>, align 8 struct Pair<First, Second, Third> { let first: First let second: Second let third: Third }
apache-2.0
39a24dae1e7e67238180a26faabd645c
35.483871
173
0.361922
3.115702
false
false
false
false
mojio/mojio-ios-sdk
MojioSDK/Models/Activity Streams/Activity.swift
1
1341
// // BaseActivity.swift // MojioSDK // // Created by Narayan Sainaney on 2016-06-27. // Copyright © 2016 Mojio. All rights reserved. // import Foundation import ObjectMapper public class Activity : BaseActivity { public dynamic var StartTime : String? = nil public dynamic var EndTime : String? = nil public dynamic var Duration : String? = nil public dynamic var Published : String? = nil public dynamic var Updated : String? = nil public dynamic var Context : String? = nil public dynamic var Location : ActivityLocation? = nil public dynamic var Origin : ActivityLocation? = nil public dynamic var Summary : Dictionary<String,String>? = nil public var Icon : Dictionary<String, AnyObject>? = nil public required override init() { super.init() } public required convenience init?(_ map: Map) { self.init() } public override func mapping(map: Map) { super.mapping(map) Context <- map["Context"] Location <- map["Location"] Origin <- map["Origin"] StartTime <- map["StartTime"] EndTime <- map["EndTime"] Duration <- map["Duration"] Published <- map["Published"] Updated <- map["Updated"] Summary <- map["SummaryMap"] Icon <- map["Icon"] } }
mit
ce03537bf180e6eb25211a62d74440c7
27.531915
65
0.619403
4.379085
false
false
false
false
UsrNameu1/TraverSwift
TraverSwiftTests/ArrayFunctionsTests.swift
1
1981
// // ArrayFunctionsTests.swift // TraverSwift // // Created by adachi yuichi on 2014/12/17. // Copyright (c) 2014年 yad. All rights reserved. // // The MIT License (MIT) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest import TraverSwift class ArrayFunctionsTests: XCTestCase { func testExistsAnyFunction() { let arr = ["1e3","123","rf3","rf3"].map{ str in str.toInt() } let result = existsAny(arr) XCTAssert(result, "One of the elements can convert to Int") } func testExistsAllFunction() { let arr = ["13","123","3","312"].map{ str in str.toInt() } let result = existsAll(arr) XCTAssert(result, "All of the elements can convert to Int") } func testConcatFunction() { let arr1 = [[1,2,3],[4,5,6],[7,8,9]] let result1 = concat(arr1) XCTAssert(result1 == [1,2,3,4,5,6,7,8,9], "returns array of concatenation") } }
mit
1405b90961271ef467e0b0988a743dde
40.25
83
0.689742
3.918812
false
true
false
false
ScalaInc/exp-ios-sdk
ExpSwift/Classes/Zone.swift
1
3589
// // Zone.swift // Pods // // Created by Cesar on 9/10/15. // // import Foundation import PromiseKit import Alamofire public final class Zone: Model,ResponseObject,ResponseCollection,ModelProtocol { public var name: String? public let key: String fileprivate var location: Location? required public init?(response: HTTPURLResponse?, representation: Any?) { guard let representation = representation as? [String: Any], let key = representation["key"] as? String, let name = representation["name"] as? String else{ return nil} self.key = key self.name = name super.init(response: response, representation: representation) } public static func collection(response: HTTPURLResponse?, representation: Any?,location: Location?) -> [Zone] { var zones: [Zone] = [] if let representation = representation as? [[String: AnyObject]] { for zoneRepresentation in representation { if let zone = Zone(response: response, representation: zoneRepresentation as AnyObject) { zone.location = location zones.append(zone) } } } return zones } public func getDevices() -> Promise<SearchResults<Device>>{ return Promise { fulfill, reject in let uuidLocation:String = (self.location?.uuid)! Alamofire.request(Router.findDevices(["location.uuid":uuidLocation,"location.zones.key":self.key])) .responseCollection { (response: DataResponse<SearchResults<Device>>) in switch response.result{ case .success(let data): fulfill(data) case .failure(let error): return reject(error) } } } } public func getThings() -> Promise<SearchResults<Thing>>{ return Promise { fulfill, reject in Alamofire.request(Router.findThings(["location.uuid":self.location!.uuid,"location.zones.key":self.key])) .responseCollection { (response: DataResponse<SearchResults<Thing>>) in switch response.result{ case .success(let data): fulfill(data) case .failure(let error): return reject(error) } } } } /** Get Current Zones @return Promise<[Zone]>. */ public func getCurrentZones() -> Promise<[Zone?]>{ return Device.getCurrentDevice().then{ (device:Device?) -> Promise<[Zone?]> in return Promise<[Zone?]> { fulfill, reject in if let zones:[Zone] = device?.getZones(){ fulfill(zones) }else{ fulfill([]) expLogging("Zone - getCurrentZones NULL") } } } } /** Get Channel Name */ override public func getChannelName() -> String { return (self.location?.uuid)!+":zone:"+self.key } /** Refresh Zone by calling the location @return Promise<Location> */ public func refresh() -> Promise<Location> { return (self.location?.refresh())! } /** Save Zone by calling the location @return Promise<Location> */ public func save() -> Promise<Location> { return (self.location?.save())! } }
mit
a0af1cc6009b1eb6afae7b1588df994f
30.482456
117
0.542212
5.134478
false
false
false
false
Masteryyz/CSYMicroBlockSina
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewCell/RetweetedView/CSYRetweetedView.swift
1
3857
// // CSYRetweetedView.swift // CSYMicroBlockSina // // Created by 姚彦兆 on 15/11/15. // Copyright © 2015年 姚彦兆. All rights reserved. // import UIKit import SnapKit import FFLabel class CSYRetweetedView: UIView ,FFLabelDelegate { private var bottomConstraint : Constraint? //数据源方法 var retweetedModel : CSYMyMicroBlogModel? { didSet{ contentLabel.attributedText = CSYEmoticonManager.manager.setTextToImageText(retweetedModel?.text ?? "" , font: contentLabel.font) self.bottomConstraint?.uninstall() if let urlArray : [NSURL] = retweetedModel?.picURLArray where urlArray.count > 0 { pictureView.hidden = false pictureView.imageURLArray = urlArray pictureView.backgroundColor = UIColor.whiteColor() self.snp_updateConstraints(closure: { (make) -> Void in self.bottomConstraint = make.bottom.equalTo(pictureView.snp_bottom).offset(cellMargin).constraint }) }else{ pictureView.hidden = true self.snp_updateConstraints(closure: { (make) -> Void in self.bottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(cellMargin).constraint }) } } } //初始化方法 override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor(white: 0.95, alpha: 1) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //设置UI private func setUpUI(){ addSubview(contentLabel) contentLabel.labelDelegate = self contentLabel.linkTextColor = UIColor.orangeColor() addSubview(pictureView) pictureView.backgroundColor = UIColor.lightGrayColor() contentLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(snp_top).offset(cellMargin) make.left.equalTo(snp_left).offset(cellMargin) } pictureView.snp_makeConstraints { (make) -> Void in make.top.equalTo(contentLabel.snp_bottom).offset(cellMargin) make.left.equalTo(snp_left).offset(cellMargin) } self.snp_makeConstraints { (make) -> Void in self.bottomConstraint = make.bottom.equalTo(pictureView.snp_bottom).offset(cellMargin).constraint } } //懒加载所有控件 lazy var contentLabel : FFLabel = FFLabel(textInfo: "这是转发的微博正文", fontSize: 14, infoColor: UIColor.darkGrayColor(), numberOFLines: 0, alphaValue: 1, margin: cellMargin) lazy var pictureView : CSYBlogPictureView = CSYBlogPictureView() } extension CSYRetweetedView { func labelDidSelectedLinkText(label: FFLabel, text: String) { print(text) if let URL : NSURL = NSURL(string: text){ if text.hasPrefix("http"){ let webVC : CSYShowLinkViewController = CSYShowLinkViewController(url: URL, blogModel: retweetedModel!) self.getNavController()?.pushViewController(webVC, animated: true) } } } }
mit
b0f27ed86815c25c16bc217ab349ad74
26.042857
171
0.525621
5.543192
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/ISMSStreamManager/StreamQueue.swift
1
4434
// // StreamQueue.swift // iSub // // Created by Benjamin Baron on 1/16/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class StreamQueue: StreamHandlerDelegate { public static let si = StreamQueue() fileprivate let maxReconnects = 5 fileprivate(set) var isDownloading = false fileprivate(set) var song: Song? var streamHandler: StreamHandler? func start() { guard let currentSong = PlayQueue.si.currentSong, song != currentSong, !SavedSettings.si.isOfflineMode else { return } if currentSong.basicType == .audio && !currentSong.isFullyCached && DownloadQueue.si.currentSong != currentSong { song = currentSong } else if let nextSong = PlayQueue.si.nextSong, nextSong.basicType == .audio && !nextSong.isFullyCached && DownloadQueue.si.currentSong != nextSong { song = nextSong } else { return } isDownloading = true // Create the stream handler streamHandler?.cancel() streamHandler = StreamHandler(song: song!, isTemp: false, delegate: self) streamHandler!.allowReconnects = true streamHandler!.start() } func stop() { isDownloading = false streamHandler?.cancel() streamHandler = nil song = nil } // MARK: - Stream Handler Delegate - fileprivate func removeFile(forHandler handler: StreamHandler) { do { try FileManager.default.removeItem(atPath: handler.filePath) } catch { printError(error) } } func streamHandlerStarted(_ handler: StreamHandler) { } func streamHandlerConnectionFinished(_ handler: StreamHandler) { var isSuccess = true if handler.totalBytesTransferred == 0 { // TODO: Display message to user that we couldn't stream removeFile(forHandler: handler) isSuccess = false } else if handler.totalBytesTransferred < 2000 { var isLicenceIssue = false if let receivedData = try? Data(contentsOf: URL(fileURLWithPath: handler.filePath)) { if let root = RXMLElement(fromXMLData: receivedData), root.isValid { if let error = root.child("error"), error.isValid { if let code = error.attribute("code"), code == "60" { isLicenceIssue = true } } } } else { isSuccess = false } if isLicenceIssue { // TODO: Update this error message to better explain and to point to free alternatives let alert = UIAlertController(title: "Subsonic API Trial Expired", message: "You can purchase a license for Subsonic by logging in to the web interface and clicking the red Donate link on the top right.\n\nPlease remember, iSub is a 3rd party client for Subsonic, and this license and trial is for Subsonic and not iSub.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) AppDelegate.si.sidePanelController.present(alert, animated: true, completion: nil) removeFile(forHandler: handler) isSuccess = false } } if isSuccess { if streamHandler?.numberOfReconnects == 0 { // Only mark song as cached if it didn't reconnect to avoid files with glitches song?.isFullyCached = true } song = nil streamHandler = nil // Start streaming the next song start() } } func streamHandlerConnectionFailed(_ handler: StreamHandler, withError error: Error?) { if handler.allowReconnects && handler.numberOfReconnects < maxReconnects { // Less than max number of reconnections, so try again handler.numberOfReconnects += 1 handler.start(true) } else { // TODO: Display message to user in app streamHandler = nil start() } } }
gpl-3.0
0870051aea3721bf31b4d3a5a93cb327
35.636364
301
0.566434
5.215294
false
false
false
false
bsantanas/Twitternator2
Twitternator2/Swifter/SwifterSpam.swift
13
2573
// // SwifterSpam.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /* POST users/report_spam Report the specified user as a spam account to Twitter. Additionally performs the equivalent of POST blocks/create on behalf of the authenticated user. */ public func postUsersReportSpamWithScreenName(screenName: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "users/report_spam.json" var parameters = Dictionary<String, Any>() parameters["screen_name"] = screenName self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } public func postUsersReportSpamWithUserID(userID: String, success: ((user: Dictionary<String, JSONValue>?) -> Void)? = nil, failure: FailureHandler? = nil) { let path = "users/report_spam.json" var parameters = Dictionary<String, Any>() parameters["user_id"] = userID self.postJSONWithPath(path, baseURL: self.apiURL, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { json, response in success?(user: json.object) return }, failure: failure) } }
mit
9f5293d03bfb9e8f97abf37a44cfadbb
38.584615
169
0.694909
4.521968
false
false
false
false
nicnocquee/ComposerSheet
ComposerSheetTests/ComposerSheetTests.swift
1
8954
// // ComposerSheetTests.swift // ComposerSheetTests // // Created by Nico Prananta on 6/30/15. // Copyright (c) 2015 DelightfulDev. All rights reserved. // import UIKit import XCTest class ComposerSheetTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInit() { // This is an example of a functional test case. let composerController = DLFComposerViewController() XCTAssertNotNil(composerController.sheetView, "Sheet view should not be nil") XCTAssertNotNil(composerController.sheetTitle, "Sheet title should not be nil") XCTAssertNotNil(composerController.cancelButton, "Sheet cancel button should not be nil") XCTAssertNotNil(composerController.nextButton, "Sheet next button should not be nil") XCTAssertNotNil(composerController.charactersLabel, "Sheet characters label should not be nil") XCTAssertNotNil(composerController.textView, "Sheet text view should not be nil") XCTAssertTrue(CGPointEqualToPoint(composerController.sheetView.frame.origin, CGPointZero), "Initialized sheet view should contain point zero") XCTAssertTrue(composerController.sheetView.frame.width == 0, "Initialized sheet view width should be zero") } func testSheetComposetConstraints () { let composerController = DLFComposerViewController() let view = composerController.view let window = UIApplication.sharedApplication().delegate?.window! view.frame = window!.frame let constraints = composerController.sheetComposerConstraints() XCTAssertNotNil(constraints, "Constraints should not be nil") view.setNeedsLayout() view.layoutIfNeeded() XCTAssertFalse(CGRectEqualToRect(CGRectZero, composerController.sheetView.frame), "Sheet composer controller view should not be zero rect") } func testSheetComposerTitleConstraints () { let composerController = DLFComposerViewController() let view = composerController.view let window = UIApplication.sharedApplication().delegate?.window! view.frame = window!.frame let constraints = composerController.sheetComposerTitleConstraints() XCTAssertNotNil(constraints, "Constraints should not be nil") view.setNeedsLayout() view.layoutIfNeeded() XCTAssertFalse(CGRectEqualToRect(CGRectZero, composerController.cancelButton.frame), "Sheet composer controller cancelButton should not be zero rect") XCTAssertFalse(CGRectEqualToRect(CGRectZero, composerController.nextButton.frame), "Sheet composer controller nextButton should not be zero rect") XCTAssertFalse(CGRectEqualToRect(CGRectZero, composerController.sheetTitle.frame), "Sheet composer controller sheetTitle should not be zero rect") XCTAssertTrue(composerController.sheetTitle.center.y == composerController.cancelButton.center.y, "Cancel button and Title button should be same vertical center") XCTAssertTrue(composerController.sheetTitle.center.y == composerController.nextButton.center.y, "Cancel button and Title button should be same vertical center") } func testCancelButton () { let window = UIWindow(frame: CGRectZero) window.makeKeyAndVisible() let composerController = DLFComposerViewController() let viewController = UIViewController() window.rootViewController = viewController viewController.presentViewController(composerController, animated: false, completion: nil) XCTAssertTrue(composerController.respondsToSelector("didTapCancelButton"), "didTapCancelButton ") let actions = composerController.cancelButton.actionsForTarget(composerController, forControlEvent: UIControlEvents.TouchUpInside) XCTAssertTrue(actions?.count == 1, "Cancel button should have one action for touch up inside") let touchUpInside: AnyObject? = actions?.first XCTAssertEqual(touchUpInside as? String, "didTapCancelButton", "Cancel touch up inside action should be didTapCancelButton") composerController.cancelButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) NSRunLoop.mainRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.4)) XCTAssertNil(viewController.presentedViewController, "Cancel button should dismiss DLFComposerViewController") } func testHeaderLineConstraints () { let composerController = DLFComposerViewController() let view = composerController.view let window = UIApplication.sharedApplication().delegate?.window! view.frame = window!.frame let constraints = composerController.headerLineConstraints() XCTAssertNotNil(constraints, "header line constraints should not be nil") } func testCharactersLabelConstraints () { let composerController = DLFComposerViewController() let view = composerController.view let window = UIApplication.sharedApplication().delegate?.window! view.frame = window!.frame let constraints = composerController.charactersLabelConstraints() XCTAssertNotNil(constraints, "character label constraints should not be nil") } func testTextViewConstraints () { let composerController = DLFComposerViewController() let view = composerController.view let window = UIApplication.sharedApplication().delegate?.window! view.frame = window!.frame let constraints = composerController.textViewConstraints() XCTAssertNotNil(constraints, "text view constraints should not be nil") } func testNextButton () { let composerController = DLFComposerViewController() _ = composerController.view class ComposeDelegate: DLFComposerViewControllerDelegate { var counter = 0 @objc func didTweet(composeViewController: DLFComposerViewController) { ++counter } } let composeDelegate = ComposeDelegate() composerController.delegate = composeDelegate composerController.nextButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) XCTAssertTrue(composeDelegate.counter == 0, "delegate should not be called on tapping next when there are no characters") composerController.numberOfChars = 1 composerController.nextButton.sendActionsForControlEvents(UIControlEvents.TouchUpInside) XCTAssertTrue(composeDelegate.counter != 0, "delegate should be called on tapping next") } func testCharactersTooMany () { let composerController = DLFComposerViewController() _ = composerController.view composerController.textView.text = "we're all stories, in the end. Just make it a good one, eh? Because it was, you know, it was the best: a daft old man, who stole a magic box and ran away. Did I ever tell you I stole it? Well, I borrowed it; I was always going to take it back. Oh, that box, Amy, you'll dream about that box. It'll never leave you. Big and little at the same time, brand-new and ancient, and the bluest blue, ever." composerController.numberOfChars = composerController.textView.text.characters.count XCTAssertFalse(composerController.nextButton.enabled, "Next button should be disabled when character + media url is more than 140") XCTAssertTrue(composerController.charactersLabel.textColor.isEqual(UIColor.redColor()), "Character label should be red when more than 140 characters") } func testTextViewDelegate () { let composerController = DLFComposerViewController() _ = composerController.view XCTAssertTrue(composerController.textView.delegate === composerController, "Text view should have delegate") XCTAssertTrue(composerController.numberOfChars == 0, "Initial number of chars should be zero") composerController.textView.text = "" composerController.textView(composerController.textView, shouldChangeTextInRange: NSMakeRange(0, 0), replacementText: "a") XCTAssertTrue(composerController.numberOfChars == 1, "numberOfChars should be updated when text view delegate is called") XCTAssertTrue(composerController.charactersLabel.text == "116", "when numberOfChars is updated charactersLabel text should be updated too") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
c97f4bcab77bf8745efd45e8487600ff
54.271605
442
0.723587
5.449787
false
true
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Multisig/MultisigViewController.swift
1
28789
// // MultisigViewController.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import UIKit import SwiftyJSON fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } /// The view controller that lets the user manage multisig for the account. final class MultisigViewController: UIViewController { // MARK: - View Controller Properties fileprivate var account: Account? fileprivate var accountData: AccountData? fileprivate var activeAccountData: AccountData? fileprivate var addedCosignatories = [String]() fileprivate var removedCosignatories = [String]() fileprivate var accountChooserViewController: UIViewController? fileprivate var minCosignatoriesUserPreference: Int? // MARK: - View Controller Outlets @IBOutlet weak var multisigAccountChooserButton: AccountChooserButton! @IBOutlet weak var infoHeaderLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var loadingView: UIView! @IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() account = AccountManager.sharedInstance.activeAccount guard account != nil else { print("Critical: Account not available!") return } showLoadingView() updateViewControllerAppearance() fetchAccountData(forAccount: account!) } // MARK: - View Controller Helper Methods /// Updates the appearance (coloring, titles) of the view controller. fileprivate func updateViewControllerAppearance() { title = "MULTISIG".localized() multisigAccountChooserButton.setImage(#imageLiteral(resourceName: "DropDown").imageWithColor(UIColor(red: 90.0/255.0, green: 179.0/255.0, blue: 232.0/255.0, alpha: 1)), for: UIControlState()) tableView.tableFooterView = UIView(frame: CGRect.zero) } /** Updates the info header label with the fetched account data. - Parameter accountData: The fetched account data for the account. */ fileprivate func updateInfoHeaderLabel(withAccountData accountData: AccountData?) { guard accountData != nil else { infoHeaderLabel.attributedText = NSMutableAttributedString(string: "LOST_CONNECTION".localized(), attributes: [NSForegroundColorAttributeName : UIColor.red]) return } let accountTitle = accountData!.title != nil ? accountData!.title! : accountData!.address.nemAddressNormalised() let infoHeaderText = NSMutableAttributedString(string: "\(accountTitle)") infoHeaderLabel.attributedText = infoHeaderText } /** Updates the multisig account chooser button title with the fetched account data. - Parameter accountData: The fetched account data for the account. */ fileprivate func updateAccountChooserButtonTitle(withAccountData accountData: AccountData?) { guard accountData != nil else { multisigAccountChooserButton.setTitle("LOST_CONNECTION".localized(), for: .normal) return } let accountTitle = accountData!.title != nil ? accountData!.title! : accountData!.address.nemAddressNormalised() multisigAccountChooserButton.setTitle(accountTitle, for: .normal) } /** Shows an alert view controller with the provided alert message. - Parameter message: The message that should get shown. - Parameter completion: An optional action that should get performed on completion. */ fileprivate func showAlert(withMessage message: String, completion: ((Void) -> Void)? = nil) { let alert = UIAlertController(title: "INFO".localized(), message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertActionStyle.default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) completion?() })) present(alert, animated: true, completion: nil) } /** Shows the loading view above the table view which shows an spinning activity indicator. */ fileprivate func showLoadingView() { loadingActivityIndicator.startAnimating() loadingView.isHidden = false } /// Hides the loading view. fileprivate func hideLoadingView() { loadingView.isHidden = true loadingActivityIndicator.stopAnimating() } /** Fetches the account data (balance, cosignatories, etc.) for the current account from the active NIS. - Parameter account: The current account for which the account data should get fetched. */ fileprivate func fetchAccountData(forAccount account: Account) { NEMProvider.request(NEM.accountData(accountAddress: account.address)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let json = JSON(data: response.data) let accountData = try json.mapObject(AccountData.self) DispatchQueue.main.async { self?.accountData = accountData self?.activeAccountData = accountData if self?.accountData?.cosignatoryOf.count > 0 { self?.multisigAccountChooserButton.isHidden = false self?.infoHeaderLabel.isHidden = true self?.updateAccountChooserButtonTitle(withAccountData: accountData) } else { self?.multisigAccountChooserButton.isHidden = true self?.infoHeaderLabel.isHidden = false self?.updateInfoHeaderLabel(withAccountData: accountData) } self?.tableView.reloadData() self?.hideLoadingView() } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") } } case let .failure(error): DispatchQueue.main.async { print(error) } } } } /** Fetches the account data (balance, cosignatories, etc.) for the current account from the active NIS. - Parameter accountData: The current account for which the account data should get fetched. */ fileprivate func fetchAccountData(forAccount accountData: AccountData) { addedCosignatories = [String]() removedCosignatories = [String]() NEMProvider.request(NEM.accountData(accountAddress: accountData.address)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let json = JSON(data: response.data) let accountData = try json.mapObject(AccountData.self) DispatchQueue.main.async { self?.activeAccountData = accountData if self?.accountData?.cosignatoryOf.count > 0 { self?.multisigAccountChooserButton.isHidden = false self?.infoHeaderLabel.isHidden = true self?.updateAccountChooserButtonTitle(withAccountData: accountData) } else { self?.multisigAccountChooserButton.isHidden = true self?.infoHeaderLabel.isHidden = false self?.updateInfoHeaderLabel(withAccountData: accountData) } self?.tableView.reloadData() self?.hideLoadingView() } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") } } case let .failure(error): DispatchQueue.main.async { print(error) } } } } /** Signs and announces a new transaction to the NIS. - Parameter transaction: The transaction object that should get signed and announced. */ fileprivate func announceTransaction(_ transaction: Transaction) { let requestAnnounce = TransactionManager.sharedInstance.signTransaction(transaction, account: account!) NEMProvider.request(NEM.announceTransaction(requestAnnounce: requestAnnounce)) { [weak self] (result) in switch result { case let .success(response): do { let _ = try response.filterSuccessfulStatusCodes() let responseJSON = JSON(data: response.data) try self?.validateAnnounceTransactionResult(responseJSON) DispatchQueue.main.async { self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_SUCCESS".localized()) self?.minCosignatoriesUserPreference = nil } } catch TransactionAnnounceValidation.failure(let errorMessage) { DispatchQueue.main.async { print("Failure: \(response.statusCode)") self?.showAlert(withMessage: errorMessage) } } catch { DispatchQueue.main.async { print("Failure: \(response.statusCode)") self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } } case let .failure(error): DispatchQueue.main.async { print(error) self?.showAlert(withMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } } } } /** Validates the response (announce transaction result object) of the NIS regarding the announcement of the transaction. - Parameter responseJSON: The response of the NIS JSON formatted. - Throws: - TransactionAnnounceValidation.Failure if the announcement of the transaction wasn't successful. */ fileprivate func validateAnnounceTransactionResult(_ responseJSON: JSON) throws { guard let responseCode = responseJSON["code"].int else { throw TransactionAnnounceValidation.failure(errorMessage: "TRANSACTION_ANOUNCE_FAILED".localized()) } let responseMessage = responseJSON["message"].stringValue switch responseCode { case 1: return default: throw TransactionAnnounceValidation.failure(errorMessage: responseMessage) } } /** Removes the cosignatory from the table view. - Parameter indexPath: The index path of the cosignatory that should get removed. */ fileprivate func deleteCosignatory(atIndexPath indexPath: IndexPath) { if indexPath.row < activeAccountData!.cosignatories.count { removedCosignatories.append(activeAccountData!.cosignatories[indexPath.row].publicKey) activeAccountData!.cosignatories.remove(at: indexPath.row) } else { addedCosignatories.remove(at: indexPath.row - activeAccountData!.cosignatories.count) } tableView.reloadData() } // MARK: - View Controller Outlet Actions @IBAction func chooseAccount(_ sender: UIButton) { if accountChooserViewController == nil { var accounts = accountData!.cosignatoryOf ?? [] accounts.append(accountData!) let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) let accountChooserViewController = mainStoryboard.instantiateViewController(withIdentifier: "AccountChooserViewController") as! AccountChooserViewController accountChooserViewController.view.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.width, height: tableView.frame.height) accountChooserViewController.view.layer.opacity = 0 accountChooserViewController.delegate = self accountChooserViewController.accounts = accounts self.accountChooserViewController = accountChooserViewController if accounts.count > 0 { view.addSubview(accountChooserViewController.view) UIView.animate(withDuration: 0.2, animations: { accountChooserViewController.view.layer.opacity = 1 }) } } else { accountChooserViewController!.view.removeFromSuperview() accountChooserViewController!.removeFromParentViewController() accountChooserViewController = nil } } @IBAction func unwindToMultisigViewController(_ sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? MultisigAddCosignatoryViewController { let newCosignatoryPublicKey = sourceViewController.newCosignatoryPublicKey addedCosignatories.append(newCosignatoryPublicKey!) tableView.reloadData() } } @IBAction func saveMultisigChanges(_ sender: UIButton) { guard removedCosignatories.count <= 1 else { showAlert(withMessage: "MULTISIG_REMOVE_COUNT_ERROR".localized()) return } guard (activeAccountData!.cosignatories.count + addedCosignatories.count) <= 16 else { showAlert(withMessage: "MULTISIG_COSIGNATORIES_COUNT_ERROR".localized()) return } // TODO: let originalMinCosignatories = (activeAccountData!.minCosignatories == 0 || activeAccountData!.minCosignatories == activeAccountData!.cosignatories.count) ? activeAccountData!.cosignatories.count : activeAccountData!.minCosignatories ?? 0 var relativeChange = 0 if let minCosignatoriesUserPreference = minCosignatoriesUserPreference { if minCosignatoriesUserPreference > originalMinCosignatories { relativeChange = minCosignatoriesUserPreference - originalMinCosignatories } else if minCosignatoriesUserPreference == originalMinCosignatories { relativeChange = 0 } else { relativeChange = minCosignatoriesUserPreference - originalMinCosignatories } print("USER PREFERRED!: \(minCosignatoriesUserPreference) RELCHANGE: \(relativeChange)") } else { for _ in addedCosignatories { relativeChange += 1 } for _ in removedCosignatories { relativeChange -= 1 } print("NO USER PREF: RELCHANGE:\(relativeChange)") } let transactionVersion = 2 let transactionTimeStamp = Int(TimeManager.sharedInstance.currentNetworkTime) var transactionFee = 0.5 let transactionRelativeChange = relativeChange let transactionDeadline = Int(TimeManager.sharedInstance.currentNetworkTime + Constants.transactionDeadline) var transactionSigner = activeAccountData!.publicKey if activeAccountData!.cosignatories.count == 0 { transactionSigner = account!.publicKey } let transaction = MultisigAggregateModificationTransaction(version: transactionVersion, timeStamp: transactionTimeStamp, fee: Int(transactionFee * 1000000), relativeChange: transactionRelativeChange, deadline: transactionDeadline, signer: transactionSigner!) for cosignatoryAccount in addedCosignatories { transaction!.addModification(.addCosignatory, cosignatoryAccount: cosignatoryAccount) } for cosignatoryAccount in removedCosignatories { transaction!.addModification(.deleteCosignatory, cosignatoryAccount: cosignatoryAccount) } // Check if the transaction is a multisig transaction if activeAccountData!.publicKey != account!.publicKey { let multisigTransaction = MultisigTransaction(version: 1, timeStamp: transactionTimeStamp, fee: Int(0.15 * 1000000), deadline: transactionDeadline, signer: account!.publicKey, innerTransaction: transaction!) announceTransaction(multisigTransaction!) return } announceTransaction(transaction!) } @IBAction func minCosignatoriesChanged(_ sender: UITextField) { guard let minCosignatories = Int(sender.text!) else { sender.text = "" minCosignatoriesUserPreference = nil tableView.reloadData() return } let originalMinCosignatories = (activeAccountData!.minCosignatories == 0 || activeAccountData!.minCosignatories == activeAccountData!.cosignatories.count) ? activeAccountData!.cosignatories.count : activeAccountData!.minCosignatories ?? 0 if activeAccountData!.cosignatories.count <= minCosignatories { minCosignatoriesUserPreference = activeAccountData!.cosignatories.count } else if minCosignatories < 0 { minCosignatoriesUserPreference = originalMinCosignatories } else { minCosignatoriesUserPreference = minCosignatories } if minCosignatoriesUserPreference == originalMinCosignatories { sender.text = "" minCosignatoriesUserPreference = nil tableView.reloadData() return } print(minCosignatoriesUserPreference!) sender.text = "" sender.placeholder = "\(String(format: "MIN_COSIG_PLACEHOLDER_CHANGED".localized(), "\(minCosignatoriesUserPreference!)"))" tableView.reloadData() } } // MARK: - Table View Delegate extension MultisigViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let activeAccountData = activeAccountData { if activeAccountData.cosignatories.count > 0 { if accountData == activeAccountData { return activeAccountData.cosignatories.count } else { if addedCosignatories.count > 0 || removedCosignatories.count > 0 || minCosignatoriesUserPreference != nil { return activeAccountData.cosignatories.count + addedCosignatories.count + 3 } else { return activeAccountData.cosignatories.count + addedCosignatories.count + 2 } } } else { if addedCosignatories.count > 0 || removedCosignatories.count > 0 { return addedCosignatories.count + 3 } else { return addedCosignatories.count + 1 } } } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if activeAccountData?.cosignatories.count > 0 { if accountData == activeAccountData { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigCosignatoryTableViewCell") as! MultisigCosignatoryTableViewCell cell.cosignatoryAccountData = activeAccountData!.cosignatories[indexPath.row] return cell } else { if indexPath.row < activeAccountData!.cosignatories.count { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigCosignatoryTableViewCell") as! MultisigCosignatoryTableViewCell cell.cosignatoryAccountData = activeAccountData!.cosignatories[indexPath.row] return cell } else if indexPath.row >= activeAccountData!.cosignatories.count && indexPath.row < activeAccountData!.cosignatories.count + addedCosignatories.count { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigCosignatoryTableViewCell") as! MultisigCosignatoryTableViewCell cell.cosignatoryIdentifier = addedCosignatories[indexPath.row - activeAccountData!.cosignatories.count] return cell } else if indexPath.row == activeAccountData!.cosignatories.count + addedCosignatories.count { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigAddCosignatoryTableViewCell") as! MultisigAddCosignatoryTableViewCell return cell } else if indexPath.row == activeAccountData!.cosignatories.count + addedCosignatories.count + 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigMinimumCosignatoriesTableViewCell") as! MultisigMinimumCosignatoriesTableViewCell let minCosignatories = (activeAccountData!.minCosignatories == 0 || activeAccountData!.minCosignatories == activeAccountData!.cosignatories.count) ? activeAccountData!.cosignatories.count : activeAccountData!.minCosignatories if minCosignatoriesUserPreference == nil { cell.textField.placeholder = String(format: ("MIN_COSIG_PLACEHOLDER".localized()), "\(minCosignatories!)") } return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigSaveChangesTableViewCell") as! MultisigSaveChangesTableViewCell return cell } } } else { if indexPath.row < addedCosignatories.count { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigCosignatoryTableViewCell") as! MultisigCosignatoryTableViewCell cell.cosignatoryIdentifier = addedCosignatories[indexPath.row] return cell } else if indexPath.row == addedCosignatories.count { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigAddCosignatoryTableViewCell") as! MultisigAddCosignatoryTableViewCell return cell } else if indexPath.row == addedCosignatories.count + 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigMinimumCosignatoriesTableViewCell") as! MultisigMinimumCosignatoriesTableViewCell let minCosignatories = addedCosignatories.count cell.textField.placeholder = String(format: ("MIN_COSIG_PLACEHOLDER".localized()), "\(minCosignatories)") return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "MultisigSaveChangesTableViewCell") as! MultisigSaveChangesTableViewCell return cell } } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: deleteCosignatory(atIndexPath: indexPath) default: return } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if activeAccountData?.cosignatories.count > 0 { if accountData == activeAccountData { return false } else { if indexPath.row < activeAccountData!.cosignatories.count { if removedCosignatories.count == 0 { return true } else { return false } } else if indexPath.row >= activeAccountData!.cosignatories.count && indexPath.row < activeAccountData!.cosignatories.count + addedCosignatories.count { return true } else { return false } } } else { if indexPath.row < addedCosignatories.count { return true } else { return false } } } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == addedCosignatories.count + activeAccountData!.cosignatories.count { performSegue(withIdentifier: "showMultisigAddCosignatoryViewController", sender: nil) } } } // MARK: - Account Chooser Delegate extension MultisigViewController: AccountChooserDelegate { func didChooseAccount(_ accountData: AccountData) { activeAccountData = accountData accountChooserViewController?.view.removeFromSuperview() accountChooserViewController?.removeFromParentViewController() accountChooserViewController = nil fetchAccountData(forAccount: accountData) } }
mit
2ea6d6dccd42f8bf8d9fa3670035fb44
38.329235
266
0.563688
5.896968
false
false
false
false
dlrifkin/Perspective-1.0
Perspective/Perspective/LoginVC.swift
2
2770
// // LoginVC.swift // Perspective // // Created by Apprentice on 2/13/15. // Copyright (c) 2015 Dev Bootcamp. All rights reserved. // import UIKit class LoginVC: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtIncompleteFieldsMessage: UILabel! @IBOutlet weak var txtUsername: UITextField! @IBOutlet weak var txtPassword: UITextField! override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().postNotificationName("loggedIn", object: nil) var currentUser = PFUser.currentUser() if currentUser != nil { // Do stuff with the user } else { // Show the signup or login screen } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true; } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { txtUsername.endEditing(true) txtPassword.endEditing(true) } @IBAction func signinTapped(sender: UIButton) { // Authentication Code var usrEntered = txtUsername.text var pwdEntered = txtPassword.text func userLogIn() { PFUser.logInWithUsernameInBackground(usrEntered, password:pwdEntered) { (user: PFUser!, error: NSError!) -> Void in if user != nil { self.txtIncompleteFieldsMessage.text = "Log in successful." self.navigationController?.popToRootViewControllerAnimated(true) } else { self.txtIncompleteFieldsMessage.text = "Log in failed. Please try again." } } } if usrEntered != "" && pwdEntered != "" { userLogIn() } else { self.txtIncompleteFieldsMessage.text = "All Fields Required" } } @IBAction func signupTapped(sender: UIButton) { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("SignupVC") as SignupVC self.navigationController?.pushViewController(vc, animated: true) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */
mit
65c758d5a9f88cbc15fa7f241725c6e6
29.108696
102
0.622744
5.296367
false
false
false
false
arvindhsukumar/PredicateEditor
Example/Pods/SeedStackViewController/StackViewController/StackViewController.swift
1
5150
// // StackViewController.swift // StackViewController // // Created by Indragie Karunaratne on 2016-04-11. // Copyright © 2016 Seed Platform, Inc. All rights reserved. // import UIKit /// Provides a view controller composition based API on top of the /// `StackViewContainer` API. Instead of adding content views directly to a view, /// view controllers that control each content view are added as child view /// controllers via the API exposed in this class. Adding and removing these /// child view controllers is managed automatically. public class StackViewController: UIViewController { /// This is exposed for configuring `backgroundView`, `stackView` /// `axis`, and `separatorViewFactory`. All other operations should /// be performed via this controller and not directly via the container view. public lazy var stackViewContainer = StackViewContainer() private var _items = [StackViewItem]() /// The items displayed by this controller public var items: [StackViewItem] { get { return _items } set(newItems) { for (index, _) in _items.enumerate() { removeItemAtIndex(index) } for item in newItems { addItem(item, canShowSeparator: true) } } } private var viewControllers = [UIViewController]() public override func loadView() { view = stackViewContainer } /** Adds an item to the list of items managed by the controller. The item can be either a `UIView` or a `UIViewController`, both of which conform to the `StackViewItem` protocol. - parameter item: The item to add - parameter canShowSeparator: See the documentation for `StackViewContainer.setCanShowSeparator(:forContentViewAtIndex:)` for more details on this parameter. */ public func addItem(item: StackViewItem, canShowSeparator: Bool = true) { insertItem(item, atIndex: _items.endIndex, canShowSeparator: canShowSeparator) } /** Inserts an item into the list of items managed by the controller. The item can be either a `UIView` or a `UIViewController`, both of which conform to the `StackViewItem` protocol. - parameter item: The item to insert - parameter index: The index to insert the item at - parameter canShowSeparator: See the documentation for `StackViewContainer.setCanShowSeparator(:forContentViewAtIndex:)` for more details on this parameter. */ public func insertItem(item: StackViewItem, atIndex index: Int, canShowSeparator: Bool = true) { precondition(index >= _items.startIndex) precondition(index <= _items.endIndex) _items.insert(item, atIndex: index) let viewController = item.toViewController() viewControllers.insert(viewController, atIndex: index) addChildViewController(viewController) stackViewContainer.insertContentView(viewController.view, atIndex: index, canShowSeparator: canShowSeparator) } /** Removes an item from the list of items managed by this controller. If `item` does not exist in `items`, this method does nothing. - parameter item: The item to remove. */ public func removeItem(item: StackViewItem) { guard let index = _items.indexOf({ $0 === item }) else { return } removeItemAtIndex(index) } /** Removes an item from the list of items managed by this controller. - parameter index: The index of the item to remove */ public func removeItemAtIndex(index: Int) { _items.removeAtIndex(index) let viewController = viewControllers[index] viewController.willMoveToParentViewController(nil) stackViewContainer.removeContentViewAtIndex(index) viewController.removeFromParentViewController() viewControllers.removeAtIndex(index) } /** Sets whether a separator can be shown for `item` - parameter canShowSeparator: See the documentation for `StackViewContainer.setCanShowSeparator(:forContentViewAtIndex:)` for more details on this parameter. - parameter item: The item for which to configure separator visibility */ public func setCanShowSeparator(canShowSeparator: Bool, forItem item: StackViewItem) { guard let index = _items.indexOf({ $0 === item }) else { return } setCanShowSeparator(canShowSeparator, forItemAtIndex: index) } /** Sets whether a separator can be shown for the item at index `index` - parameter canShowSeparator: See the documentation for `StackViewContainer.setCanShowSeparator(:forContentViewAtIndex:)` for more details on this parameter. - parameter index: The index of the item to configure separator visibility for. */ public func setCanShowSeparator(canShowSeparator: Bool, forItemAtIndex index: Int) { stackViewContainer.setCanShowSeparator(canShowSeparator, forContentViewAtIndex: index) } }
mit
4f40d502b5b72ef03aa5f7a67438099b
38.914729
117
0.678578
5.11829
false
false
false
false
nbkey/DouYuTV
DouYu/DouYu/Classes/Tools/NetworkTools.swift
1
2234
// // NetworkTools.swift // DouYu // // Created by 吉冠坤 on 2017/7/25. // Copyright © 2017年 吉冠坤. All rights reserved. // import UIKit import Alamofire enum HttpType { case GET case Post } class NetworkTools { class func requestData(type:HttpType, url:String, parameter:[String: NSString]? = nil, finishCallback:@escaping (_ result:Any)->()) { //1.获取请求类型 let typee = type == .GET ? HTTPMethod.get : HTTPMethod.post //2.请求数据 Alamofire.request(url, method: typee, parameters: parameter).responseJSON() { (response) in //3.回调数据 guard let result = response.result.value else { print(response.result.error) return } finishCallback(result) } } } //首页三个接口均为GET(推荐界面) //https://capi.douyucdn.cn/api/v1/slide/6?version=2.521&client_sys=ios 轮播图的接口 //https://capi.douyucdn.cn/api/v1/getbigDataRoom?client_sys=ios 最热接口 //https://apiv2.douyucdn.cn/live/home/custom?client_sys=ios 颜值,王者荣耀, 移动游戏 //https://capi.douyucdn.cn/api/v1/getHotCate?aid=ios&client_sys=ios&time=1500951060&auth=0e6f4b29864472464216b6b4d2fec87d 英雄联盟以及最下面的 //手游界面接口 //https://capi.douyucdn.cn/api/homeCate/getHotRoom?identification=3e760da75be261a588c74c4830632360&client_sys=ios //娱乐界面接口 //https://capi.douyucdn.cn/api/homeCate/getHotRoom?identification=9acf9c6f117a4c2d02de30294ec29da9&client_sys=ios //游戏界面接口 //https://capi.douyucdn.cn/api/homeCate/getHotRoom?identification=ba08216f13dd1742157412386eee1225&client_sys=ios //趣玩界面 //https://capi.douyucdn.cn/api/homeCate/getHotRoom?identification=393b245e8046605f6f881d415949494c&client_sys=ios //首页粉丝狂欢节活动界面 //https://mconf.douyucdn.cn/resource/common/activity/fans_m.json //各种礼物GIF图之类的接口 //https://capi.douyucdn.cn/api/v1/station_effect?client_sys=ios //https://capi.douyucdn.cn/wb_share/config?client_sys=ios 赛艇起航了之类的 //王者荣耀, 汽车, 守望先锋...18个元素 //https://apiv2.douyucdn.cn/video/ShortVideo/getCateTags?client_sys=ios
mit
de1146a43f5d1326af39b2fa544de898
30.919355
137
0.718039
2.771709
false
false
false
false
ssherar/Swiftly
SwiftlyTests/ListTest.swift
1
2560
// // ListTest.swift // Swiftly // // Created by Sam Sherar on 13/02/2015. // Copyright (c) 2015 Sam Sherar. All rights reserved. // import Foundation import XCTest import Swiftly class ListTest: XCTestCase { var data : List<String>! override func setUp() { super.setUp() self.data = List<String>() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testStackEmpty() { XCTAssert(self.data.isEmpty, "Data structure is not empty") } func testStackPush() { XCTAssert(self.data.isEmpty, "Data structure is not empty") self.data.push("Item 1") XCTAssert(self.data.isEmpty == false, "Data structure is empty") XCTAssert(self.data.count == 1, "Data structure doesn't contain 1 item") } func testStackPeak() { self.data.push("Item 1") XCTAssert(self.data.peak() == "Item 1", "Top of stack doens't equal 'Item 1'") XCTAssert(self.data.count == 1, "Item was removed by using peak") } func testStackPop() { self.data.push("Item 1") self.data.push("Item 2") XCTAssert(self.data.pop() == "Item 2", "Top of stack doesn't equal 'Item 2") XCTAssert(self.data.pop() == "Item 1", "Top of stack doesn't equal 'Item 1") XCTAssert(self.data.count == 0, "Item wasn't removed by using pop") } func testStackEmptyList() { XCTAssert(self.data.peak() == nil, "Peaking an empty list returned an element.") XCTAssert(self.data.pop() == nil, "Pop an empty list returned an element.") } func testEnqueue() { self.data.enqueue("Item 1") XCTAssert(self.data.count == 1, "Enqueue didn't add item at the end of the queue") XCTAssert(self.data.isEmpty == false, "Enqueue didn't add element") } func testDequeue() { self.data.enqueue("Item 1") self.data.enqueue("Item 2") XCTAssert(self.data.dequeue() == "Item 1", "Front of queue doesn't equal 'Item 1'") XCTAssert(self.data.dequeue() == "Item 2", "Front of queue doesn't equal 'Item 2'") XCTAssert(self.data.isEmpty, "Queue isn't empty") } func testDequeueEmptyList() { XCTAssert(self.data.dequeue() == nil, "Dequeue'ing an empty list returned an element.") } }
mit
d7e9761cfef0f60f1ff53557947cc50c
32.684211
111
0.6125
3.950617
false
true
false
false
SoneeJohn/WWDC
PlayerUI/Protocols/PUIExternalPlaybackProvider.swift
1
2190
// // PUIExternalPlaybackProvider.swift // PlayerUI // // Created by Guilherme Rambo on 01/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa public struct PUIExternalPlaybackMediaStatus { /// The rate at which the media is playing (1 = playing. 0 = paused) public var rate: Float /// The current timestamp the media is playing at (in seconds) public var currentTime: Double /// The volume on the external device (between 0 and 1) public var volume: Float public init(rate: Float = 0, volume: Float = 1, currentTime: Double = 0) { self.rate = rate self.volume = volume self.currentTime = currentTime } } public protocol PUIExternalPlaybackProvider: class { /// Initializes the external playback provider to start playing the media at the specified URL /// /// - Parameter consumer: The consumer that's going to be using this provider init(consumer: PUIExternalPlaybackConsumer) /// Whether this provider only works with a remote URL or can be used with only the `AVPlayer` instance var requiresRemoteMediaUrl: Bool { get } /// The name of the external playback system (ex: "AirPlay") static var name: String { get } /// An image to be used as the icon in the UI var icon: NSImage { get } /// A larger image to be used when the provider is current var image: NSImage { get } /// The current media status var status: PUIExternalPlaybackMediaStatus { get } /// Extra information to be displayed on-screen when this playback provider is current var info: String { get } /// Return whether this playback system is available var isAvailable: Bool { get } /// Tells the external playback provider to play func play() /// Tells the external playback provider to pause func pause() /// Tells the external playback provider to seek to the specified time (in seconds) func seek(to timestamp: Double) /// Tells the external playback provider to change the volume on the device /// /// - Parameter volume: The volume (value between 0 and 1) func setVolume(_ volume: Float) }
bsd-2-clause
588d9f40cdff28cd50f15387d430f0cc
29.402778
107
0.684331
4.657447
false
false
false
false