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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dannofx/AudioPal | AudioPal/AudioPal/SettingsTableViewController.swift | 1 | 11376 | //
// SettingsTableViewController.swift
// AudioPal
//
// Created by Danno on 7/4/17.
// Copyright © 2017 Daniel Heredia. All rights reserved.
//
import UIKit
import CoreData
let versionTag = 60
let userNameTag = 61
enum TableSection: Int {
case username = 0
case blockedUsers = 1
case about = 2
var index: Int {
switch self {
case .username:
return 0
case .blockedUsers:
return 1
case .about:
return 2
}
}
var title: String {
switch self {
case .username:
return NSLocalizedString("Username", comment: "")
case .blockedUsers:
return NSLocalizedString("Blocked users", comment: "")
case .about:
return NSLocalizedString("About", comment: "")
}
}
func rowsNumber(_ fetchedController: NSFetchedResultsController<BlockedUser>?) -> Int {
switch self {
case .username:
return 1
case .blockedUsers:
if let count = fetchedController?.sections?[0].numberOfObjects, count > 0 {
return count
} else {
return 1
}
case .about:
return 2
}
}
func cellId(forIndex index: Int, fetchedController: NSFetchedResultsController<BlockedUser>?) -> String {
switch self {
case .username:
return CellIdentifiers.username
case .blockedUsers:
if let count = fetchedController?.sections?[0].numberOfObjects, count > 0 {
return CellIdentifiers.blockedPal
} else {
return CellIdentifiers.noBlockedUsers
}
case .about:
if (index == 0) {
return CellIdentifiers.info
} else {
return CellIdentifiers.version
}
}
}
func segueId(atIndex index: Int) -> String? {
if self == .about && index == 0 {
return StoryboardSegues.about
} else {
return nil
}
}
static let count: Int = {
var max: Int = 0
while let _ = TableSection(rawValue: max) { max += 1 }
return max
}()
}
class SettingsTableViewController: UITableViewController, UITextFieldDelegate {
fileprivate var username: String!
fileprivate var fetchedResultController: NSFetchedResultsController<BlockedUser>!
weak var dataController: DataController!
weak var versionLabel: UILabel?
weak var usernameTextfield: UITextField?
@IBOutlet var saveButton: UIBarButtonItem!
@IBOutlet var cancelButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
username = UserDefaults.standard.value(forKey: StoredValues.username) as? String ?? ""
toggleUsernameButtonsIfNecessary(hidden: true)
fetchedResultController = dataController.createFetchedResultController()
fetchedResultController.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadUsernameField() {
guard let usernameTextfield = usernameTextfield else {
return
}
usernameTextfield.text = username
usernameTextfield.delegate = self
}
func loadVersionLabel() {
guard let versionLabel = versionLabel else {
return
}
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.text = String(format: NSLocalizedString("Version %@", comment: ""), version)
}
}
deinit {
saveButton = nil
cancelButton = nil
}
}
// MARK: - Username management
extension SettingsTableViewController {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
func textFieldDidEndEditing(_ textField: UITextField) {
if textField.text == "" {
textField.text = username
}
}
@IBAction func didChangeText(sender: UITextField) {
let hide = sender.text == "" || sender.text == username
toggleUsernameButtonsIfNecessary(hidden: hide)
}
func toggleUsernameButtonsIfNecessary(hidden: Bool) {
if self.navigationItem.rightBarButtonItem == nil && !hidden {
self.navigationItem.rightBarButtonItem = saveButton
self.navigationItem.leftBarButtonItem = cancelButton
} else if self.navigationItem.rightBarButtonItem != nil && hidden {
self.navigationItem.rightBarButtonItem = nil
self.navigationItem.leftBarButtonItem = nil
}
}
@IBAction func saveUsername(sender: UIBarButtonItem) {
guard let newUsername = usernameTextfield?.text, newUsername != "" else {
return
}
username = newUsername
UserDefaults.standard.setValue(username, forKey: StoredValues.username)
let userInfo: [AnyHashable : Any] = [StoredValues.username: username]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: NotificationNames.userReady),
object: self,
userInfo: userInfo)
toggleUsernameButtonsIfNecessary(hidden: true)
self.view.endEditing(true)
}
@IBAction func cancelUsernameChanges(sender: UIBarButtonItem) {
usernameTextfield?.text = username
toggleUsernameButtonsIfNecessary(hidden: true)
}
}
// MARK: - Table view data source
extension SettingsTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return TableSection.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionVals = TableSection(rawValue: section)!
return sectionVals.rowsNumber(fetchedResultController)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = TableSection(rawValue: indexPath.section)!
let cell = tableView.dequeueReusableCell(withIdentifier: section.cellId(forIndex: indexPath.row, fetchedController: fetchedResultController), for: indexPath)
if let blockedPalCell = cell as? BlockedPalTableViewCell {
let modIndexPath = IndexPath.init(row: indexPath.row, section: 0)
let blockedUser = fetchedResultController.object(at: modIndexPath)
blockedPalCell.configure(withBlockedUser: blockedUser)
blockedPalCell.delegate = self
} else if let label = cell.viewWithTag(versionTag) as? UILabel {
versionLabel = label
loadVersionLabel()
} else if let textfield = cell.viewWithTag(userNameTag) as? UITextField {
usernameTextfield = textfield
loadUsernameField()
}
return cell
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SettingsSectionView.defaultHeight
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionVals = TableSection(rawValue: section)!
let sectionView = Bundle.main.loadNibNamed(String(describing: SettingsSectionView.self), owner: self, options: nil)!.first as! SettingsSectionView
sectionView.titleLabel.text = sectionVals.title
return sectionView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: CGRect.zero)
}
}
// MARK: - Table view delegate
extension SettingsTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sectionVals = TableSection(rawValue: indexPath.section)!
self.view.endEditing(true)
tableView.deselectRow(at: indexPath, animated: true)
if let segueId = sectionVals.segueId(atIndex: indexPath.row) {
self.performSegue(withIdentifier: segueId, sender: self)
}
}
}
// MARK: - Blocked Pal Cell Delegate
extension SettingsTableViewController: BlockedPalTableViewCellDelegate {
func blockedPalCell(_ cell: BlockedPalTableViewCell, didUnblock objectID: NSManagedObjectID) {
let blockedUser = dataController.persistentContainer.viewContext.object(with: objectID) as! BlockedUser
let alertController = UIAlertController(title: NSLocalizedString("Unblock user", comment: ""),
message: String(format: NSLocalizedString("unblock.user %@", comment: ""), blockedUser.username ?? "(unknown)"),
preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("Not", comment: ""), style: UIAlertActionStyle.default))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: ""), style: UIAlertActionStyle.default) { action in
blockedUser.managedObjectContext?.delete(blockedUser)
self.dataController.saveContext()
})
self.present(alertController, animated: true)
}
}
// MARK: - Fetched Result Controller Delegate
extension SettingsTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
let tableIndexPath = IndexPath.init(row: indexPath!.row, section: TableSection.blockedUsers.rawValue)
let tableNewIndexPath = IndexPath.init(row: newIndexPath!.row, section: TableSection.blockedUsers.rawValue)
switch type {
case .insert:
tableView.insertRows(at: [tableNewIndexPath], with: .automatic)
case .delete:
tableView.deleteRows(at: [tableIndexPath], with: .automatic)
if controller.sections![0].numberOfObjects == 0 {
tableView.insertRows(at: [tableIndexPath], with: .automatic) // this cell will show the "empty" message
}
case .update:
let cell = tableView.cellForRow(at: tableIndexPath) as! BlockedPalTableViewCell
let blockedUser = fetchedResultController.object(at: indexPath!)
cell.configure(withBlockedUser: blockedUser)
case .move:
tableView.deleteRows(at: [tableIndexPath], with: .automatic)
tableView.insertRows(at: [tableNewIndexPath], with: .automatic)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| mit | 9e64872a1a3738ddef41a393ee9c2f91 | 36.417763 | 200 | 0.64633 | 5.622837 | false | false | false | false |
jeroendesloovere/swifter | SwifterCommon/NSURL+Swifter.swift | 4 | 1726 | //
// NSURL+Swifter.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
extension NSURL {
func URLByAppendingQueryString(queryString: String) -> NSURL {
if queryString.utf16count == 0 {
return self
}
var absoluteURLString = self.absoluteString
if absoluteURLString.hasSuffix("?") {
absoluteURLString = absoluteURLString.substringToIndex(absoluteURLString.utf16count - 1)
}
let URLString = absoluteURLString + (absoluteURLString.rangeOfString("?") ? "&" : "?") + queryString
return NSURL(string: URLString)
}
}
| mit | 2da90116342be9a596144a665e65a5a9 | 35.723404 | 108 | 0.71321 | 4.627346 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS | Mr-Ride-iOS/Mr-Ride-iOS/TrackingViewController.swift | 1 | 10230 | //
// RidingViewController.swift
// Mr-Ride-iOS
//
// Created by Derek on 5/24/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import UIKit
import MapKit
import CoreData
import CoreLocation
protocol TrackingDelegate: class {
func dismissVC()
}
class TrackingViewController: UIViewController {
@IBOutlet weak var labelCurrentDistance: UILabel!
@IBOutlet weak var labelSpeed: UILabel!
@IBOutlet weak var labelCalories: UILabel!
@IBOutlet weak var labelTimer: UILabel!
@IBOutlet weak var btnStartAndPause: UIButton!
@IBOutlet weak var mapViewContainer: UIView!
weak var dismissDelegate: TrackingDelegate?
// temp
var managedObjectContext: NSManagedObjectContext?
var calorieCalcultor = CalorieCalculator()
var isRidding = false
var btnCancel: UIBarButtonItem?
var btnFinish: UIBarButtonItem?
var counter = 0.0
var timer = NSTimer()
var calories = 0.0
let mapViewController = MapViewController()
let middleIcon = UIView()
override func viewDidLoad() {
super.viewDidLoad()
setupMap()
setupDistance()
setupSpeed()
setupCalories()
setupTimer()
setupButton()
setupBackground()
TrackingActionHelper.getInstance().trackingAction(viewName: "record_creating", action: "view_in_record_creating")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
print("viewWillDisappear \(self.dynamicType)")
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
print("viewDidDisappear \(self.dynamicType)")
}
deinit {
print("deinit \(self.dynamicType)")
}
func setupBackground() {
let color1 = UIColor.mrBlack60Color()
let color2 = UIColor.mrBlack40Color()
let gradient = CAGradientLayer()
gradient.frame = self.view.frame
gradient.colors = [color1.CGColor, color2.CGColor]
view.layer.insertSublayer(gradient, atIndex: 0)
view.backgroundColor = UIColor.clearColor()
navigationController?.navigationBar.barTintColor = UIColor.mrLightblueColor()
navigationController?.navigationBar.translucent = false
}
func setupDistance() {
labelCurrentDistance.text = String(format: "%.2f km", mapViewController.distance / 1000)
}
func setupSpeed() {
labelSpeed.text = String(format: "%.2f m/s", mapViewController.distance / counter)
}
func setupCalories() {
calories = calorieCalcultor.kiloCalorieBurned(.Bike, speed: (mapViewController.distance / 1000) / (counter / 3600) , weight: 60.0, time: counter / 3600)
labelCalories.text = String(format: "%.2f Kcal", calories)
}
func setupTimer() {
let minuteSecond = Int(counter % 1 * 100)
let second = Int(counter) % 60
let minutes = Int(counter / 60) % 60
let hours = Int(counter / 60 / 60) % 99
// print(minuteSecond)
labelTimer.text = String(format: "%02d:%02d:%02d.%02d", hours, minutes, second, minuteSecond)
counter = counter + 0.05
// print(counter)
}
func eachSecond() {
setupDistance()
setupSpeed()
setupCalories()
setupTimer()
}
func setupButton() {
btnStartAndPause.addTarget(self, action: #selector(startAndStopRidding), forControlEvents: UIControlEvents.TouchUpInside)
btnStartAndPause.layer.cornerRadius = btnStartAndPause.frame.size.width / 2
btnStartAndPause.layer.borderColor = UIColor.whiteColor().CGColor
btnStartAndPause.layer.borderWidth = 3.0
btnStartAndPause.backgroundColor = UIColor.clearColor()
btnStartAndPause.clipsToBounds = true
middleIcon.frame.size = CGSize(width: 30, height: 30)
middleIcon.userInteractionEnabled = false
middleIcon.backgroundColor = UIColor.redColor()
middleIcon.center = CGPoint(x: btnStartAndPause.bounds.width / 2, y: btnStartAndPause.bounds.height / 2)
btnStartAndPause.addSubview(middleIcon)
btnCancel = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain , target: self , action: #selector(dismissSelf))
btnFinish = UIBarButtonItem(title: "Finish", style: UIBarButtonItemStyle.Plain , target: self , action: #selector(finishRidding))
navigationItem.leftBarButtonItem = btnCancel
navigationItem.rightBarButtonItem = btnFinish
navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor()
btnFinish?.enabled = false
btnFinish?.tintColor = UIColor.clearColor()
}
func setupMap() {
mapViewContainer.layer.cornerRadius = 10
mapViewController.view.frame = mapViewContainer.bounds
mapViewController.view.layer.cornerRadius = 10
mapViewController.view.clipsToBounds = true
self.addChildViewController(mapViewController)
mapViewContainer.addSubview(mapViewController.view)
mapViewController.didMoveToParentViewController(self)
}
func startAndStopRidding() {
if isRidding {
// stop them
isRidding = false
timer.invalidate()
mapViewController.locationManager.stopUpdatingLocation()
UIView.animateWithDuration(0.6){
self.middleIcon.transform = CGAffineTransformMakeScale(1 , 1)
self.middleIcon.layer.cornerRadius = (self.middleIcon.frame.width) / 2
}
UIView.animateWithDuration(0.6,delay: 0.0,options: .TransitionFlipFromLeft, animations:{
self.middleIcon.transform = CGAffineTransformMakeScale(1, 1)
},completion: { (isFinished) in
self.addIconCornerRadiusAnimation( 10, to: (self.middleIcon.frame.width) / 2, duration: 0.3)
})
TrackingActionHelper.getInstance().trackingAction(viewName: "record_creating", action: "select_pause_in_record_creating")
} else {
isRidding = true
timer = NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: #selector(eachSecond), userInfo: nil, repeats: true)
// NSDate apply here
// GCD
mapViewController.locationManager.startUpdatingLocation()
UIView.animateWithDuration(0.6,delay: 0.0,options: .TransitionFlipFromLeft, animations:{
self.middleIcon.transform = CGAffineTransformMakeScale(1, 1)
},completion: { (isFinished) in
self.addIconCornerRadiusAnimation( (self.middleIcon.frame.width) / 2, to: 10, duration: 0.3)
})
btnFinish?.enabled = true
btnFinish?.tintColor = UIColor.whiteColor()
TrackingActionHelper.getInstance().trackingAction(viewName: "record_creating", action: "select_start_in_record_creating")
}
}
func dismissSelf(sender: AnyObject) {
timer.invalidate()
mapViewController.removeFromParentViewController()
mapViewController.locationManager.stopUpdatingLocation()
dismissDelegate?.dismissVC()
dismissViewControllerAnimated(true, completion: nil)
TrackingActionHelper.getInstance().trackingAction(viewName: "record_creating", action: "select_cancel_in_record_creating")
// dismissDelegate = nil
}
func finishRidding(sender: AnyObject) {
timer.invalidate()
let runID = NSUUID().UUIDString
savedRun(runID)
let statisticViewController = storyboard?.instantiateViewControllerWithIdentifier("StatisticViewController") as! StatisticViewController
statisticViewController.runID = runID
statisticViewController.dismissDelegate = dismissDelegate
navigationController?.pushViewController(statisticViewController, animated: true)
mapViewController.locationManager.stopUpdatingLocation()
TrackingActionHelper.getInstance().trackingAction(viewName: "record_creating", action: "select_finish_in_record_creating")
}
func savedRun(runID: String) {
// let date = NSDate()
let days = -2.0
let date = NSDate.init(timeIntervalSinceNow: 86400.00 * days)
let savedRun = NSEntityDescription.insertNewObjectForEntityForName("Run", inManagedObjectContext: moc) as! Run
savedRun.id = runID
savedRun.distance = mapViewController.distance
savedRun.during = counter
// savedRun.timestamp = NSDate()
savedRun.timestamp = date
savedRun.calorie = calories
// 2
var savedLocations = [Location]()
for location in mapViewController.locations {
let savedLocation = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: moc) as! Location
savedLocation.id = runID
savedLocation.timestamp = location.timestamp
savedLocation.latitude = location.coordinate.latitude
savedLocation.longitude = location.coordinate.longitude
savedLocations.append(savedLocation)
}
savedRun.location = NSOrderedSet(array: savedLocations)
do {
try moc.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
func addIconCornerRadiusAnimation(from: CGFloat, to: CGFloat, duration: CFTimeInterval)
{
let animation = CABasicAnimation(keyPath:"cornerRadius")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.fromValue = from
animation.toValue = to
animation.duration = duration
self.middleIcon.layer.addAnimation(animation, forKey: "cornerRadius")
self.middleIcon.layer.cornerRadius = to
}
}
| mit | 0dc35c48229f8cd56efa2bdabaf4075b | 37.746212 | 160 | 0.655196 | 5.33316 | false | false | false | false |
richardpiazza/LCARSDisplayKit | Sources/LCARSDisplayKitUI/RoundedRectangleButton.swift | 1 | 1177 | #if canImport(LCARSDisplayKit)
import LCARSDisplayKit
#endif
#if (os(iOS) || os(tvOS))
import UIKit
import GraphPoint
/// A rectangular button with options for rounding left/right edges.
@IBDesignable open class RoundedRectangleButton: Button {
public static let defaultSize: CGSize = CGSize(width: 144, height: 60)
@IBInspectable open var roundLeft: Bool {
get {
return rectangle.leftRounded
}
set {
rectangle.leftRounded = newValue
}
}
@IBInspectable open var roundRight: Bool {
get {
return rectangle.rightRounded
}
set {
rectangle.rightRounded = newValue
}
}
@IBInspectable open var isFrame: Bool {
get {
return rectangle.cornersOnly
}
set {
rectangle.cornersOnly = newValue
}
}
open override var intrinsicContentSize: CGSize {
return type(of: self).defaultSize
}
public convenience init(with frame: CGRect, roundedRectangle: RoundedRectangle) {
self.init(frame: frame)
self.rectangle = roundedRectangle
}
}
#endif
| mit | dce4114c73c58ddc400a3081e98e8b41 | 23.520833 | 85 | 0.609176 | 4.863636 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceComponents/Tests/DealersComponentTests/Presenter Tests/WhenBindingDealerSearchResultGroupHeading_DealersPresenterShould.swift | 1 | 833 | import DealersComponent
import EurofurenceModel
import XCTest
class WhenBindingDealerSearchResultGroupHeading_DealersPresenterShould: XCTestCase {
func testBindTheGroupHeadingOntoTheComponent() {
let groups = [DealersGroupViewModel].random
let randomGroup = groups.randomElement()
let expected = randomGroup.element.title
let searchViewModel = CapturingDealersSearchViewModel(dealerGroups: groups)
let viewModelFactory = FakeDealersViewModelFactory(searchViewModel: searchViewModel)
let context = DealersPresenterTestBuilder().with(viewModelFactory).build()
context.simulateSceneDidLoad()
let component = context.makeAndBindComponentHeader(forSearchResultGroupAt: randomGroup.index)
XCTAssertEqual(expected, component.capturedDealersGroupTitle)
}
}
| mit | 32a4ed7849461bf9268c85c541fa2e38 | 40.65 | 101 | 0.781513 | 5.992806 | false | true | false | false |
ello/ello-ios | Sources/Utilities/TemporaryCache.swift | 1 | 1238 | ////
/// TemporaryCache.swift
//
struct TemporaryCache {
typealias Entry = (data: Any, expiration: Date)
enum Key {
case avatar
case coverImage
case categories
}
private static var cache: [Key: Entry] = [:]
static func clear() {
TemporaryCache.cache = [:]
}
static func save(_ prop: Profile.ImageProperty, image: UIImage) {
let key: Key
switch prop {
case .avatar: key = .avatar
case .coverImage: key = .coverImage
}
save(key, image)
}
static func save(_ key: Key, _ data: Any, expires: TimeInterval = 5) {
let fiveMinutes: TimeInterval = expires * 60
let date = Date(timeIntervalSinceNow: fiveMinutes)
cache[key] = (data: data, expiration: date)
}
static func load(_ prop: Profile.ImageProperty) -> UIImage? {
let key: Key
switch prop {
case .avatar: key = .avatar
case .coverImage: key = .coverImage
}
return load(key)
}
static func load<T>(_ key: Key) -> T? {
guard
let entry = cache[key],
entry.expiration > Globals.now
else { return nil }
return entry.data as? T
}
}
| mit | d4aabe279b393e25afe655965ebe3e37 | 22.807692 | 74 | 0.553312 | 4.254296 | false | false | false | false |
BellAppLab/JustTest | JustTest/JustTest/LocationController.swift | 1 | 2931 | //
// LocationController.swift
// JustTest
//
// Created by André Abou Chami Campana on 06/04/2016.
// Copyright © 2016 Bell App Lab. All rights reserved.
//
import Foundation
import CoreLocation
//MARK: Location Controller Delegate
/*
Instead of relying on callbacks to handle requests to the API, we're handling responses via a delegate
This is so we avoid a bit of the spaghettiness of completion blocks
*/
protocol LocationControllerDelegate: AnyObject
{
func willStartSearchingLocation()
func didFinishSearchingLocation()
}
//MARK:
/*
This controller is intended to be the main API between the rest of the app and Location objects.
By being one step removed from dealing directly with the data model, we reduce the odds of breaking the rest of the app when changing the way we handle data coming in.
Instances of this class are meant to be plugged into View Controllers through Interface Builder.
*/
final class LocationController: NSObject
{
//MARK: Delegate
weak var delegate: LocationControllerDelegate?
//MARK: Search Params
//This is meant to store the coordinates in the API's response
//We default to London
lazy var location = CLLocation(latitude: 51.51678600, longitude: -0.13162300)
private func setCoordinates(coords: [String: String]) {
guard let latitude = Double(coords["lat"] ?? ""), let longitude = Double(coords["lng"] ?? "") else { return }
self.location = CLLocation(latitude: latitude, longitude: longitude)
}
//MARK: Searching
private(set) lazy var results = [Location]()
func search(withName name: String) {
guard !name.isEmpty else { return }
self.search(name.lowercaseString.stringByReplacingOccurrencesOfString(" ", withString: "+"))
}
func search(withLocation location: CLLocation) {
self.search(withCoordinates: location.coordinate)
}
func search(withCoordinates coordinates: CLLocationCoordinate2D) {
self.search(coordinates.coordinatesString)
}
private func search(string: String) {
self.delegate?.willStartSearchingLocation()
request(.GET, "https://api.justpark.com/1.1/location/", parameters: ["q": string]).responseJSON { [weak self] (response: Response<AnyObject, NSError>) in
if let JSON = response.result.value {
if let coords = JSON["coords"] as? [String: String] {
self?.setCoordinates(coords)
}
if let results = JSON["data"] as? [[String: AnyObject]] {
self?.results = Location.collection(response: response.response!, representation: results)
}
}
self?.delegate?.didFinishSearchingLocation()
}
}
}
//MARK: Aux
extension CLLocationCoordinate2D
{
var coordinatesString: String {
return "\(self.latitude)+\(self.longitude)"
}
}
| mit | 9d56cbf67aa6b12c7ac1e2c065fe8e1e | 33.869048 | 168 | 0.67395 | 4.55521 | false | false | false | false |
luojunwei1992/goodjob | ljwb/ljwb/AppDelegate.swift | 1 | 935 | //
// AppDelegate.swift
// ljwb
//
// Created by comma on 16/5/16.
// Copyright © 2016年 lj. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//设置导航条和tabbar外观
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = MainTabBarController()
window?.makeKeyAndVisible()
return true
}
}
| mit | 704f21184b34c34559ac80b7b2613f5a | 22.487179 | 127 | 0.643013 | 5.452381 | false | false | false | false |
brave/browser-ios | brave/src/data/FaviconMO.swift | 1 | 2110 | /* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import CoreData
import Foundation
import Storage
public final class FaviconMO: NSManagedObject, CRUD {
@NSManaged public var url: String?
@NSManaged public var width: Int16
@NSManaged public var height: Int16
@NSManaged public var type: Int16
@NSManaged public var domain: Domain?
// Necessary override due to bad classname, maybe not needed depending on future CD
static func entity(_ context: NSManagedObjectContext) -> NSEntityDescription {
return NSEntityDescription.entity(forEntityName: "Favicon", in: context)!
}
public class func get(forFaviconUrl urlString: String, context: NSManagedObjectContext) -> FaviconMO? {
let urlKeyPath = #keyPath(FaviconMO.url)
let predicate = NSPredicate(format: "\(urlKeyPath) == %@", urlString)
return first(where: predicate, context: context)
}
public class func add(_ favicon: Favicon, forSiteUrl siteUrl: URL) {
let context = DataController.newBackgroundContext()
context.perform {
var item = FaviconMO.get(forFaviconUrl: favicon.url, context: context)
if item == nil {
item = FaviconMO(entity: FaviconMO.entity(context), insertInto: context)
item!.url = favicon.url
}
if item?.domain == nil {
item!.domain = Domain.getOrCreateForUrl(siteUrl, context: context)
}
let w = Int16(favicon.width ?? 0)
let h = Int16(favicon.height ?? 0)
let t = Int16(favicon.type.rawValue)
if w != item!.width && w > 0 {
item!.width = w
}
if h != item!.height && h > 0 {
item!.height = h
}
if t != item!.type {
item!.type = t
}
DataController.save(context: context)
}
}
}
| mpl-2.0 | 9f24e4bb0b6d901a0068f5e48aa0e4c3 | 34.762712 | 198 | 0.602844 | 4.678492 | false | false | false | false |
codestergit/swift | test/SILGen/copy_lvalue_peepholes.swift | 3 | 2061 | // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
var zero = getInt()
func getInt() -> Int { return zero }
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes014init_var_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[X:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[PBX:%.*]] = project_box [[X]]
// CHECK: [[Y:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[PBY:%.*]] = project_box [[Y]]
// CHECK: copy_addr [[PBX]] to [initialization] [[PBY]] : $*Builtin.Int64
func init_var_from_lvalue(x: Int) {
var x = x
var y = x
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes016assign_var_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[Y:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[PBY:%.*]] = project_box [[Y]]
// CHECK: copy_addr [[PBY]] to %0
func assign_var_from_lvalue(x: inout Int, y: Int) {
var y = y
x = y
}
// -- Peephole doesn't apply to computed lvalues
var computed: Int {
get {
return zero
}
set {}
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes023init_var_from_computed_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fg
// CHECK: [[GOTTEN:%.*]] = apply [[GETTER]]()
// CHECK: store [[GOTTEN]] to [trivial] {{%.*}}
func init_var_from_computed_lvalue() {
var y = computed
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes021assign_computed_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[Y:%.*]] = alloc_box
// CHECK: [[PBY:%.*]] = project_box [[Y]]
// CHECK: [[Y_VAL:%.*]] = load [trivial] [[PBY]]
// CHECK: [[SETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fs
// CHECK: apply [[SETTER]]([[Y_VAL]])
func assign_computed_from_lvalue(y: Int) {
var y = y
computed = y
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes24assign_var_from_computed{{[_0-9a-zA-Z]*}}F
// CHECK: assign {{%.*}} to %0
func assign_var_from_computed(x: inout Int) {
x = computed
}
| apache-2.0 | 028389ccfa650d5352229c7451acfea0 | 32.241935 | 100 | 0.61475 | 2.935897 | false | false | false | false |
sdaheng/DFITableViewManager | Carthage/Checkouts/ReactiveSwift/Tests/ReactiveSwiftTests/SignalProducerSpec.swift | 2 | 82158 | //
// SignalProducerSpec.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2015-01-23.
// Copyright (c) 2015 GitHub. All rights reserved.
//
import Dispatch
import Foundation
import Result
import Nimble
import Quick
import ReactiveSwift
class SignalProducerSpec: QuickSpec {
override func spec() {
describe("init") {
it("should run the handler once per start()") {
var handlerCalledTimes = 0
let signalProducer = SignalProducer<String, NSError> { _, _ in
handlerCalledTimes += 1
return
}
signalProducer.start()
signalProducer.start()
expect(handlerCalledTimes) == 2
}
it("should not release signal observers when given disposable is disposed") {
var lifetime: Lifetime!
let producer = SignalProducer<Int, NoError> { observer, innerLifetime in
lifetime = innerLifetime
innerLifetime.observeEnded {
// This is necessary to keep the observer long enough to
// even test the memory management.
observer.send(value: 0)
}
}
weak var objectRetainedByObserver: NSObject?
var disposable: Disposable!
producer.startWithSignal { signal, interruptHandle in
disposable = interruptHandle
let object = NSObject()
objectRetainedByObserver = object
signal.observeValues { _ in _ = object }
}
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
expect(objectRetainedByObserver).to(beNil())
}
it("should dispose of added disposables upon completion") {
let addedDisposable = AnyDisposable()
var observer: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError> { incomingObserver, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendCompleted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon error") {
let addedDisposable = AnyDisposable()
var observer: Signal<(), TestError>.Observer!
let producer = SignalProducer<(), TestError> { incomingObserver, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.send(error: .default)
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon interruption") {
let addedDisposable = AnyDisposable()
var observer: Signal<(), NoError>.Observer!
let producer = SignalProducer<(), NoError> { incomingObserver, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendInterrupted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon start() disposal") {
let addedDisposable = AnyDisposable()
let producer = SignalProducer<(), TestError> { _, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
return
}
let startDisposable = producer.start()
expect(addedDisposable.isDisposed) == false
startDisposable.dispose()
expect(addedDisposable.isDisposed) == true
}
it("should deliver the interrupted event with respect to the applied asynchronous operators") {
let scheduler = TestScheduler()
var signalInterrupted = false
var observerInterrupted = false
let (signal, _) = Signal<Int, NoError>.pipe()
SignalProducer(signal)
.observe(on: scheduler)
.on(interrupted: { signalInterrupted = true })
.startWithInterrupted { observerInterrupted = true }
.dispose()
expect(signalInterrupted) == false
expect(observerInterrupted) == false
scheduler.run()
expect(signalInterrupted) == true
expect(observerInterrupted) == true
}
}
describe("init(signal:)") {
var signal: Signal<Int, TestError>!
var observer: Signal<Int, TestError>.Observer!
beforeEach {
// Cannot directly assign due to compiler crash on Xcode 7.0.1
let (signalTemp, observerTemp) = Signal<Int, TestError>.pipe()
signal = signalTemp
observer = observerTemp
}
it("should emit values then complete") {
let producer = SignalProducer<Int, TestError>(signal)
var values: [Int] = []
var error: TestError?
var completed = false
producer.start { event in
switch event {
case let .value(value):
values.append(value)
case let .failed(err):
error = err
case .completed:
completed = true
default:
break
}
}
expect(values) == []
expect(error).to(beNil())
expect(completed) == false
observer.send(value: 1)
expect(values) == [ 1 ]
observer.send(value: 2)
observer.send(value: 3)
expect(values) == [ 1, 2, 3 ]
observer.sendCompleted()
expect(completed) == true
}
it("should emit error") {
let producer = SignalProducer<Int, TestError>(signal)
var error: TestError?
let sentError = TestError.default
producer.start { event in
switch event {
case let .failed(err):
error = err
default:
break
}
}
expect(error).to(beNil())
observer.send(error: sentError)
expect(error) == sentError
}
}
describe("init(value:)") {
it("should immediately send the value then complete") {
let producerValue = "StringValue"
let signalProducer = SignalProducer<String, NSError>(value: producerValue)
expect(signalProducer).to(sendValue(producerValue, sendError: nil, complete: true))
}
}
describe("init closure overloading") {
it("should be inferred and overloaded without ambiguity") {
let action: () -> String = { "" }
let throwableAction: () throws -> String = { "" }
let resultAction1: () -> Result<String, NoError> = { .success("") }
let resultAction2: () -> Result<String, AnyError> = { .success("") }
let throwableResultAction: () throws -> Result<String, NoError> = { .success("") }
expect(type(of: SignalProducer(action))) == SignalProducer<String, AnyError>.self
expect(type(of: SignalProducer<String, NoError>(action))) == SignalProducer<String, NoError>.self
expect(type(of: SignalProducer<String, TestError>(action))) == SignalProducer<String, TestError>.self
expect(type(of: SignalProducer(resultAction1))) == SignalProducer<String, NoError>.self
expect(type(of: SignalProducer(resultAction2))) == SignalProducer<String, AnyError>.self
expect(type(of: SignalProducer(throwableAction))) == SignalProducer<String, AnyError>.self
expect(type(of: SignalProducer(throwableResultAction))) == SignalProducer<Result<String, NoError>, AnyError>.self
}
}
describe("init(_:) lazy value") {
it("should not evaluate the supplied closure until started") {
var evaluated: Bool = false
func lazyGetter() -> String {
evaluated = true
return "🎃"
}
let lazyProducer = SignalProducer<String, NoError>(lazyGetter)
expect(evaluated).to(beFalse())
expect(lazyProducer).to(sendValue("🎃", sendError: nil, complete: true))
expect(evaluated).to(beTrue())
}
}
describe("init(error:)") {
it("should immediately send the error") {
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let signalProducer = SignalProducer<Int, NSError>(error: producerError)
expect(signalProducer).to(sendValue(nil, sendError: producerError, complete: false))
}
}
describe("init(result:)") {
it("should immediately send the value then complete") {
let producerValue = "StringValue"
let producerResult = .success(producerValue) as Result<String, NSError>
let signalProducer = SignalProducer(result: producerResult)
expect(signalProducer).to(sendValue(producerValue, sendError: nil, complete: true))
}
it("should immediately send the error") {
let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let producerResult = .failure(producerError) as Result<String, NSError>
let signalProducer = SignalProducer(result: producerResult)
expect(signalProducer).to(sendValue(nil, sendError: producerError, complete: false))
}
}
describe("init(values:)") {
it("should immediately send the sequence of values") {
let sequenceValues = [1, 2, 3]
let signalProducer = SignalProducer<Int, NSError>(sequenceValues)
expect(signalProducer).to(sendValues(sequenceValues, sendError: nil, complete: true))
}
}
describe("SignalProducer.empty") {
it("should immediately complete") {
let signalProducer = SignalProducer<Int, NSError>.empty
expect(signalProducer).to(sendValue(nil, sendError: nil, complete: true))
}
}
describe("SignalProducer.never") {
it("should not send any events while still being alive") {
let signalProducer = SignalProducer<Int, NSError>.never
var numberOfEvents = 0
var isDisposed = false
func scope() -> Disposable {
defer {
expect(numberOfEvents) == 0
expect(isDisposed) == false
}
return signalProducer.on(disposed: { isDisposed = true }).start { _ in numberOfEvents += 1 }
}
let d = scope()
expect(numberOfEvents) == 0
expect(isDisposed) == false
d.dispose()
expect(numberOfEvents) == 1
expect(isDisposed) == true
}
it("should not send any events while still being alive even if the interrupt handle deinitializes") {
let signalProducer = SignalProducer<Int, NSError>.never
var numberOfEvents = 0
var isDisposed = false
func scope() {
signalProducer.on(disposed: { isDisposed = false }).start { _ in numberOfEvents += 1 }
expect(numberOfEvents) == 0
expect(isDisposed) == false
}
scope()
expect(numberOfEvents) == 0
expect(isDisposed) == false
}
}
describe("trailing closure") {
it("receives next values") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
var values = [Int]()
producer.startWithValues { value in
values.append(value)
}
observer.send(value: 1)
expect(values) == [1]
}
}
describe("init(_:) lazy result") {
it("should run the operation once per start()") {
var operationRunTimes = 0
let operation: () -> Result<String, NSError> = {
operationRunTimes += 1
return .success("OperationValue")
}
SignalProducer(operation).start()
SignalProducer(operation).start()
expect(operationRunTimes) == 2
}
it("should send the value then complete") {
let operationReturnValue = "OperationValue"
let operation: () -> Result<String, NSError> = {
return .success(operationReturnValue)
}
let signalProducer = SignalProducer(operation)
expect(signalProducer).to(sendValue(operationReturnValue, sendError: nil, complete: true))
}
it("should send the error") {
let operationError = NSError(domain: "com.reactivecocoa.errordomain", code: 4815, userInfo: nil)
let operation: () -> Result<String, NSError> = {
return .failure(operationError)
}
let signalProducer = SignalProducer(operation)
expect(signalProducer).to(sendValue(nil, sendError: operationError, complete: false))
}
}
describe("init(_:) throwable lazy value") {
it("should send a successful value then complete") {
let operationReturnValue = "OperationValue"
let signalProducer = SignalProducer<String, AnyError> { () throws -> String in
operationReturnValue
}
var error: Error?
signalProducer.startWithFailed {
error = $0
}
expect(error).to(beNil())
}
it("should send the error") {
let operationError = TestError.default
let signalProducer = SignalProducer<String, AnyError> { () throws -> String in
throw operationError
}
var error: TestError?
signalProducer.startWithFailed {
error = $0.error as? TestError
}
expect(error) == operationError
}
}
describe("startWithSignal") {
it("should invoke the closure before any effects or events") {
var started = false
var value: Int?
SignalProducer<Int, NoError>(value: 42)
.on(started: {
started = true
}, value: {
value = $0
})
.startWithSignal { _, _ in
expect(started) == false
expect(value).to(beNil())
}
expect(started) == true
expect(value) == 42
}
it("should dispose of added disposables if disposed") {
let addedDisposable = AnyDisposable()
var disposable: Disposable!
let producer = SignalProducer<Int, NoError> { _, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
return
}
producer.startWithSignal { signal, innerDisposable in
signal.observe { _ in }
disposable = innerDisposable
}
expect(addedDisposable.isDisposed) == false
disposable.dispose()
expect(addedDisposable.isDisposed) == true
}
it("should send interrupted if disposed") {
var interrupted = false
var disposable: Disposable!
SignalProducer<Int, NoError>(value: 42)
.start(on: TestScheduler())
.startWithSignal { signal, innerDisposable in
signal.observeInterrupted {
interrupted = true
}
disposable = innerDisposable
}
expect(interrupted) == false
disposable.dispose()
expect(interrupted) == true
}
it("should release signal observers if disposed") {
weak var objectRetainedByObserver: NSObject?
var disposable: Disposable!
let producer = SignalProducer<Int, NoError>.never
producer.startWithSignal { signal, innerDisposable in
let object = NSObject()
objectRetainedByObserver = object
signal.observeValues { _ in _ = object.description }
disposable = innerDisposable
}
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
expect(objectRetainedByObserver).to(beNil())
}
it("should not trigger effects if disposed before closure return") {
var started = false
var value: Int?
SignalProducer<Int, NoError>(value: 42)
.on(started: {
started = true
}, value: {
value = $0
})
.startWithSignal { _, disposable in
expect(started) == false
expect(value).to(beNil())
disposable.dispose()
}
expect(started) == false
expect(value).to(beNil())
}
it("should send interrupted if disposed before closure return") {
var interrupted = false
SignalProducer<Int, NoError>(value: 42)
.startWithSignal { signal, disposable in
expect(interrupted) == false
signal.observeInterrupted {
interrupted = true
}
disposable.dispose()
}
expect(interrupted) == true
}
it("should dispose of added disposables upon completion") {
let addedDisposable = AnyDisposable()
var observer: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError> { incomingObserver, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.sendCompleted()
expect(addedDisposable.isDisposed) == true
}
it("should dispose of added disposables upon error") {
let addedDisposable = AnyDisposable()
var observer: Signal<Int, TestError>.Observer!
let producer = SignalProducer<Int, TestError> { incomingObserver, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
observer = incomingObserver
}
producer.start()
expect(addedDisposable.isDisposed) == false
observer.send(error: .default)
expect(addedDisposable.isDisposed) == true
}
it("should dispose of the added disposable if the signal is unretained and unobserved upon exiting the scope") {
let addedDisposable = AnyDisposable()
let producer = SignalProducer<Int, TestError> { _, lifetime in
lifetime.observeEnded(addedDisposable.dispose)
}
var started = false
var disposed = false
producer
.on(started: { started = true }, disposed: { disposed = true })
.startWithSignal { _, _ in }
expect(started) == true
expect(disposed) == true
expect(addedDisposable.isDisposed) == true
}
it("should return whatever value is returned by the setup closure") {
let producer = SignalProducer<Never, NoError>.empty
expect(producer.startWithSignal { _, _ in "Hello" }) == "Hello"
}
it("should dispose of the upstream when the downstream producer terminates") {
var iterationCount = 0
let loop = SignalProducer<Int, NoError> { observer, lifetime in
for i in 0 ..< 100 where !lifetime.hasEnded {
observer.send(value: i)
iterationCount += 1
}
observer.sendCompleted()
}
var results: [Int] = []
waitUntil { done in
loop
.lift { $0.take(first: 5) }
.on(disposed: done)
.startWithValues { results.append($0) }
}
expect(iterationCount) == 5
expect(results) == [0, 1, 2, 3, 4]
}
}
describe("start") {
it("should immediately begin sending events") {
let producer = SignalProducer<Int, NoError>([1, 2])
var values: [Int] = []
var completed = false
producer.start { event in
switch event {
case let .value(value):
values.append(value)
case .completed:
completed = true
default:
break
}
}
expect(values) == [1, 2]
expect(completed) == true
}
it("should send interrupted if disposed") {
let producer = SignalProducer<(), NoError>.never
var interrupted = false
let disposable = producer.startWithInterrupted {
interrupted = true
}
expect(interrupted) == false
disposable.dispose()
expect(interrupted) == true
}
it("should release observer when disposed") {
weak var objectRetainedByObserver: NSObject?
var disposable: Disposable!
let test = {
let producer = SignalProducer<Int, NoError>.never
let object = NSObject()
objectRetainedByObserver = object
disposable = producer.startWithValues { _ in _ = object }
}
test()
expect(objectRetainedByObserver).toNot(beNil())
disposable.dispose()
expect(objectRetainedByObserver).to(beNil())
}
describe("trailing closure") {
it("receives next values") {
let (producer, observer) = SignalProducer<Int, NoError>.pipe()
var values = [Int]()
producer.startWithValues { value in
values.append(value)
}
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.sendCompleted()
expect(values) == [1, 2, 3]
}
it("receives results") {
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
var results: [Result<Int, TestError>] = []
producer.startWithResult { results.append($0) }
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(error: .default)
observer.sendCompleted()
expect(results).to(haveCount(4))
expect(results[0].value) == 1
expect(results[1].value) == 2
expect(results[2].value) == 3
expect(results[3].error) == .default
}
}
}
describe("lift") {
describe("over unary operators") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>([1, 2])
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> Signal<Int, NoError> in
counter += 1
return signal
}
let producer = baseProducer.lift(transform)
expect(counter) == 0
producer.start()
expect(counter) == 1
producer.start()
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>([1, 2, 3, 4])
let producer = baseProducer.lift { signal in
return signal.map { $0 * $0 }
}
let result = producer.collect().single()
expect(result?.value) == [1, 4, 9, 16]
}
}
describe("over binary operators") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>([1, 2])
let otherProducer = SignalProducer<Int, NoError>([3, 4])
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<(Int, Int), NoError> in
return { otherSignal in
counter += 1
return Signal.zip(signal, otherSignal)
}
}
let producer = baseProducer.lift(transform)(otherProducer)
expect(counter) == 0
producer.start()
expect(counter) == 1
producer.start()
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>([1, 2, 3])
let otherProducer = SignalProducer<Int, NoError>([4, 5, 6])
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<Int, NoError> in
return { otherSignal in
return Signal.zip(signal, otherSignal).map { $0.0 + $0.1 }
}
}
let producer = baseProducer.lift(transform)(otherProducer)
let result = producer.collect().single()
expect(result?.value) == [5, 7, 9]
}
}
describe("over binary operators with signal") {
it("should invoke transformation once per started signal") {
let baseProducer = SignalProducer<Int, NoError>([1, 2])
let (otherSignal, otherSignalObserver) = Signal<Int, NoError>.pipe()
var counter = 0
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<(Int, Int), NoError> in
return { otherSignal in
counter += 1
return Signal.zip(signal, otherSignal)
}
}
let producer = baseProducer.lift(transform)(SignalProducer(otherSignal))
expect(counter) == 0
producer.start()
otherSignalObserver.send(value: 1)
expect(counter) == 1
producer.start()
otherSignalObserver.send(value: 2)
expect(counter) == 2
}
it("should not miss any events") {
let baseProducer = SignalProducer<Int, NoError>([ 1, 2, 3 ])
let (otherSignal, otherSignalObserver) = Signal<Int, NoError>.pipe()
let transform = { (signal: Signal<Int, NoError>) -> (Signal<Int, NoError>) -> Signal<Int, NoError> in
return { otherSignal in
return Signal.zip(signal, otherSignal).map { $0.0 + $0.1 }
}
}
let producer = baseProducer.lift(transform)(SignalProducer(otherSignal))
var result: [Int] = []
var completed: Bool = false
producer.start { event in
switch event {
case .value(let value): result.append(value)
case .completed: completed = true
default: break
}
}
otherSignalObserver.send(value: 4)
expect(result) == [ 5 ]
otherSignalObserver.send(value: 5)
expect(result) == [ 5, 7 ]
otherSignalObserver.send(value: 6)
expect(result) == [ 5, 7, 9 ]
expect(completed) == true
}
}
}
describe("combineLatest") {
it("should combine the events to one array") {
let (producerA, observerA) = SignalProducer<Int, NoError>.pipe()
let (producerB, observerB) = SignalProducer<Int, NoError>.pipe()
let producer = SignalProducer.combineLatest([producerA, producerB])
var values = [[Int]]()
producer.startWithValues { value in
values.append(value)
}
observerA.send(value: 1)
observerB.send(value: 2)
observerA.send(value: 3)
observerA.sendCompleted()
observerB.sendCompleted()
expect(values._bridgeToObjectiveC()) == [[1, 2], [3, 2]]
}
it("should start signal producers in order as defined") {
var ids = [Int]()
let createProducer = { (id: Int) -> SignalProducer<Int, NoError> in
return SignalProducer { observer, _ in
ids.append(id)
observer.send(value: id)
observer.sendCompleted()
}
}
let producerA = createProducer(1)
let producerB = createProducer(2)
let producer = SignalProducer.combineLatest([producerA, producerB])
var values = [[Int]]()
producer.startWithValues { value in
values.append(value)
}
expect(ids) == [1, 2]
expect(values._bridgeToObjectiveC()) == [[1, 2]]._bridgeToObjectiveC()
}
}
describe("zip") {
it("should zip the events to one array") {
let producerA = SignalProducer<Int, NoError>([ 1, 2 ])
let producerB = SignalProducer<Int, NoError>([ 3, 4 ])
let producer = SignalProducer.zip([producerA, producerB])
let result = producer.collect().single()
expect(result?.value.map { $0._bridgeToObjectiveC() }) == [[1, 3], [2, 4]]._bridgeToObjectiveC()
}
it("should start signal producers in order as defined") {
var ids = [Int]()
let createProducer = { (id: Int) -> SignalProducer<Int, NoError> in
return SignalProducer { observer, _ in
ids.append(id)
observer.send(value: id)
observer.sendCompleted()
}
}
let producerA = createProducer(1)
let producerB = createProducer(2)
let producer = SignalProducer.zip([producerA, producerB])
var values = [[Int]]()
producer.startWithValues { value in
values.append(value)
}
expect(ids) == [1, 2]
expect(values._bridgeToObjectiveC()) == [[1, 2]]._bridgeToObjectiveC()
}
}
describe("timer") {
it("should send the current date at the given interval") {
let scheduler = TestScheduler()
let producer = SignalProducer.timer(interval: .seconds(1), on: scheduler, leeway: .seconds(0))
let startDate = scheduler.currentDate
let tick1 = startDate.addingTimeInterval(1)
let tick2 = startDate.addingTimeInterval(2)
let tick3 = startDate.addingTimeInterval(3)
var dates: [Date] = []
producer.startWithValues { dates.append($0) }
scheduler.advance(by: .milliseconds(900))
expect(dates) == []
scheduler.advance(by: .seconds(1))
expect(dates) == [tick1]
scheduler.advance()
expect(dates) == [tick1]
scheduler.advance(by: .milliseconds(200))
expect(dates) == [tick1, tick2]
scheduler.advance(by: .seconds(1))
expect(dates) == [tick1, tick2, tick3]
}
it("shouldn't overflow on a real scheduler") {
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer.timer(interval: .seconds(3), on: scheduler)
producer
.start()
.dispose()
}
it("should dispose of the signal when disposed") {
let scheduler = TestScheduler()
let producer = SignalProducer.timer(interval: .seconds(1), on: scheduler, leeway: .seconds(0))
var interrupted = false
var isDisposed = false
weak var weakSignal: Signal<Date, NoError>?
producer.startWithSignal { signal, disposable in
weakSignal = signal
scheduler.schedule {
disposable.dispose()
}
signal.on(disposed: { isDisposed = true }).observeInterrupted { interrupted = true }
}
expect(weakSignal).to(beNil())
expect(isDisposed) == false
expect(interrupted) == false
scheduler.run()
expect(weakSignal).to(beNil())
expect(isDisposed) == true
expect(interrupted) == true
}
}
describe("throttle while") {
var scheduler: ImmediateScheduler!
var shouldThrottle: MutableProperty<Bool>!
var observer: Signal<Int, NoError>.Observer!
var producer: SignalProducer<Int, NoError>!
beforeEach {
scheduler = ImmediateScheduler()
shouldThrottle = MutableProperty(false)
let (baseSignal, baseObserver) = Signal<Int, NoError>.pipe()
observer = baseObserver
producer = SignalProducer(baseSignal)
.throttle(while: shouldThrottle, on: scheduler)
expect(producer).notTo(beNil())
}
it("doesn't extend the lifetime of the throttle property") {
var completed = false
shouldThrottle.lifetime.observeEnded { completed = true }
observer.send(value: 1)
shouldThrottle = nil
expect(completed) == true
}
}
describe("on") {
it("should attach event handlers to each started signal") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
var starting = 0
var started = 0
var event = 0
var value = 0
var completed = 0
var terminated = 0
let producer = baseProducer
.on(starting: {
starting += 1
}, started: {
started += 1
}, event: { _ in
event += 1
}, completed: {
completed += 1
}, terminated: {
terminated += 1
}, value: { _ in
value += 1
})
producer.start()
expect(starting) == 1
expect(started) == 1
producer.start()
expect(starting) == 2
expect(started) == 2
observer.send(value: 1)
expect(event) == 2
expect(value) == 2
observer.sendCompleted()
expect(event) == 4
expect(completed) == 2
expect(terminated) == 2
}
it("should attach event handlers for disposal") {
let (baseProducer, observer) = SignalProducer<Int, TestError>.pipe()
withExtendedLifetime(observer) {
var disposed: Bool = false
let producer = baseProducer
.on(disposed: { disposed = true })
let disposable = producer.start()
expect(disposed) == false
disposable.dispose()
expect(disposed) == true
}
}
it("should invoke the `started` action of the inner producer first") {
let (baseProducer, _) = SignalProducer<Int, TestError>.pipe()
var numbers = [Int]()
_ = baseProducer
.on(started: { numbers.append(1) })
.on(started: { numbers.append(2) })
.on(started: { numbers.append(3) })
.start()
expect(numbers) == [1, 2, 3]
}
it("should invoke the `starting` action of the outer producer first") {
let (baseProducer, _) = SignalProducer<Int, TestError>.pipe()
var numbers = [Int]()
_ = baseProducer
.on(starting: { numbers.append(1) })
.on(starting: { numbers.append(2) })
.on(starting: { numbers.append(3) })
.start()
expect(numbers) == [3, 2, 1]
}
}
describe("startOn") {
it("should invoke effects on the given scheduler") {
let scheduler = TestScheduler()
var invoked = false
let producer = SignalProducer<Int, NoError> { _, _ in
invoked = true
}
producer.start(on: scheduler).start()
expect(invoked) == false
scheduler.advance()
expect(invoked) == true
}
it("should forward events on their original scheduler") {
let startScheduler = TestScheduler()
let testScheduler = TestScheduler()
let producer = SignalProducer.timer(interval: .seconds(2), on: testScheduler, leeway: .seconds(0))
var value: Date?
producer.start(on: startScheduler).startWithValues { value = $0 }
startScheduler.advance(by: .seconds(2))
expect(value).to(beNil())
testScheduler.advance(by: .seconds(1))
expect(value).to(beNil())
testScheduler.advance(by: .seconds(1))
expect(value) == testScheduler.currentDate
}
}
describe("flatMapError") {
it("should invoke the handler and start new producer for an error") {
let (baseProducer, baseObserver) = SignalProducer<Int, TestError>.pipe()
var values: [Int] = []
var completed = false
baseProducer
.flatMapError { (error: TestError) -> SignalProducer<Int, TestError> in
expect(error) == TestError.default
expect(values) == [1]
return .init(value: 2)
}
.start { event in
switch event {
case let .value(value):
values.append(value)
case .completed:
completed = true
default:
break
}
}
baseObserver.send(value: 1)
baseObserver.send(error: .default)
expect(values) == [1, 2]
expect(completed) == true
}
it("should interrupt the replaced producer on disposal") {
let (baseProducer, baseObserver) = SignalProducer<Int, TestError>.pipe()
var (disposed, interrupted) = (false, false)
let disposable = baseProducer
.flatMapError { (_: TestError) -> SignalProducer<Int, TestError> in
return SignalProducer<Int, TestError> { _, lifetime in
lifetime.observeEnded { disposed = true }
}
}
.startWithInterrupted { interrupted = true }
baseObserver.send(error: .default)
disposable.dispose()
expect(interrupted) == true
expect(disposed) == true
}
}
describe("flatten") {
describe("FlattenStrategy.concat") {
describe("sequencing") {
var completePrevious: (() -> Void)!
var sendSubsequent: (() -> Void)!
var completeOuter: (() -> Void)!
var subsequentStarted = false
beforeEach {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
let (previousProducer, previousObserver) = SignalProducer<Int, NoError>.pipe()
subsequentStarted = false
let subsequentProducer = SignalProducer<Int, NoError> { _, _ in
subsequentStarted = true
}
completePrevious = { previousObserver.sendCompleted() }
sendSubsequent = { outerObserver.send(value: subsequentProducer) }
completeOuter = { outerObserver.sendCompleted() }
outerProducer.flatten(.concat).start()
outerObserver.send(value: previousProducer)
}
it("should immediately start subsequent inner producer if previous inner producer has already completed") {
completePrevious()
sendSubsequent()
expect(subsequentStarted) == true
}
context("with queued producers") {
beforeEach {
// Place the subsequent producer into `concat`'s queue.
sendSubsequent()
expect(subsequentStarted) == false
}
it("should start subsequent inner producer upon completion of previous inner producer") {
completePrevious()
expect(subsequentStarted) == true
}
it("should start subsequent inner producer upon completion of previous inner producer and completion of outer producer") {
completeOuter()
completePrevious()
expect(subsequentStarted) == true
}
}
}
it("should forward an error from an inner producer") {
let errorProducer = SignalProducer<Int, TestError>(error: TestError.default)
let outerProducer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: errorProducer)
var error: TestError?
(outerProducer.flatten(.concat)).startWithFailed { e in
error = e
}
expect(error) == TestError.default
}
it("should forward an error from the outer producer") {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
var error: TestError?
outerProducer.flatten(.concat).startWithFailed { e in
error = e
}
outerObserver.send(error: TestError.default)
expect(error) == TestError.default
}
it("should not overflow the stack if inner producers complete immediately") {
typealias Inner = SignalProducer<(), NoError>
let depth = 10000
let inner: Inner = SignalProducer(value: ())
let (first, firstObserver) = SignalProducer<(), NoError>.pipe()
let (outer, outerObserver) = SignalProducer<Inner, NoError>.pipe()
var value = 0
outer
.flatten(.concat)
.startWithValues { _ in
value += 1
}
outerObserver.send(value: first)
for _ in 0..<depth { outerObserver.send(value: inner) }
firstObserver.sendCompleted()
expect(value) == depth
}
describe("completion") {
var completeOuter: (() -> Void)!
var completeInner: (() -> Void)!
var completed = false
beforeEach {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
let (innerProducer, innerObserver) = SignalProducer<Int, NoError>.pipe()
completeOuter = { outerObserver.sendCompleted() }
completeInner = { innerObserver.sendCompleted() }
completed = false
outerProducer.flatten(.concat).startWithCompleted {
completed = true
}
outerObserver.send(value: innerProducer)
}
it("should complete when inner producers complete, then outer producer completes") {
completeInner()
expect(completed) == false
completeOuter()
expect(completed) == true
}
it("should complete when outer producers completes, then inner producers complete") {
completeOuter()
expect(completed) == false
completeInner()
expect(completed) == true
}
}
}
describe("FlattenStrategy.merge") {
describe("behavior") {
var completeA: (() -> Void)!
var sendA: (() -> Void)!
var completeB: (() -> Void)!
var sendB: (() -> Void)!
var outerObserver: Signal<SignalProducer<Int, NoError>, NoError>.Observer!
var outerCompleted = false
var recv = [Int]()
beforeEach {
let (outerProducer, _outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
outerObserver = _outerObserver
let (producerA, observerA) = SignalProducer<Int, NoError>.pipe()
let (producerB, observerB) = SignalProducer<Int, NoError>.pipe()
completeA = { observerA.sendCompleted() }
completeB = { observerB.sendCompleted() }
var a = 0
sendA = { observerA.send(value: a); a += 1 }
var b = 100
sendB = { observerB.send(value: b); b += 1 }
outerProducer.flatten(.merge).start { event in
switch event {
case let .value(i):
recv.append(i)
case .completed:
outerCompleted = true
default:
break
}
}
outerObserver.send(value: producerA)
outerObserver.send(value: producerB)
outerObserver.sendCompleted()
}
afterEach {
(completeA, completeB) = (nil, nil)
(sendA, sendB) = (nil, nil)
outerObserver = nil
outerCompleted = false
recv = []
}
it("should forward values from any inner signals") {
sendA()
sendA()
sendB()
sendA()
sendB()
expect(recv) == [0, 1, 100, 2, 101]
}
it("should complete when all signals have completed") {
completeA()
expect(outerCompleted) == false
completeB()
expect(outerCompleted) == true
}
}
describe("error handling") {
it("should forward an error from an inner signal") {
let errorProducer = SignalProducer<Int, TestError>(error: TestError.default)
let outerProducer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: errorProducer)
var error: TestError?
outerProducer.flatten(.merge).startWithFailed { e in
error = e
}
expect(error) == TestError.default
}
it("should forward an error from the outer signal") {
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
var error: TestError?
outerProducer.flatten(.merge).startWithFailed { e in
error = e
}
outerObserver.send(error: TestError.default)
expect(error) == TestError.default
}
}
}
describe("FlattenStrategy.latest") {
it("should forward values from the latest inner signal") {
let (outer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
let (firstInner, firstInnerObserver) = SignalProducer<Int, TestError>.pipe()
let (secondInner, secondInnerObserver) = SignalProducer<Int, TestError>.pipe()
var receivedValues: [Int] = []
var errored = false
var completed = false
outer.flatten(.latest).start { event in
switch event {
case let .value(value):
receivedValues.append(value)
case .completed:
completed = true
case .failed:
errored = true
case .interrupted:
break
}
}
outerObserver.send(value: SignalProducer(value: 0))
outerObserver.send(value: firstInner)
firstInnerObserver.send(value: 1)
outerObserver.send(value: secondInner)
secondInnerObserver.send(value: 2)
outerObserver.sendCompleted()
expect(receivedValues) == [ 0, 1, 2 ]
expect(errored) == false
expect(completed) == false
firstInnerObserver.send(value: 3)
firstInnerObserver.sendCompleted()
secondInnerObserver.send(value: 4)
secondInnerObserver.sendCompleted()
expect(receivedValues) == [ 0, 1, 2, 4 ]
expect(errored) == false
expect(completed) == true
}
it("should forward an error from an inner signal") {
let inner = SignalProducer<Int, TestError>(error: .default)
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
let result = outer.flatten(.latest).first()
expect(result?.error) == TestError.default
}
it("should forward an error from the outer signal") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(error: .default)
let result = outer.flatten(.latest).first()
expect(result?.error) == TestError.default
}
it("should complete when the original and latest signals have completed") {
let inner = SignalProducer<Int, TestError>.empty
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
var completed = false
outer.flatten(.latest).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should complete when the outer signal completes before sending any signals") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>.empty
var completed = false
outer.flatten(.latest).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should not deadlock") {
let producer = SignalProducer<Int, NoError>(value: 1)
.flatMap(.latest) { _ in SignalProducer(value: 10) }
let result = producer.take(first: 1).last()
expect(result?.value) == 10
}
}
describe("FlattenStrategy.race") {
it("should forward values from the first inner producer to send an event") {
let (outer, outerObserver) = SignalProducer<SignalProducer<Int, TestError>, TestError>.pipe()
let (firstInner, firstInnerObserver) = SignalProducer<Int, TestError>.pipe()
let (secondInner, secondInnerObserver) = SignalProducer<Int, TestError>.pipe()
var receivedValues: [Int] = []
var errored = false
var completed = false
outer.flatten(.race).start { event in
switch event {
case let .value(value):
receivedValues.append(value)
case .completed:
completed = true
case .failed:
errored = true
case .interrupted:
break
}
}
outerObserver.send(value: firstInner)
outerObserver.send(value: secondInner)
firstInnerObserver.send(value: 1)
secondInnerObserver.send(value: 2)
outerObserver.sendCompleted()
expect(receivedValues) == [ 1 ]
expect(errored) == false
expect(completed) == false
secondInnerObserver.send(value: 3)
secondInnerObserver.sendCompleted()
expect(receivedValues) == [ 1 ]
expect(errored) == false
expect(completed) == false
firstInnerObserver.send(value: 4)
firstInnerObserver.sendCompleted()
expect(receivedValues) == [ 1, 4 ]
expect(errored) == false
expect(completed) == true
}
it("should forward an error from the first inner producer to send an error") {
let inner = SignalProducer<Int, TestError>(error: .default)
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
let result = outer.flatten(.race).first()
expect(result?.error) == TestError.default
}
it("should forward an error from the outer producer") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(error: .default)
let result = outer.flatten(.race).first()
expect(result?.error) == TestError.default
}
it("should complete when the 'outer producer' and 'first inner producer to send an event' have completed") {
let inner = SignalProducer<Int, TestError>.empty
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
var completed = false
outer.flatten(.race).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should complete when the outer producer completes before sending any inner producers") {
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>.empty
var completed = false
outer.flatten(.race).startWithCompleted {
completed = true
}
expect(completed) == true
}
it("should not complete when the outer producer completes after sending an inner producer but it doesn't send an event") {
let inner = SignalProducer<Int, TestError>.never
let outer = SignalProducer<SignalProducer<Int, TestError>, TestError>(value: inner)
var completed = false
outer.flatten(.race).startWithCompleted {
completed = true
}
expect(completed) == false
}
it("should not deadlock") {
let producer = SignalProducer<Int, NoError>(value: 1)
.flatMap(.race) { _ in SignalProducer(value: 10) }
let result = producer.take(first: 1).last()
expect(result?.value) == 10
}
}
describe("interruption") {
var innerObserver: Signal<(), NoError>.Observer!
var outerObserver: Signal<SignalProducer<(), NoError>, NoError>.Observer!
var execute: ((FlattenStrategy) -> Void)!
var interrupted = false
var completed = false
beforeEach {
let (innerProducer, incomingInnerObserver) = SignalProducer<(), NoError>.pipe()
let (outerProducer, incomingOuterObserver) = SignalProducer<SignalProducer<(), NoError>, NoError>.pipe()
innerObserver = incomingInnerObserver
outerObserver = incomingOuterObserver
execute = { strategy in
interrupted = false
completed = false
outerProducer
.flatten(strategy)
.start { event in
switch event {
case .interrupted:
interrupted = true
case .completed:
completed = true
default:
break
}
}
}
incomingOuterObserver.send(value: innerProducer)
}
describe("Concat") {
it("should drop interrupted from an inner producer") {
execute(.concat)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.concat)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
describe("Latest") {
it("should drop interrupted from an inner producer") {
execute(.latest)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.latest)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
describe("Merge") {
it("should drop interrupted from an inner producer") {
execute(.merge)
innerObserver.sendInterrupted()
expect(interrupted) == false
expect(completed) == false
outerObserver.sendCompleted()
expect(completed) == true
}
it("should forward interrupted from the outer producer") {
execute(.merge)
outerObserver.sendInterrupted()
expect(interrupted) == true
}
}
}
describe("disposal") {
var completeOuter: (() -> Void)!
var disposeOuter: (() -> Void)!
var execute: ((FlattenStrategy) -> Void)!
var innerDisposable = AnyDisposable()
var isInnerInterrupted = false
var isInnerDisposed = false
var interrupted = false
beforeEach {
execute = { strategy in
let (outerProducer, outerObserver) = SignalProducer<SignalProducer<Int, NoError>, NoError>.pipe()
innerDisposable = AnyDisposable()
isInnerInterrupted = false
isInnerDisposed = false
let innerProducer = SignalProducer<Int, NoError> { $1.observeEnded(innerDisposable.dispose) }
.on(interrupted: { isInnerInterrupted = true }, disposed: { isInnerDisposed = true })
interrupted = false
let outerDisposable = outerProducer.flatten(strategy).startWithInterrupted {
interrupted = true
}
completeOuter = outerObserver.sendCompleted
disposeOuter = outerDisposable.dispose
outerObserver.send(value: innerProducer)
}
}
describe("Concat") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.concat)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.concat)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
}
describe("Latest") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.latest)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.latest)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
}
describe("Merge") {
it("should cancel inner work when disposed before the outer producer completes") {
execute(.merge)
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
it("should cancel inner work when disposed after the outer producer completes") {
execute(.merge)
completeOuter()
expect(innerDisposable.isDisposed) == false
expect(interrupted) == false
expect(isInnerInterrupted) == false
expect(isInnerDisposed) == false
disposeOuter()
expect(innerDisposable.isDisposed) == true
expect(interrupted) == true
expect(isInnerInterrupted) == true
expect(isInnerDisposed) == true
}
}
}
}
describe("times") {
it("should start a signal N times upon completion") {
let original = SignalProducer<Int, NoError>([ 1, 2, 3 ])
let producer = original.repeat(3)
let result = producer.collect().single()
expect(result?.value) == [ 1, 2, 3, 1, 2, 3, 1, 2, 3 ]
}
it("should produce an equivalent signal producer if count is 1") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.repeat(1)
let result = producer.collect().single()
expect(result?.value) == [ 1 ]
}
it("should produce an empty signal if count is 0") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.repeat(0)
let result = producer.first()
expect(result).to(beNil())
}
it("should not repeat upon error") {
let results: [Result<Int, TestError>] = [
.success(1),
.success(2),
.failure(.default),
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.repeat(3)
let events = producer
.materialize()
.collect()
.single()
let result = events?.value
let expectedEvents: [Signal<Int, TestError>.Event] = [
.value(1),
.value(2),
.failed(.default),
]
// TODO: if let result = result where result.count == expectedEvents.count
if result?.count != expectedEvents.count {
fail("Invalid result: \(String(describing: result))")
} else {
// Can't test for equality because Array<T> is not Equatable,
// and neither is Signal<Value, Error>.Event.
expect(result![0] == expectedEvents[0]) == true
expect(result![1] == expectedEvents[1]) == true
expect(result![2] == expectedEvents[2]) == true
}
}
it("should evaluate lazily") {
let original = SignalProducer<Int, NoError>(value: 1)
let producer = original.repeat(Int.max)
let result = producer.take(first: 1).single()
expect(result?.value) == 1
}
}
describe("retry") {
it("should start a signal N times upon error") {
let results: [Result<Int, TestError>] = [
.failure(.error1),
.failure(.error2),
.success(1),
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.value) == 1
}
it("should forward errors that occur after all retries") {
let results: [Result<Int, TestError>] = [
.failure(.default),
.failure(.error1),
.failure(.error2),
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.error) == TestError.error2
}
it("should not retry upon completion") {
let results: [Result<Int, TestError>] = [
.success(1),
.success(2),
.success(3),
]
let original = SignalProducer.attemptWithResults(results)
let producer = original.retry(upTo: 2)
let result = producer.single()
expect(result?.value) == 1
}
context("with interval") {
it("should send values at the given interval") {
let scheduler = TestScheduler()
var count = 0
let original = SignalProducer<Int, TestError> { observer, _ in
if count < 2 {
scheduler.schedule { observer.send(value: count) }
scheduler.schedule { observer.send(error: .default) }
} else {
scheduler.schedule { observer.sendCompleted() }
}
count += 1
}
var values: [Int] = []
var completed = false
original.retry(upTo: Int.max, interval: 1, on: scheduler)
.start { event in
switch event {
case let .value(value):
values.append(value)
case .completed:
completed = true
default:
break
}
}
expect(count) == 1
expect(values) == []
scheduler.advance()
expect(count) == 1
expect(values) == [1]
expect(completed) == false
scheduler.advance(by: .seconds(1))
expect(count) == 2
expect(values) == [1, 2]
expect(completed) == false
scheduler.advance(by: .seconds(1))
expect(count) == 3
expect(values) == [1, 2]
expect(completed) == true
}
it("should not send values after hitting the limitation") {
let scheduler = TestScheduler()
var count = 0
var values: [Int] = []
var errors: [TestError] = []
let original = SignalProducer<Int, TestError> { observer, _ in
scheduler.schedule { observer.send(value: count) }
scheduler.schedule { observer.send(error: .default) }
count += 1
}
original.retry(upTo: 2, interval: 1, on: scheduler)
.start { event in
switch event {
case let .value(value):
values.append(value)
case let .failed(error):
errors.append(error)
default:
break
}
}
scheduler.advance()
expect(count) == 1
expect(values) == [1]
expect(errors) == []
scheduler.advance(by: .seconds(1))
expect(count) == 2
expect(values) == [1, 2]
expect(errors) == []
scheduler.advance(by: .seconds(1))
expect(count) == 3
expect(values) == [1, 2, 3]
expect(errors) == [.default]
scheduler.advance(by: .seconds(1))
expect(count) == 3
expect(values) == [1, 2, 3]
expect(errors) == [.default]
}
}
}
describe("then") {
it("should start the subsequent producer after the completion of the original") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
var subsequentStarted = false
let subsequent = SignalProducer<Int, NoError> { _, _ in
subsequentStarted = true
}
let producer = original.then(subsequent)
producer.start()
expect(subsequentStarted) == false
observer.sendCompleted()
expect(subsequentStarted) == true
}
it("should forward errors from the original producer") {
let original = SignalProducer<Int, TestError>(error: .default)
let subsequent = SignalProducer<Int, TestError>.empty
let result = original.then(subsequent).first()
expect(result?.error) == TestError.default
}
it("should forward errors from the subsequent producer") {
let original = SignalProducer<Int, TestError>.empty
let subsequent = SignalProducer<Int, TestError>(error: .default)
let result = original.then(subsequent).first()
expect(result?.error) == TestError.default
}
it("should forward interruptions from the original producer") {
let (original, observer) = SignalProducer<Int, NoError>.pipe()
var subsequentStarted = false
let subsequent = SignalProducer<Int, NoError> { _, _ in
subsequentStarted = true
}
var interrupted = false
let producer = original.then(subsequent)
producer.startWithInterrupted {
interrupted = true
}
expect(subsequentStarted) == false
observer.sendInterrupted()
expect(interrupted) == true
}
it("should complete when both inputs have completed") {
let (original, originalObserver) = SignalProducer<Int, NoError>.pipe()
let (subsequent, subsequentObserver) = SignalProducer<String, NoError>.pipe()
let producer = original.then(subsequent)
var completed = false
producer.startWithCompleted {
completed = true
}
originalObserver.sendCompleted()
expect(completed) == false
subsequentObserver.sendCompleted()
expect(completed) == true
}
it("works with NoError and TestError") {
let producer: SignalProducer<Int, TestError> = SignalProducer<Int, NoError>.empty
.then(SignalProducer<Int, TestError>.empty)
_ = producer
}
it("works with TestError and NoError") {
let producer: SignalProducer<Int, TestError> = SignalProducer<Int, TestError>.empty
.then(SignalProducer<Int, NoError>.empty)
_ = producer
}
it("works with NoError and NoError") {
let producer: SignalProducer<Int, NoError> = SignalProducer<Int, NoError>.empty
.then(SignalProducer<Int, NoError>.empty)
_ = producer
}
it("should not be ambiguous") {
let a = SignalProducer<Int, NoError>.empty.then(SignalProducer<Int, NoError>.empty)
expect(type(of: a)) == SignalProducer<Int, NoError>.self
let b = SignalProducer<Int, NoError>.empty.then(SignalProducer<Double, NoError>.empty)
expect(type(of: b)) == SignalProducer<Double, NoError>.self
let c = SignalProducer<Int, NoError>.empty.then(SignalProducer<Int, TestError>.empty)
expect(type(of: c)) == SignalProducer<Int, TestError>.self
let d = SignalProducer<Int, NoError>.empty.then(SignalProducer<Double, TestError>.empty)
expect(type(of: d)) == SignalProducer<Double, TestError>.self
let e = SignalProducer<Int, TestError>.empty.then(SignalProducer<Int, TestError>.empty)
expect(type(of: e)) == SignalProducer<Int, TestError>.self
let f = SignalProducer<Int, TestError>.empty.then(SignalProducer<Int, NoError>.empty)
expect(type(of: f)) == SignalProducer<Int, TestError>.self
let g = SignalProducer<Int, TestError>.empty.then(SignalProducer<Double, TestError>.empty)
expect(type(of: g)) == SignalProducer<Double, TestError>.self
let h = SignalProducer<Int, TestError>.empty.then(SignalProducer<Double, NoError>.empty)
expect(type(of: h)) == SignalProducer<Double, TestError>.self
}
}
describe("first") {
it("should start a signal then block on the first value") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let forwardingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
forwardingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
forwardingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(_signal.delay(0.1, on: forwardingScheduler))
let observingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
observingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
observingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
var result: Int?
observingScheduler.schedule {
result = producer.first()?.value
}
expect(result).to(beNil())
observer.send(value: 1)
expect(result).toEventually(equal(1), timeout: 5.0)
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.first()
expect(result).to(beNil())
}
it("should return the first value if more than one value is sent") {
let result = SignalProducer<Int, NoError>([ 1, 2 ]).first()
expect(result?.value) == 1
}
it("should return an error if one occurs before the first value") {
let result = SignalProducer<Int, TestError>(error: .default).first()
expect(result?.error) == TestError.default
}
}
describe("single") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let forwardingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
forwardingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
forwardingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(_signal.delay(0.1, on: forwardingScheduler))
let observingScheduler: QueueScheduler
if #available(OSX 10.10, *) {
observingScheduler = QueueScheduler(qos: .default, name: "\(#file):\(#line)")
} else {
observingScheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
var result: Int?
observingScheduler.schedule {
result = producer.single()?.value
}
expect(result).to(beNil())
observer.send(value: 1)
Thread.sleep(forTimeInterval: 3.0)
expect(result).to(beNil())
observer.sendCompleted()
expect(result).toEventually(equal(1))
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.single()
expect(result).to(beNil())
}
it("should return a nil result if more than one value is sent before completion") {
let result = SignalProducer<Int, NoError>([ 1, 2 ]).single()
expect(result).to(beNil())
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).single()
expect(result?.error) == TestError.default
}
}
describe("last") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let scheduler: QueueScheduler
if #available(*, OSX 10.10) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(_signal.delay(0.1, on: scheduler))
var result: Result<Int, NoError>?
let group = DispatchGroup()
let globalQueue: DispatchQueue
if #available(*, OSX 10.10) {
globalQueue = DispatchQueue.global()
} else {
globalQueue = DispatchQueue.global(priority: .default)
}
globalQueue.async(group: group, flags: []) {
result = producer.last()
}
expect(result).to(beNil())
observer.send(value: 1)
observer.send(value: 2)
expect(result).to(beNil())
observer.sendCompleted()
group.wait()
expect(result?.value) == 2
}
it("should return a nil result if no values are sent before completion") {
let result = SignalProducer<Int, NoError>.empty.last()
expect(result).to(beNil())
}
it("should return the last value if more than one value is sent") {
let result = SignalProducer<Int, NoError>([ 1, 2 ]).last()
expect(result?.value) == 2
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).last()
expect(result?.error) == TestError.default
}
}
describe("wait") {
it("should start a signal then block until completion") {
let (_signal, observer) = Signal<Int, NoError>.pipe()
let scheduler: QueueScheduler
if #available(*, OSX 10.10) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
let producer = SignalProducer(_signal.delay(0.1, on: scheduler))
var result: Result<(), NoError>?
let group = DispatchGroup()
let globalQueue: DispatchQueue
if #available(*, OSX 10.10) {
globalQueue = DispatchQueue.global()
} else {
globalQueue = DispatchQueue.global(priority: .default)
}
globalQueue.async(group: group, flags: []) {
result = producer.wait()
}
expect(result).to(beNil())
observer.sendCompleted()
group.wait()
expect(result?.value).toNot(beNil())
}
it("should return an error if one occurs") {
let result = SignalProducer<Int, TestError>(error: .default).wait()
expect(result.error) == TestError.default
}
}
describe("observeOn") {
it("should immediately cancel upstream producer's work when disposed") {
var upstreamLifetime: Lifetime!
let producer = SignalProducer<(), NoError>{ _, innerLifetime in
upstreamLifetime = innerLifetime
}
var downstreamDisposable: Disposable!
producer
.observe(on: TestScheduler())
.startWithSignal { signal, innerDisposable in
signal.observe { _ in }
downstreamDisposable = innerDisposable
}
expect(upstreamLifetime.hasEnded) == false
downstreamDisposable.dispose()
expect(upstreamLifetime.hasEnded) == true
}
}
describe("take") {
it("Should not start concat'ed producer if the first one sends a value when using take(1)") {
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(name: "\(#file):\(#line)")
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "\(#file):\(#line)"))
}
// Delaying producer1 from sending a value to test whether producer2 is started in the mean-time.
let producer1 = SignalProducer<Int, NoError> { handler, _ in
handler.send(value: 1)
handler.sendCompleted()
}.start(on: scheduler)
var started = false
let producer2 = SignalProducer<Int, NoError> { handler, _ in
started = true
handler.send(value: 2)
handler.sendCompleted()
}
let result = producer1.concat(producer2).take(first: 1).collect().first()
expect(result?.value) == [1]
expect(started) == false
}
}
describe("replayLazily") {
var producer: SignalProducer<Int, TestError>!
var observer: SignalProducer<Int, TestError>.ProducedSignal.Observer!
var replayedProducer: SignalProducer<Int, TestError>!
beforeEach {
let (producerTemp, observerTemp) = SignalProducer<Int, TestError>.pipe()
producer = producerTemp
observer = observerTemp
replayedProducer = producer.replayLazily(upTo: 2)
}
context("subscribing to underlying producer") {
it("emits new values") {
var last: Int?
replayedProducer
.assumeNoErrors()
.startWithValues { last = $0 }
expect(last).to(beNil())
observer.send(value: 1)
expect(last) == 1
observer.send(value: 2)
expect(last) == 2
}
it("emits errors") {
var error: TestError?
replayedProducer.startWithFailed { error = $0 }
expect(error).to(beNil())
observer.send(error: .default)
expect(error) == TestError.default
}
}
context("buffers past values") {
it("emits last value upon subscription") {
let disposable = replayedProducer
.start()
observer.send(value: 1)
disposable.dispose()
var last: Int?
replayedProducer
.assumeNoErrors()
.startWithValues { last = $0 }
expect(last) == 1
}
it("emits previous failure upon subscription") {
let disposable = replayedProducer
.start()
observer.send(error: .default)
disposable.dispose()
var error: TestError?
replayedProducer
.startWithFailed { error = $0 }
expect(error) == TestError.default
}
it("emits last n values upon subscription") {
var disposable = replayedProducer
.start()
observer.send(value: 1)
observer.send(value: 2)
observer.send(value: 3)
observer.send(value: 4)
disposable.dispose()
var values: [Int] = []
disposable = replayedProducer
.assumeNoErrors()
.startWithValues { values.append($0) }
expect(values) == [ 3, 4 ]
observer.send(value: 5)
expect(values) == [ 3, 4, 5 ]
disposable.dispose()
values = []
replayedProducer
.assumeNoErrors()
.startWithValues { values.append($0) }
expect(values) == [ 4, 5 ]
}
}
context("starting underying producer") {
it("starts lazily") {
var started = false
let producer = SignalProducer<Int, NoError>(value: 0)
.on(started: { started = true })
expect(started) == false
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(started) == false
replayedProducer.start()
expect(started) == true
}
it("shares a single subscription") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>.never
.on(started: { startedTimes += 1 })
expect(startedTimes) == 0
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start()
expect(startedTimes) == 1
replayedProducer.start()
expect(startedTimes) == 1
}
it("does not start multiple times when subscribing multiple times") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>(value: 0)
.on(started: { startedTimes += 1 })
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start().dispose()
expect(startedTimes) == 1
replayedProducer.start().dispose()
expect(startedTimes) == 1
}
it("does not start again if it finished") {
var startedTimes = 0
let producer = SignalProducer<Int, NoError>.empty
.on(started: { startedTimes += 1 })
expect(startedTimes) == 0
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(startedTimes) == 0
replayedProducer.start()
expect(startedTimes) == 1
replayedProducer.start()
expect(startedTimes) == 1
}
}
context("lifetime") {
it("does not dispose underlying subscription if the replayed producer is still in memory") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
let replayedProducer = producer
.replayLazily(upTo: 1)
expect(disposed) == false
let disposable = replayedProducer.start()
expect(disposed) == false
disposable.dispose()
expect(disposed) == false
}
it("does not dispose if it has active subscriptions") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
var replayedProducer = ImplicitlyUnwrappedOptional(producer.replayLazily(upTo: 1))
expect(disposed) == false
let disposable1 = replayedProducer?.start()
let disposable2 = replayedProducer?.start()
expect(disposed) == false
replayedProducer = nil
expect(disposed) == false
disposable1?.dispose()
expect(disposed) == false
disposable2?.dispose()
expect(disposed) == true
}
it("disposes underlying producer when the producer is deallocated") {
var disposed = false
let producer = SignalProducer<Int, NoError>.never
.on(disposed: { disposed = true })
var replayedProducer = ImplicitlyUnwrappedOptional(producer.replayLazily(upTo: 1))
expect(disposed) == false
let disposable = replayedProducer?.start()
expect(disposed) == false
disposable?.dispose()
expect(disposed) == false
replayedProducer = nil
expect(disposed) == true
}
it("does not leak buffered values") {
final class Value {
private let deinitBlock: () -> Void
init(deinitBlock: @escaping () -> Void) {
self.deinitBlock = deinitBlock
}
deinit {
self.deinitBlock()
}
}
var deinitValues = 0
var producer: SignalProducer<Value, NoError>! = SignalProducer(value: Value {
deinitValues += 1
})
expect(deinitValues) == 0
var replayedProducer: SignalProducer<Value, NoError>! = producer
.replayLazily(upTo: 1)
let disposable = replayedProducer
.start()
disposable.dispose()
expect(deinitValues) == 0
producer = nil
expect(deinitValues) == 0
replayedProducer = nil
expect(deinitValues) == 1
}
}
describe("log events") {
it("should output the correct event") {
let expectations: [(String) -> Void] = [
{ event in expect(event) == "[] starting" },
{ event in expect(event) == "[] started" },
{ event in expect(event) == "[] value 1" },
{ event in expect(event) == "[] completed" },
{ event in expect(event) == "[] terminated" },
{ event in expect(event) == "[] disposed" },
]
let logger = TestLogger(expectations: expectations)
let (producer, observer) = SignalProducer<Int, TestError>.pipe()
producer
.logEvents(logger: logger.logEvent)
.start()
observer.send(value: 1)
observer.sendCompleted()
}
}
describe("init(values) ambiguity") {
it("should not be a SignalProducer<SignalProducer<Int, NoError>, NoError>") {
let producer1: SignalProducer<Int, NoError> = SignalProducer.empty
let producer2: SignalProducer<Int, NoError> = SignalProducer.empty
// This expression verifies at compile time that the type is as expected.
let _: SignalProducer<Int, NoError> = SignalProducer([producer1, producer2])
.flatten(.merge)
}
}
}
describe("take(during:)") {
it("completes a signal when the lifetime ends") {
let (signal, observer) = Signal<Int, NoError>.pipe()
let object = MutableReference(TestObject())
let output = signal.take(during: object.value!.lifetime)
var results: [Int] = []
output.observeValues { results.append($0) }
observer.send(value: 1)
observer.send(value: 2)
object.value = nil
observer.send(value: 3)
expect(results) == [1, 2]
}
it("completes a signal producer when the lifetime ends") {
let (producer, observer) = Signal<Int, NoError>.pipe()
let object = MutableReference(TestObject())
let output = producer.take(during: object.value!.lifetime)
var results: [Int] = []
output.observeValues { results.append($0) }
observer.send(value: 1)
observer.send(value: 2)
object.value = nil
observer.send(value: 3)
expect(results) == [1, 2]
}
}
describe("negated attribute") {
it("should return the negate of a value in a Boolean producer") {
let producer = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
producer.negate().startWithValues { value in
expect(value).to(beFalse())
}
}
}
describe("and attribute") {
it("should emit true when both producers emits the same value") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
let producer2 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
producer1.and(producer2).startWithValues { value in
expect(value).to(beTrue())
}
}
it("should emit false when both producers emits opposite values") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
let producer2 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: false)
observer.sendCompleted()
}
producer1.and(producer2).startWithValues { value in
expect(value).to(beFalse())
}
}
it("should work the same way when using signal instead of a producer") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
let (signal2, observer2) = Signal<Bool, NoError>.pipe()
producer1.and(signal2).startWithValues { value in
expect(value).to(beTrue())
}
observer2.send(value: true)
observer2.sendCompleted()
}
}
describe("or attribute") {
it("should emit true when at least one of the producers emits true") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
let producer2 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: false)
observer.sendCompleted()
}
producer1.or(producer2).startWithValues { value in
expect(value).to(beTrue())
}
}
it("should emit false when both producers emits false") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: false)
observer.sendCompleted()
}
let producer2 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: false)
observer.sendCompleted()
}
producer1.or(producer2).startWithValues { value in
expect(value).to(beFalse())
}
}
it("should work the same way when using signal instead of a producer") {
let producer1 = SignalProducer<Bool, NoError> { observer, _ in
observer.send(value: true)
observer.sendCompleted()
}
let (signal2, observer2) = Signal<Bool, NoError>.pipe()
producer1.or(signal2).startWithValues { value in
expect(value).to(beTrue())
}
observer2.send(value: true)
observer2.sendCompleted()
}
}
describe("promoteError") {
it("should infer the error type from the context") {
let combined: Any = SignalProducer
.combineLatest(SignalProducer<Int, NoError>.never.promoteError(),
SignalProducer<Double, TestError>.never,
SignalProducer<Float, NoError>.never.promoteError(),
SignalProducer<UInt, POSIXError>.never.flatMapError { _ in .empty })
expect(combined is SignalProducer<(Int, Double, Float, UInt), TestError>) == true
}
}
}
}
// MARK: - Helpers
private func == <T>(left: Expectation<T.Type>, right: Any.Type) {
left.to(Predicate.fromDeprecatedClosure { expression, _ in
return try expression.evaluate()! == right
}.requireNonNil)
}
extension SignalProducer {
internal static func pipe() -> (SignalProducer, ProducedSignal.Observer) {
let (signal, observer) = ProducedSignal.pipe()
let producer = SignalProducer(signal)
return (producer, observer)
}
/// Creates a producer that can be started as many times as elements in `results`.
/// Each signal will immediately send either a value or an error.
fileprivate static func attemptWithResults<C: Collection>(_ results: C) -> SignalProducer<Value, Error> where C.Iterator.Element == Result<Value, Error>, C.IndexDistance == C.Index, C.Index == Int {
let resultCount = results.count
var operationIndex = 0
precondition(resultCount > 0)
let operation: () -> Result<Value, Error> = {
if operationIndex < resultCount {
defer {
operationIndex += 1
}
return results[results.index(results.startIndex, offsetBy: operationIndex)]
} else {
fail("Operation started too many times")
return results[results.startIndex]
}
}
return SignalProducer(operation)
}
}
| mit | e21d0f6b3095bd332c3a01323938e20f | 26.744681 | 199 | 0.646874 | 3.972918 | false | true | false | false |
iAmrSalman/Dots | Sources/DataLoadOperationAsync.swift | 1 | 2209 | //
// DataLoadOperation.swift
// Dots
//
// Created by Amr Salman on 4/4/17.
//
//
import Foundation
internal class DataLoadOperationAsync: ConcurrentOperation, DataLoadProtocol {
internal var url: URL?
internal var complitionHandler: ComplitionHandler?
internal var method: HTTPMethod
internal var parameters: Parameters?
internal var encoding: ParameterEncoding
internal var headers: HTTPHeaders?
init(
_ url: URL?,
method: HTTPMethod = .get,
parameters: Parameters? = nil,
encoding: ParameterEncoding = .url,
headers: HTTPHeaders? = nil,
qualityOfService: QualityOfService = .default,
complitionHandler: ComplitionHandler? = nil ) {
self.url = url
self.method = method
self.parameters = parameters
self.encoding = encoding
self.headers = headers
self.complitionHandler = complitionHandler
super.init()
self.qualityOfService = qualityOfService
}
override func main() {
guard let url = url else { self.state = .finished; return }
guard let session = createSession(configuration: .defualt) else { self.state = .finished; return }
var originalRequest = URLRequest(url: url)
originalRequest.httpMethod = method.rawValue
originalRequest.allHTTPHeaderFields = headers
do {
let encodedURLRequest: URLRequest
switch encoding {
case .url:
encodedURLRequest = try urlEncode(&originalRequest, with: parameters)
case .json:
encodedURLRequest = try jsonEncode(&originalRequest, with: parameters)
}
session.dataTask(with: encodedURLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async {
guard let complitionHandler = self.complitionHandler else { self.state = .finished; return }
complitionHandler(Dot(data: data, response: response, error: error))
self.state = .finished
}
}).resume()
} catch {
guard let complitionHandler = self.complitionHandler else { self.state = .finished; return }
complitionHandler(Dot(data: nil, response: nil, error: error))
self.state = .finished
}
}
}
| mit | 8a05f701741181c711b4d27647b01fdd | 30.112676 | 124 | 0.67904 | 4.781385 | false | false | false | false |
avaidyam/Parrot | MochaUI/Changeset.swift | 1 | 12453 | //
// Changeset.swift
// Copyright (c) 2015-16 Joachim Bondo. All rights reserved.
//
import AppKit
/** Defines an atomic edit.
- seealso: Note on `Edit.Operation`.
*/
public struct Edit<T: Equatable> {
/** Defines the type of an `Edit`.
*/
public enum Operation {
case insertion
case deletion
case substitution
case move(origin: Int)
}
public let operation: Operation
public let value: T
public let destination: Int
// Define initializer so that we don't have to add the `operation` label.
public init(_ operation: Operation, value: T, destination: Int) {
self.operation = operation
self.value = value
self.destination = destination
}
}
/** A `Changeset` is a way to describe the edits required to go from one set of data to another.
It detects additions, deletions, substitutions, and moves. Data is a `Collection` of `Equatable` elements.
- note: This implementation was inspired by [Dave DeLong](https://twitter.com/davedelong)'s article, [Edit distance and edit steps](http://davedelong.tumblr.com/post/134367865668/edit-distance-and-edit-steps).
- seealso: `Changeset.editDistance`.
*/
public struct Changeset<T: Collection> where T.Iterator.Element: Equatable {
/// The starting-point collection.
public let origin: T
/// The ending-point collection.
public let destination: T
/** The edit steps required to go from `self.origin` to `self.destination`.
- note: I would have liked to make this `lazy`, but that would prohibit users from using constant `Changeset` values.
- seealso: [Lazy Properties in Structs](http://oleb.net/blog/2015/12/lazy-properties-in-structs-swift/) by [Ole Begemann](https://twitter.com/olebegemann).
*/
public let edits: [Edit<T.Iterator.Element>]
public init(source origin: T, target destination: T) {
self.origin = origin
self.destination = destination
self.edits = Changeset.edits(from: self.origin, to: self.destination)
}
/** Returns the edit steps required to go from one collection to another.
The number of steps is the `count` of elements.
- note: Indexes in the returned `Edit` elements are into the `from` source collection (just like how `UITableView` expects changes in the `beginUpdates`/`endUpdates` block.)
- seealso:
- [Edit distance and edit steps](http://davedelong.tumblr.com/post/134367865668/edit-distance-and-edit-steps) by [Dave DeLong](https://twitter.com/davedelong).
- [Explanation of and Pseudo-code for the Wagner-Fischer algorithm](https://en.wikipedia.org/wiki/Wagner–Fischer_algorithm).
- parameters:
- from: The starting-point collection.
- to: The ending-point collection.
- returns: An array of `Edit` elements.
*/
public static func edits(from source: T, to target: T) -> [Edit<T.Iterator.Element>] {
let rows = source.count
let columns = target.count
// Only the previous and current row of the matrix are required.
var previousRow: [[Edit<T.Iterator.Element>]] = Array(repeating: [], count: columns + 1)
var currentRow = [[Edit<T.Iterator.Element>]]()
// Indexes into the two collections.
var sourceIndex = source.startIndex
var targetIndex: T.Index
// Fill first row of insertions.
var edits = [Edit<T.Iterator.Element>]()
for (column, element) in target.enumerated() {
let edit = Edit(.insertion, value: element, destination: column)
edits.append(edit)
previousRow[column + 1] = edits
}
if rows > 0 {
for row in 1...rows {
targetIndex = target.startIndex
currentRow = Array(repeating: [], count: columns + 1)
// Fill first cell with deletion.
var edits = previousRow[0]
let edit = Edit(.deletion, value: source[sourceIndex], destination: row - 1)
edits.append(edit)
currentRow[0] = edits
if columns > 0 {
for column in 1...columns {
if source[sourceIndex] == target[targetIndex] {
currentRow[column] = previousRow[column - 1] // no operation
} else {
var deletion = previousRow[column] // a deletion
var insertion = currentRow[column - 1] // an insertion
var substitution = previousRow[column - 1] // a substitution
// Record operation.
let minimumCount = min(deletion.count, insertion.count, substitution.count)
if deletion.count == minimumCount {
let edit = Edit(.deletion, value: source[sourceIndex], destination: row - 1)
deletion.append(edit)
currentRow[column] = deletion
} else if insertion.count == minimumCount {
let edit = Edit(.insertion, value: target[targetIndex], destination: column - 1)
insertion.append(edit)
currentRow[column] = insertion
} else {
let edit = Edit(.substitution, value: target[targetIndex], destination: row - 1)
substitution.append(edit)
currentRow[column] = substitution
}
}
targetIndex = target.index(targetIndex, offsetBy: 1)
}
}
previousRow = currentRow
sourceIndex = source.index(sourceIndex, offsetBy: 1)
}
}
// Convert deletion/insertion pairs of same element into moves.
return reducedEdits(previousRow[columns])
}
}
/** Returns an array where deletion/insertion pairs of the same element are replaced by `.move` edits.
- parameter edits: An array of `Edit` elements to be reduced.
- returns: An array of `Edit` elements.
*/
private func reducedEdits<T>(_ edits: [Edit<T>]) -> [Edit<T>] {
return edits.reduce([Edit<T>]()) { (edits, edit) in
var reducedEdits = edits
if let (move, index) = move(from: edit, in: reducedEdits), case .move = move.operation {
reducedEdits.remove(at: index)
reducedEdits.append(move)
} else {
reducedEdits.append(edit)
}
return reducedEdits
}
}
/** Returns a potential `.move` edit based on an array of `Edit` elements and an edit to match up against.
If `edit` is a deletion or an insertion, and there is a matching opposite insertion/deletion with the same value in the array, a corresponding `.move` edit is returned.
- parameters:
- deletionOrInsertion: A `.deletion` or `.insertion` edit there will be searched an opposite match for.
- edits: The array of `Edit` elements to search for a match in.
- returns: An optional tuple consisting of the `.move` `Edit` that corresponds to the given deletion or insertion and an opposite match in `edits`, and the index of the match – if one was found.
*/
private func move<T>(from deletionOrInsertion: Edit<T>, `in` edits: [Edit<T>]) -> (move: Edit<T>, index: Int)? {
switch deletionOrInsertion.operation {
case .deletion:
if let insertionIndex = edits.index(where: { (earlierEdit) -> Bool in
if case .insertion = earlierEdit.operation, earlierEdit.value == deletionOrInsertion.value { return true } else { return false }
}) {
return (Edit(.move(origin: deletionOrInsertion.destination), value: deletionOrInsertion.value, destination: edits[insertionIndex].destination), insertionIndex)
}
case .insertion:
if let deletionIndex = edits.index(where: { (earlierEdit) -> Bool in
if case .deletion = earlierEdit.operation, earlierEdit.value == deletionOrInsertion.value { return true } else { return false }
}) {
return (Edit(.move(origin: edits[deletionIndex].destination), value: deletionOrInsertion.value, destination: deletionOrInsertion.destination), deletionIndex)
}
default:
break
}
return nil
}
extension Edit: Equatable {}
public func ==<T>(lhs: Edit<T>, rhs: Edit<T>) -> Bool {
guard lhs.destination == rhs.destination && lhs.value == rhs.value else { return false }
switch (lhs.operation, rhs.operation) {
case (.insertion, .insertion), (.deletion, .deletion), (.substitution, .substitution):
return true
case (.move(let lhsOrigin), .move(let rhsOrigin)):
return lhsOrigin == rhsOrigin
default:
return false
}
}
extension NSTableView {
/// Performs batch updates on the table view, given the edits of a Changeset, and animates the transition.
open func update<T>(with edits: [Edit<T>],
insertAnimation: AnimationOptions = [.effectFade, .slideUp],
deleteAnimation: AnimationOptions = [.effectFade, .slideDown]) {
guard !edits.isEmpty else { return }
let indexPaths = batchIndices(from: edits)
self.beginUpdates()
if !indexPaths.deletions.isEmpty { self.removeRows(at: IndexSet(indexPaths.deletions), withAnimation: insertAnimation) }
if !indexPaths.insertions.isEmpty { self.insertRows(at: IndexSet(indexPaths.insertions), withAnimation: deleteAnimation) }
if !indexPaths.updates.isEmpty { self.reloadData(forRowIndexes: IndexSet(indexPaths.updates), columnIndexes: IndexSet()) }
self.endUpdates()
}
}
extension NSCollectionView {
/// Performs batch updates on the table view, given the edits of a Changeset, and animates the transition.
open func update<T>(with edits: [Edit<T>], in section: Int = 0, completion: ((Bool) -> Void)? = nil) {
guard !edits.isEmpty else { return }
let indexPaths = batchIndexPaths(from: edits, in: section)
self.animator().performBatchUpdates({
if !indexPaths.deletions.isEmpty { self.deleteItems(at: Set(indexPaths.deletions)) }
if !indexPaths.insertions.isEmpty { self.insertItems(at: Set(indexPaths.insertions)) }
if !indexPaths.updates.isEmpty { self.reloadItems(at: Set(indexPaths.updates)) }
}, completionHandler: completion)
}
}
private func batchIndices<T> (from edits: [Edit<T>]) -> (insertions: [Int], deletions: [Int], updates: [Int]) {
var insertions = [Int](), deletions = [Int](), updates = [Int]()
for edit in edits {
switch edit.operation {
case .deletion:
deletions.append(edit.destination)
case .insertion:
insertions.append(edit.destination)
case .move(let origin):
deletions.append(origin)
insertions.append(edit.destination)
case .substitution:
updates.append(edit.destination)
}
}
return (insertions: insertions, deletions: deletions, updates: updates)
}
private func batchIndexPaths<T> (from edits: [Edit<T>], in section: Int) -> (insertions: [IndexPath], deletions: [IndexPath], updates: [IndexPath]) {
var insertions = [IndexPath](), deletions = [IndexPath](), updates = [IndexPath]()
for edit in edits {
let destinationIndexPath = IndexPath(item: edit.destination, section: section)
switch edit.operation {
case .deletion:
deletions.append(destinationIndexPath)
case .insertion:
insertions.append(destinationIndexPath)
case .move(let origin):
let originIndexPath = IndexPath(item: origin, section: section)
deletions.append(originIndexPath)
insertions.append(destinationIndexPath)
case .substitution:
updates.append(destinationIndexPath)
}
}
return (insertions: insertions, deletions: deletions, updates: updates)
}
| mpl-2.0 | ae1b1776dfdf5bdce41fdc25b8ad4244 | 43.302491 | 210 | 0.608161 | 4.747902 | false | false | false | false |
MrDeveloper4/TestProject-GitHubAPI | TestProject-GitHubAPI/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationLineScalePulseOut.swift | 5 | 1720 | //
// NVActivityIndicatorAnimationLineScalePulseOut.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/24/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
class NVActivityIndicatorAnimationLineScalePulseOut: NVActivityIndicatorAnimationDelegate {
func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let duration: CFTimeInterval = 1
let beginTime = CACurrentMediaTime()
let beginTimes = [0.4, 0.2, 0, 0.2, 0.4]
let timingFunction = CAMediaTimingFunction(controlPoints: 0.85, 0.25, 0.37, 0.85)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.4, 1]
animation.duration = duration
animation.repeatCount = HUGE
animation.removedOnCompletion = false
// Draw lines
for i in 0 ..< 5 {
let line = NVActivityIndicatorShape.Line.createLayerWith(size: CGSize(width: lineSize, height: size.height), color: color)
let frame = CGRect(x: x + lineSize * 2 * CGFloat(i),
y: y,
width: lineSize,
height: size.height)
animation.beginTime = beginTime + beginTimes[i]
line.frame = frame
line.addAnimation(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
| mit | c0a815fdf4d4a3f281acf2f5234c0c90 | 36.391304 | 134 | 0.616279 | 4.574468 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/is-graph-bipartite.swift | 2 | 2043 | /**
* https://leetcode.com/problems/is-graph-bipartite/
*
*
*/
// Date: Wed Mar 10 10:31:09 PST 2021
class Solution {
func isBipartite(_ graph: [[Int]]) -> Bool {
let n = graph.count
var color = Array(repeating: 0, count: n)
func dfs(_ start: Int) -> Bool {
let nextColor = 3 - color[start]
for next in graph[start] {
if color[next] == color[start] {
return false
}
if color[next] == 0 {
color[next] = nextColor
if dfs(next) == false { return false }
}
}
return true
}
for start in 0 ..< n {
if color[start] == 0 {
color[start] = 1
if dfs(start) == false {
return false
}
}
}
return true
}
}/**
* https://leetcode.com/problems/is-graph-bipartite/
*
*
*/
// Date: Wed Mar 10 10:36:12 PST 2021
class Solution {
func isBipartite(_ graph: [[Int]]) -> Bool {
let n = graph.count
var color = Array(repeating: 0, count: n)
for start in 0 ..< n {
if color[start] == 0 {
color[start] = 1
var queue = [start]
while queue.isEmpty == false {
var size = queue.count
while size > 0 {
size -= 1
let node = queue.removeFirst()
let c = color[node]
for next in graph[node] {
if color[next] == 0 {
color[next] = 3 - c
queue.append(next)
} else if color[next] == c {
return false
}
}
}
}
}
}
return true
}
} | mit | 8ee16b0b46ca977df56304c19efb6bc2 | 28.2 | 58 | 0.371023 | 4.762238 | false | false | false | false |
lieonCX/Live | Live/View/Home/Room/PlaybackBottomView.swift | 1 | 4129 | //
// PlaybackBottomView.swift
// Live
//
// Created by lieon on 2017/7/8.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class PlaybackBottomView: UIView {
var playAction: ((UIButton) -> Void)?
var onSeeckAction: ((UISlider) -> Void)?
var onSeekBeginAction: ((UISlider) -> Void)?
var onDragAction: ((UISlider) -> Void)?
fileprivate let disposeBag = DisposeBag()
lazy var playBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "play"), for: .normal)
btn.setImage(UIImage(named: "pause"), for: .highlighted)
btn.setImage(UIImage(named: "pause"), for: .selected)
return btn
}()
fileprivate lazy var timeLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 11)
label.textAlignment = .center
label.textColor = UIColor.white
label.text = "0:00/0:00"
return label
}()
lazy var slider: UISlider = {
let view = UISlider()
view.setThumbImage(UIImage(named: "preogress"), for: .normal)
view.setThumbImage(UIImage(named: "preogress"), for: .highlighted)
view.minimumTrackTintColor = UIColor.white.withAlphaComponent(0.5)
view.maximumTrackTintColor = UIColor.white
return view
}()
lazy var shareBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "play_share"), for: .normal)
btn.setImage(UIImage(named: "play_share"), for: .highlighted)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(playBtn)
addSubview(timeLabel)
addSubview(shareBtn)
addSubview(slider)
playBtn.snp.makeConstraints { (maker) in
maker.left.equalTo(12)
maker.centerY.equalTo(self.snp.centerY)
}
shareBtn.snp.makeConstraints { (maker) in
maker.right.equalTo(-12)
maker.centerY.equalTo(playBtn.snp.centerY)
}
slider.snp.makeConstraints { (maker) in
maker.left.equalTo(playBtn.snp.right).offset(12)
maker.centerY.equalTo(playBtn.snp.centerY)
maker.right.equalTo(shareBtn.snp.left).offset(-12)
}
timeLabel.snp.makeConstraints { (maker) in
maker.right.equalTo(slider.snp.right)
maker.top.equalTo(slider.snp.bottom).offset(-2)
}
slider.addTarget(self, action: #selector(self.onSeek(slider:)), for: .valueChanged)
slider.addTarget(self, action: #selector(self.onSeekBegin(slider:)), for: .touchDown)
slider.addTarget(self, action: #selector(self.onDrag(slider:)), for: .touchDragInside)
playBtn.addTarget(self, action: #selector(self.play(btn:)), for: .touchUpInside)
}
func setup(progress: Float, duration: Float) {
slider.maximumValue = duration
slider.setValue(progress, animated: false)
timeLabel.text = String(format: "%02d:%02d", Int(progress / 60.0), Int(progress.truncatingRemainder(dividingBy: 60.0))) + "/" + String(format: "%02d:%02d", Int(duration / 60.0), Int(duration.truncatingRemainder(dividingBy: 60.0)))
}
func setup(displayTime: Float) {
timeLabel.text = String(format: "%02d:%02d", Int(displayTime / 60.0), Int(displayTime.truncatingRemainder(dividingBy: 60.0))) + "/" + String(format: "%02d:%02d", Int(slider.maximumValue / 60.0), Int(slider.maximumValue .truncatingRemainder(dividingBy: 60.0)))
}
@objc fileprivate func onSeek(slider: UISlider) {
onSeeckAction?(slider)
}
@objc fileprivate func onSeekBegin(slider: UISlider) {
onSeekBeginAction?(slider)
}
@objc fileprivate func onDrag(slider: UISlider) {
onDragAction?(slider)
}
@objc fileprivate func play(btn: UIButton) {
playAction?(btn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | aa24a09955c8efb0314391877f851a3d | 35.192982 | 268 | 0.621183 | 4.159274 | false | false | false | false |
petetodd/BGSEmbeddedCVSwift | BGSEmbeddedCVSwift/StoryBoardCVC.swift | 1 | 2852 | //
// StoryBoardCVC.swift
// BGSEmbeddedCVSwift
//
// Created by Peter Todd Air on 05/12/2016.
// Copyright © 2016 Bright Green Star. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class StoryBoardCVC: UICollectionViewController {
var screenSize : CGRect!
var screenWidth : CGFloat!
var screenHeight : CGFloat!
override func viewDidLoad() {
super.viewDidLoad()
// screenSize = UIScreen.mainScreen().bounds
screenSize = self.view.frame
screenWidth = screenSize.width
screenHeight = screenSize.height
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
print(collectionView?.frame.width)
collectionView!.dataSource = self
collectionView!.delegate = self
collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView!.backgroundColor = UIColor.greenColor()
self.view.addSubview(collectionView!)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
if indexPath.row == 0
{
cell.backgroundColor = UIColor.blueColor()
}else
{
cell.backgroundColor = UIColor.whiteColor()
}
cell.layer.borderColor = UIColor.blackColor().CGColor
cell.layer.borderWidth = 0.5
// println(cell.frame.size.width)
cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
return cell
}
}
| mit | f020006fd86ac02463598dcaf4e38192 | 35.551282 | 169 | 0.674851 | 5.579256 | false | false | false | false |
Nikita2k/MDRotatingPieChart | MDRotatingPieChart-Example/MDRotatingPieChart/ViewController.swift | 3 | 4528 | //
// ViewController.swift
// MDRotatingPieChart
//
// Created by Maxime DAVID on 2015-04-03.
// Copyright (c) 2015 Maxime DAVID. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MDRotatingPieChartDelegate, MDRotatingPieChartDataSource {
var slicesData:Array<Data> = Array<Data>()
var pieChart:MDRotatingPieChart!
override func viewDidLoad() {
super.viewDidLoad()
pieChart = MDRotatingPieChart(frame: CGRectMake(0, 0, view.frame.width, view.frame.width))
slicesData = [
Data(myValue: 52.4, myColor: UIColor(red: 0.16, green: 0.73, blue: 0.61, alpha: 1), myLabel:"Apple"),
Data(myValue: 70.5, myColor: UIColor(red: 0.23, green: 0.6, blue: 0.85, alpha: 1), myLabel:"Banana"),
Data(myValue: 50, myColor: UIColor(red: 0.6, green: 0.36, blue: 0.71, alpha: 1), myLabel:"Coconut"),
Data(myValue: 60.1, myColor: UIColor(red: 0.46, green: 0.82, blue: 0.44, alpha: 1), myLabel:"Raspberry"),
Data(myValue: 40.9, myColor: UIColor(red: 0.94, green: 0.79, blue: 0.19, alpha: 1), myLabel:"Cherry"),
Data(myValue: 40.7, myColor: UIColor(red: 0.89, green: 0.49, blue: 0.19, alpha: 1), myLabel:"Mango")]
pieChart.delegate = self
pieChart.datasource = self
view.addSubview(pieChart)
/*
Here you can dig into some properties
-------------------------------------
var properties = Properties()
properties.smallRadius = 50
properties.bigRadius = 120
properties.expand = 25
properties.displayValueTypeInSlices = .Percent
properties.displayValueTypeCenter = .Label
properties.fontTextInSlices = UIFont(name: "Arial", size: 12)!
properties.fontTextCenter = UIFont(name: "Arial", size: 10)!
properties.enableAnimation = true
properties.animationDuration = 0.5
var nf = NSNumberFormatter()
nf.groupingSize = 3
nf.maximumSignificantDigits = 2
nf.minimumSignificantDigits = 2
properties.nf = nf
pieChart.properties = properties
*/
let title = UILabel(frame: CGRectMake(0, view.frame.width, view.frame.width, 100))
title.text = "@xouuox\n\nMDRotatingPieChart demo \nclick on a slice, or drag the pie :)"
title.textAlignment = .Center
title.numberOfLines = 4
view.addSubview(title)
let refreshBtn = UIButton(frame: CGRectMake((view.frame.width-200)/2, view.frame.width+100, 200, 50))
refreshBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
refreshBtn.setTitle("Refresh", forState: UIControlState.Normal)
refreshBtn.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.TouchUpInside)
refreshBtn.backgroundColor = UIColor.lightGrayColor()
view.addSubview(refreshBtn)
}
//Delegate
//some sample messages when actions are triggered (open/close slices)
func didOpenSliceAtIndex(index: Int) {
println("Open slice at \(index)")
}
func didCloseSliceAtIndex(index: Int) {
println("Close slice at \(index)")
}
func willOpenSliceAtIndex(index: Int) {
println("Will open slice at \(index)")
}
func willCloseSliceAtIndex(index: Int) {
println("Will close slice at \(index)")
}
//Datasource
func colorForSliceAtIndex(index:Int) -> UIColor {
return slicesData[index].color
}
func valueForSliceAtIndex(index:Int) -> CGFloat {
return slicesData[index].value
}
func labelForSliceAtIndex(index:Int) -> String {
return slicesData[index].label
}
func numberOfSlices() -> Int {
return slicesData.count
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
func refresh() {
pieChart.build()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
class Data {
var value:CGFloat
var color:UIColor = UIColor.grayColor()
var label:String = ""
init(myValue:CGFloat, myColor:UIColor, myLabel:String) {
value = myValue
color = myColor
label = myLabel
}
}
| mit | 0b544bffb493345a1c73160bcb9231a1 | 30.227586 | 117 | 0.609541 | 4.465483 | false | false | false | false |
mityung/XERUNG | IOS/Xerung/Xerung/AppDelegate.swift | 1 | 12794 | //
// AppDelegate.swift
// Xerung
//
// Created by mityung on 14/02/17.
// Copyright © 2017 mityung. All rights reserved.
//
import UIKit
import Contacts
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var contactStore = CNContactStore()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIApplication.shared.statusBarStyle = .lightContent
let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), for:UIBarMetrics.default)
UINavigationBar.appearance().barTintColor = UIColor(red: 50.0/255.0, green: 194.0/255.0, blue: 77.0/255.0, alpha: 0.8)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
UITabBarItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "helvetica", size: 12)!], for: .normal)
/* self.navigationController?.navigationBar.barTintColor = UIColor(red: 243.0/255.0, green: 100.0/255.0, blue: 36.0/255.0, alpha: 1.0)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()]
icolor = UIColor(red: 243.0/255.0, green: 100.0/255.0, blue: 36.0/255.0, alpha: 1.0)*/
registerForPushNotifications(application)
if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary {
// 2
UIApplication.shared.applicationIconBadgeNumber = 0
let aps = notification["aps"] as! [String: AnyObject]
// NotificationAlert = aps["alert"] as! String
}
createDatabase()
return true
}
func registerForPushNotifications(_ application: UIApplication) {
/*let notificationSettings = UIUserNotificationSettings(
types: [.badge, .sound, .alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)*/
if #available(iOS 10, *) {
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in }
application.registerForRemoteNotifications()
}
// iOS 9 support
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != UIUserNotificationType() {
application.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
var tokenString = ""
for i in 0..<deviceToken.count {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
UserDefaults.standard.setValue(tokenString, forKey: "deviceToken")
UserDefaults.standard.synchronize()
print("deviceToken \(tokenString)")
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register:", error)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print(notification.request.content.userInfo)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//Handle the notification
print(response.notification.request.content.userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
print(userInfo)
UIApplication.shared.applicationIconBadgeNumber = 0
let state: UIApplicationState = UIApplication.shared.applicationState
if state == .inactive {
print(userInfo)
}
}
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable: Any], completionHandler: @escaping () -> Void) {
// 1
let aps = userInfo["aps"] as! [String: AnyObject]
//NotificationAlert = aps["alert"] as! String
// 2
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func createDatabase(){
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let databasePath = documentsURL.appendingPathComponent("Xerung.sqlite")
let filemgr = FileManager.default
print(databasePath)
UserDefaults.standard.set(databasePath, forKey:"DataBasePath")
UserDefaults.standard.synchronize()
if !filemgr.fileExists(atPath: String(describing: databasePath)) {
let contactDB = FMDatabase(path: String(describing: databasePath))
if contactDB == nil {
print("Error: \(contactDB?.lastErrorMessage())")
}
if (contactDB?.open())! {
let sql_stmt = "CREATE TABLE IF NOT EXISTS Directory (ID INTEGER PRIMARY KEY AUTOINCREMENT , MADEBYPHONENO TEXT , MADEBYNAME TEXT, GROUPID TEXT, GROUPNAME TEXT, TAGNAME TEXT, DESCRITION TEXT, GROUPPHOTO TEXT, MEMBERCOUNT TEXT, ADMINFLAG TEXT, GROUPACCESSTYPE TEXT)"
if !(contactDB?.executeStatements(sql_stmt))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt1 = "CREATE TABLE IF NOT EXISTS DirectoryMember (ID INTEGER PRIMARY KEY AUTOINCREMENT , GroupData TEXT , GroupId TEXT)"
if !(contactDB?.executeStatements(sql_stmt1))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt2 = "CREATE TABLE IF NOT EXISTS PublicDirectory (ID INTEGER PRIMARY KEY AUTOINCREMENT , TAGNAME TEXT ,DESCRITION TEXT , GROUPACCESSTYPE TEXT, GROUPNAME TEXT, GROUPPHOTO TEXT,GROUPID TEXT)"
if !(contactDB?.executeStatements(sql_stmt2))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt3 = "CREATE TABLE IF NOT EXISTS PublicDirectoryMember (ID INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT ,phone TEXT , address TEXT, cityName TEXT,groupId TEXT)"
if !(contactDB?.executeStatements(sql_stmt3))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt4 = "CREATE TABLE IF NOT EXISTS GroupData (ID INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT , number TEXT , flag TEXT , address TEXT,UID TEXT,bloodGroup TEXT,city TEXT,profession TEXT,Date TEXT)"
if !(contactDB?.executeStatements(sql_stmt4))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt5 = "CREATE TABLE IF NOT EXISTS City (ID INTEGER PRIMARY KEY AUTOINCREMENT , cityId TEXT , cityName TEXT)"
if !(contactDB?.executeStatements(sql_stmt5))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
let sql_stmt6 = "CREATE TABLE IF NOT EXISTS Country (ID INTEGER PRIMARY KEY AUTOINCREMENT , countryName TEXT , countryCodeId TEXT, phoneCountryCode TEXT)"
if !(contactDB?.executeStatements(sql_stmt6))! {
print("Error: \(contactDB?.lastErrorMessage())")
}
contactDB?.close()
} else {
print("Error: \(contactDB?.lastErrorMessage())")
}
}
}
// MARK: Custom functions
class func getAppDelegate() -> AppDelegate {
return UIApplication.shared.delegate as! AppDelegate
}
func showMessage(_ message: String) {
let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
let dismissAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
}
alertController.addAction(dismissAction)
let pushedViewControllers = (self.window?.rootViewController as! UINavigationController).viewControllers
let presentedViewController = pushedViewControllers[pushedViewControllers.count - 1]
presentedViewController.present(alertController, animated: true, completion: nil)
}
func requestForAccess(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) {
let authorizationStatus = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch authorizationStatus {
case .authorized:
self.showMessage("Contact save Successfully.")
completionHandler(true)
case .denied, .notDetermined:
self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in
if access {
self.showMessage("Contact save Successfully.")
completionHandler(access)
}
else {
if authorizationStatus == CNAuthorizationStatus.denied {
DispatchQueue.main.async(execute: { () -> Void in
let message = "\(accessError!.localizedDescription)\n\nPlease allow the app to access your contacts through the Settings."
self.showMessage(message)
})
}
}
})
default:
completionHandler(false)
}
}
}
| apache-2.0 | d2ee3050aa356be952d425360580f85d | 43.574913 | 285 | 0.634566 | 5.857601 | false | false | false | false |
inspace-io/Social-Service-Browser | Example/Pods/SwiftyDropbox/Source/SwiftyDropbox/Shared/Handwritten/DropboxTransportClient.swift | 1 | 24353 | ///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
import Foundation
import Alamofire
open class DropboxTransportClient {
open let manager: SessionManager
open let backgroundManager: SessionManager
open let longpollManager: SessionManager
open var accessToken: String
open var selectUser: String?
var baseHosts: [String: String]
var userAgent: String
public convenience init(accessToken: String, selectUser: String? = nil) {
self.init(accessToken: accessToken, baseHosts: nil, userAgent: nil, selectUser: selectUser)
}
public init(accessToken: String, baseHosts: [String: String]?, userAgent: String?, selectUser: String?, sessionDelegate: SessionDelegate? = nil, backgroundSessionDelegate: SessionDelegate? = nil, serverTrustPolicyManager: ServerTrustPolicyManager? = nil, sharedContainerIdentifier: String? = nil) {
let config = URLSessionConfiguration.default
let delegate = sessionDelegate ?? SessionDelegate()
let serverTrustPolicyManager = serverTrustPolicyManager ?? nil
let manager = SessionManager(configuration: config, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager)
manager.startRequestsImmediately = false
let backgroundManager = { () -> SessionManager in
let backgroundConfig = URLSessionConfiguration.background(withIdentifier: "com.dropbox.SwiftyDropbox." + UUID().uuidString)
if let sharedContainerIdentifier = sharedContainerIdentifier{
backgroundConfig.sharedContainerIdentifier = sharedContainerIdentifier
}
if let backgroundSessionDelegate = backgroundSessionDelegate {
return SessionManager(configuration: backgroundConfig, delegate: backgroundSessionDelegate, serverTrustPolicyManager: serverTrustPolicyManager)
}
return SessionManager(configuration: backgroundConfig, serverTrustPolicyManager: serverTrustPolicyManager)
}()
backgroundManager.startRequestsImmediately = false
let longpollConfig = URLSessionConfiguration.default
longpollConfig.timeoutIntervalForRequest = 480.0
let longpollManager = SessionManager(configuration: longpollConfig, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager)
let defaultBaseHosts = [
"api": "https://api.dropbox.com/2",
"content": "https://api-content.dropbox.com/2",
"notify": "https://notify.dropboxapi.com/2",
]
let defaultUserAgent = "OfficialDropboxSwiftSDKv2/\(Constants.versionSDK)"
self.manager = manager
self.backgroundManager = backgroundManager
self.longpollManager = longpollManager
self.accessToken = accessToken
self.selectUser = selectUser
self.baseHosts = baseHosts ?? defaultBaseHosts
if let userAgent = userAgent {
let customUserAgent = "\(userAgent)/\(defaultUserAgent)"
self.userAgent = customUserAgent
} else {
self.userAgent = defaultUserAgent
}
}
open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType? = nil) -> RpcRequest<RSerial, ESerial> {
let host = route.attrs["host"]! ?? "api"
let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
var rawJsonRequest: Data?
rawJsonRequest = nil
if let serverArgs = serverArgs {
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
} else {
let voidSerializer = route.argSerializer as! VoidSerializer
let jsonRequestObj = voidSerializer.serialize(())
rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
}
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let customEncoding = SwiftyArgEncoding(rawJsonRequest: rawJsonRequest!)
let managerToUse = { () -> SessionManager in
// longpoll requests have a much longer timeout period than other requests
if type(of: route) == type(of: Files.listFolderLongpoll) {
return self.longpollManager
}
return self.manager
}()
let request = managerToUse.request(url, method: .post, parameters: ["jsonRequest": rawJsonRequest!], encoding: customEncoding, headers: headers)
request.task?.priority = URLSessionTask.highPriority
let rpcRequestObj = RpcRequest(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer)
request.resume()
return rpcRequestObj
}
struct SwiftyArgEncoding: ParameterEncoding {
fileprivate let rawJsonRequest: Data
init(rawJsonRequest: Data) {
self.rawJsonRequest = rawJsonRequest
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
urlRequest!.httpBody = rawJsonRequest
return urlRequest!
}
}
open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType, input: UploadBody) -> UploadRequest<RSerial, ESerial> {
let host = route.attrs["host"]! ?? "api"
let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let request: Alamofire.UploadRequest
switch input {
case let .data(data):
request = self.manager.upload(data, to: url, method: .post, headers: headers)
case let .file(file):
request = self.backgroundManager.upload(file, to: url, method: .post, headers: headers)
case let .stream(stream):
request = self.manager.upload(stream, to: url, method: .post, headers: headers)
}
let uploadRequestObj = UploadRequest(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer)
request.resume()
return uploadRequestObj
}
open func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType, overwrite: Bool, destination: @escaping (URL, HTTPURLResponse) -> URL) -> DownloadRequestFile<RSerial, ESerial> {
let host = route.attrs["host"]! ?? "api"
let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
weak var _self: DownloadRequestFile<RSerial, ESerial>!
let destinationWrapper: DownloadRequest.DownloadFileDestination = { url, resp in
var finalUrl = destination(url, resp)
if 200 ... 299 ~= resp.statusCode {
if FileManager.default.fileExists(atPath: finalUrl.path) {
if overwrite {
do {
try FileManager.default.removeItem(at: finalUrl)
} catch let error as NSError {
print("Error: \(error)")
}
} else {
print("Error: File already exists at \(finalUrl.path)")
}
}
} else {
_self.errorMessage = try! Data(contentsOf: url)
// Alamofire will "move" the file to the temporary location where it already resides,
// and where it will soon be automatically deleted
finalUrl = url
}
_self.urlPath = finalUrl
return (finalUrl, [])
}
let request = self.backgroundManager.download(url, method: .post, headers: headers, to: destinationWrapper)
let downloadRequestObj = DownloadRequestFile(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer)
_self = downloadRequestObj
request.resume()
return downloadRequestObj
}
public func request<ASerial, RSerial, ESerial>(_ route: Route<ASerial, RSerial, ESerial>,
serverArgs: ASerial.ValueType) -> DownloadRequestMemory<RSerial, ESerial> {
let host = route.attrs["host"]! ?? "api"
let url = "\(self.baseHosts[host]!)/\(route.namespace)/\(route.name)"
let routeStyle: RouteStyle = RouteStyle(rawValue: route.attrs["style"]!!)!
let jsonRequestObj = route.argSerializer.serialize(serverArgs)
let rawJsonRequest = SerializeUtil.dumpJSON(jsonRequestObj)
let headers = getHeaders(routeStyle, jsonRequest: rawJsonRequest, host: host)
let request = self.backgroundManager.request(url, method: .post, headers: headers)
let downloadRequestObj = DownloadRequestMemory(request: request, responseSerializer: route.responseSerializer, errorSerializer: route.errorSerializer)
request.resume()
return downloadRequestObj
}
fileprivate func getHeaders(_ routeStyle: RouteStyle, jsonRequest: Data?, host: String) -> HTTPHeaders {
var headers = ["User-Agent": self.userAgent]
let noauth = (host == "notify")
if (!noauth) {
headers["Authorization"] = "Bearer \(self.accessToken)"
if let selectUser = self.selectUser {
headers["Dropbox-Api-Select-User"] = selectUser
}
}
if (routeStyle == RouteStyle.Rpc) {
headers["Content-Type"] = "application/json"
} else if (routeStyle == RouteStyle.Upload) {
headers["Content-Type"] = "application/octet-stream"
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
} else if (routeStyle == RouteStyle.Download) {
if let jsonRequest = jsonRequest {
let value = asciiEscape(utf8Decode(jsonRequest))
headers["Dropbox-Api-Arg"] = value
}
}
return headers
}
}
open class Box<T> {
open let unboxed: T
init (_ v: T) { self.unboxed = v }
}
public enum CallError<EType>: CustomStringConvertible {
case internalServerError(Int, String?, String?)
case badInputError(String?, String?)
case rateLimitError(Auth.RateLimitError, String?, String?, String?)
case httpError(Int?, String?, String?)
case authError(Auth.AuthError, String?, String?, String?)
case accessError(Auth.AccessError, String?, String?, String?)
case routeError(Box<EType>, String?, String?, String?)
case clientError(Error?)
public var description: String {
switch self {
case let .internalServerError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Internal Server Error \(code)"
if let m = message {
ret += ": \(m)"
}
return ret
case let .badInputError(message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "Bad Input"
if let m = message {
ret += ": \(m)"
}
return ret
case let .authError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API auth error - \(error)"
return ret
case let .accessError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API access error - \(error)"
return ret
case let .httpError(code, message, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "HTTP Error"
if let c = code {
ret += "\(c)"
}
if let m = message {
ret += ": \(m)"
}
return ret
case let .routeError(box, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API route error - \(box.unboxed)"
return ret
case let .rateLimitError(error, _, _, requestId):
var ret = ""
if let r = requestId {
ret += "[request-id \(r)] "
}
ret += "API rate limit error - \(error)"
return ret
case let .clientError(err):
if let e = err {
return "\(e)"
}
return "An unknown system error"
}
}
}
func utf8Decode(_ data: Data) -> String {
return NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
}
func asciiEscape(_ s: String) -> String {
var out: String = ""
for char in s.unicodeScalars {
var esc = "\(char)"
if !char.isASCII {
esc = NSString(format:"\\u%04x", char.value) as String
} else {
esc = "\(char)"
}
out += esc
}
return out
}
public enum RouteStyle: String {
case Rpc = "rpc"
case Upload = "upload"
case Download = "download"
case Other
}
public enum UploadBody {
case data(Data)
case file(URL)
case stream(InputStream)
}
/// These objects are constructed by the SDK; users of the SDK do not need to create them manually.
///
/// Pass in a closure to the `response` method to handle a response or error.
open class Request<RSerial: JSONSerializer, ESerial: JSONSerializer> {
let responseSerializer: RSerial
let errorSerializer: ESerial
init(responseSerializer: RSerial, errorSerializer: ESerial) {
self.errorSerializer = errorSerializer
self.responseSerializer = responseSerializer
}
func handleResponseError(_ response: HTTPURLResponse?, data: Data?, error: Error?) -> CallError<ESerial.ValueType> {
let requestId = response?.allHeaderFields["X-Dropbox-Request-Id"] as? String
if let code = response?.statusCode {
switch code {
case 500...599:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .internalServerError(code, message, requestId)
case 400:
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .badInputError(message, requestId)
case 401:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .authError(Auth.AuthErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 403:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .accessError(Auth.AccessErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"),requestId)
default:
fatalError("Failed to parse error type")
}
case 409:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .routeError(Box(self.errorSerializer.deserialize(d["error"]!)), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 429:
let json = SerializeUtil.parseJSON(data!)
switch json {
case .dictionary(let d):
return .rateLimitError(Auth.RateLimitErrorSerializer().deserialize(d["error"]!), getStringFromJson(json: d, key: "user_message"), getStringFromJson(json: d, key: "error_summary"), requestId)
default:
fatalError("Failed to parse error type")
}
case 200:
return .clientError(error)
default:
return .httpError(code, "An error occurred.", requestId)
}
} else if response == nil {
return .clientError(error)
} else {
var message = ""
if let d = data {
message = utf8Decode(d)
}
return .httpError(nil, message, requestId)
}
}
func getStringFromJson(json: [String : JSON], key: String) -> String {
if let jsonStr = json[key] {
switch jsonStr {
case .str(let str):
return str;
default:
break;
}
}
return "";
}
}
/// An "rpc-style" request
open class RpcRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
open let request: Alamofire.DataRequest
public init(request: Alamofire.DataRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
open func cancel() {
self.request.cancel()
}
@discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void) -> Self {
self.request.validate().response(queue: queue) { response in
if let error = response.error {
completionHandler(nil, self.handleResponseError(response.response, data: response.data!, error: error))
} else {
completionHandler(self.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
}
return self
}
}
/// An "upload-style" request
open class UploadRequest<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
open let request: Alamofire.UploadRequest
public init(request: Alamofire.UploadRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
self.request.uploadProgress { progressData in
progressHandler(progressData)
}
return self
}
open func cancel() {
self.request.cancel()
}
@discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping (RSerial.ValueType?, CallError<ESerial.ValueType>?) -> Void) -> Self {
self.request.validate().response(queue: queue) { response in
if let error = response.error {
completionHandler(nil, self.handleResponseError(response.response, data: response.data!, error: error))
} else {
completionHandler(self.responseSerializer.deserialize(SerializeUtil.parseJSON(response.data!)), nil)
}
}
return self
}
}
/// A "download-style" request to a file
open class DownloadRequestFile<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
open let request: Alamofire.DownloadRequest
open var urlPath: URL?
open var errorMessage: Data
public init(request: Alamofire.DownloadRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
urlPath = nil
errorMessage = Data()
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
self.request.downloadProgress { progressData in
progressHandler(progressData)
}
return self
}
open func cancel() {
self.request.cancel()
}
@discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping ((RSerial.ValueType, URL)?, CallError<ESerial.ValueType>?) -> Void) -> Self {
self.request.validate().response(queue: queue) { response in
if let error = response.error {
completionHandler(nil, self.handleResponseError(response.response, data: self.errorMessage, error: error))
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = self.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
completionHandler((resultObject, self.urlPath!), nil)
}
}
return self
}
}
/// A "download-style" request to memory
open class DownloadRequestMemory<RSerial: JSONSerializer, ESerial: JSONSerializer>: Request<RSerial, ESerial> {
open let request: Alamofire.DataRequest
public init(request: Alamofire.DataRequest, responseSerializer: RSerial, errorSerializer: ESerial) {
self.request = request
super.init(responseSerializer: responseSerializer, errorSerializer: errorSerializer)
}
@discardableResult open func progress(_ progressHandler: @escaping ((Progress) -> Void)) -> Self {
self.request.downloadProgress { progressData in
progressHandler(progressData)
}
return self
}
open func cancel() {
self.request.cancel()
}
@discardableResult open func response(queue: DispatchQueue? = nil, completionHandler: @escaping ((RSerial.ValueType, Data)?, CallError<ESerial.ValueType>?) -> Void) -> Self {
self.request.validate().response(queue: queue) { response in
if let error = response.error {
completionHandler(nil, self.handleResponseError(response.response, data: response.data, error: error))
} else {
let headerFields: [AnyHashable : Any] = response.response!.allHeaderFields
let result = caseInsensitiveLookup("Dropbox-Api-Result", dictionary: headerFields)!
let resultData = result.data(using: .utf8, allowLossyConversion: false)
let resultObject = self.responseSerializer.deserialize(SerializeUtil.parseJSON(resultData!))
completionHandler((resultObject, response.data!), nil)
}
}
return self
}
}
func caseInsensitiveLookup(_ lookupKey: String, dictionary: [AnyHashable : Any]) -> String? {
for key in dictionary.keys {
let keyString = key as! String
if (keyString.lowercased() == lookupKey.lowercased()) {
return dictionary[key] as? String
}
}
return nil
}
| apache-2.0 | 4b6066fef472697e716f42589121dc50 | 39.520799 | 302 | 0.610602 | 5.180387 | false | false | false | false |
tad-iizuka/swift-sdk | Source/NaturalLanguageUnderstandingV1/Models/SentimentResult.swift | 1 | 2088 | /**
* Copyright IBM Corporation 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** The sentiment of the content. */
public struct SentimentResult: JSONDecodable {
/// The document level sentiment.
public let document: DocumentSentimentResults?
/// The targeted sentiment to analyze.
public let targets: [TargetedSentimentResults]?
/// Used internally to initialize a `SentimentResult` model from JSON.
public init(json: JSON) throws {
document = try? json.decode(at: "document", type: DocumentSentimentResults.self)
targets = try? json.decodedArray(at: "targets", type: TargetedSentimentResults.self)
}
}
/** The sentiment results of the document. */
public struct DocumentSentimentResults: JSONDecodable {
/// Sentiment score from -1 (negative) to 1 (positive).
public let score: Double?
/// Used internally to initialize a `DocumentSentimentResults` model from JSON.
public init(json: JSON) throws {
score = try? json.getDouble(at: "score")
}
}
/** The targeted sentiment results of the document. */
public struct TargetedSentimentResults: JSONDecodable {
/// Targeted text.
public let text: String?
/// Sentiment score from -1 (negative) to 1 (positive).
public let score: Double?
/// Used internally to initialize a `TargetedSentimentResults` model from JSON.
public init(json: JSON) throws {
text = try? json.getString(at: "text")
score = try? json.getDouble(at: "score")
}
}
| apache-2.0 | f4ee0d135c8cbcd7736e13c13ec36830 | 32.677419 | 92 | 0.696839 | 4.5 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | Solutions/Solutions/Medium/Medium_015_3Sum.swift | 1 | 2001 | /*
https://leetcode.com/problems/3sum/
#15 3Sum
Level: medium
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
Inspired by @peerlessbloom at https://leetcode.com/discuss/10756/my-accepted-o-n-2-solution-without-hashmap
*/
struct Medium_015_3Sum {
// O (N^2)
static func threeSum(_ num: [Int]) -> [[Int]] {
var res: [[Int]] = []
if num.count < 3 {
return res
} else {
let sorted: [Int] = num.sorted {$0 < $1}
var twoSum: Int
let size: Int = sorted.count
var i = 0
while i < size - 2 {
var l: Int = i + 1
var r: Int = size - 1
twoSum = 0 - sorted[i]
while l < r {
if sorted[l] + sorted[r] < twoSum {
l += 1
} else if sorted[l] + sorted[r] == twoSum {
var three: [Int] = []
three.append(sorted[i])
three.append(sorted[l])
three.append(sorted[r])
res.append(three)
repeat {
l += 1
} while l < r && sorted[l-1] == sorted[l]
repeat {
r -= 1
} while l < r && sorted[r+1] == sorted[r]
} else {
r -= 1
}
}
repeat {
i += 1
} while i < size - 1 && sorted[i-1] == sorted[i]
}
return res
}
}
}
| mit | f33903572e49b093e32c5e9e9223829b | 29.723077 | 155 | 0.41362 | 3.900391 | false | false | false | false |
Burning-Man-Earth/iBurn-iOS | iBurn/MainMapViewController.swift | 1 | 6575 | //
// MainMapViewController.swift
// iBurn
//
// Created by Chris Ballinger on 6/14/17.
// Copyright © 2017 Burning Man Earth. All rights reserved.
//
import UIKit
import YapDatabase
import CoreLocation
import BButton
import CocoaLumberjack
import PlayaGeocoder
public class MainMapViewController: BaseMapViewController {
let uiConnection: YapDatabaseConnection
let writeConnection: YapDatabaseConnection
/// This contains the buttons for finding the nearest POIs e.g. bathrooms
let sidebarButtons: SidebarButtonsView
let geocoder = PlayaGeocoder.shared
let search: SearchDisplayManager
private var observer: NSObjectProtocol?
var userMapViewAdapter: UserMapViewAdapter? {
return mapViewAdapter as? UserMapViewAdapter
}
deinit {
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
}
public init() {
uiConnection = BRCDatabaseManager.shared.uiConnection
writeConnection = BRCDatabaseManager.shared.readWriteConnection
sidebarButtons = SidebarButtonsView()
search = SearchDisplayManager(viewName: BRCDatabaseManager.shared.searchEverythingView)
search.tableViewAdapter.groupTransformer = GroupTransformers.searchGroup
let userSource = YapCollectionAnnotationDataSource(collection: BRCUserMapPoint.yapCollection)
userSource.allowedClass = BRCUserMapPoint.self
let mapView = MGLMapView()
let favoritesSource = YapViewAnnotationDataSource(viewHandler: YapViewHandler(viewName: BRCDatabaseManager.shared.everythingFilteredByFavorite))
let dataSource = AggregateAnnotationDataSource(dataSources: [userSource, favoritesSource])
let mapViewAdapter = UserMapViewAdapter(mapView: mapView, dataSource: dataSource)
super.init(mapViewAdapter: mapViewAdapter)
title = NSLocalizedString("Map", comment: "title for map view")
setupUserGuide()
self.observer = NotificationCenter.default.addObserver(forName: .BRCDatabaseExtensionRegistered,
object: BRCDatabaseManager.shared,
queue: .main,
using: { [weak self] (notification) in
self?.extensionRegisteredNotification(notification: notification)
})
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
// TODO: make sidebar buttons work
setupSidebarButtons()
setupSearchButton()
search.tableViewAdapter.delegate = self
definesPresentationContext = true
}
private func setupSidebarButtons() {
view.addSubview(sidebarButtons)
let bottom = sidebarButtons.autoPinEdge(toSuperviewMargin: .bottom)
bottom.constant = -50
sidebarButtons.autoPinEdge(toSuperviewMargin: .left)
sidebarButtons.autoSetDimensions(to: CGSize(width: 40, height: 150))
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
mapViewAdapter.reloadAnnotations()
geocodeNavigationBar()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
self.tabBarController?.tabBar.alpha = 1.0
self.navigationController?.setNavigationBarHidden(false, animated: animated)
self.sidebarButtons.isHidden = false
}
}
private extension MainMapViewController {
func extensionRegisteredNotification(notification: Notification) {
guard let extensionName = notification.userInfo?["extensionName"] as? String,
extensionName == BRCDatabaseManager.shared.everythingFilteredByFavorite else { return }
self.mapViewAdapter.reloadAnnotations()
}
// MARK: - Annotations
func setupUserGuide() {
sidebarButtons.findNearestAction = { [weak self] mapPointType, sender in
guard let location = self?.mapView.userLocation?.location else {
DDLogWarn("User location not found!")
return
}
self?.uiConnection.read { transaction in
if let point = UserGuidance.findNearest(userLocation: location, mapPointType: mapPointType, transaction: transaction) {
DDLogInfo("Found closest point: \(point)")
self?.mapView.selectAnnotation(point, animated: true, completionHandler: nil)
} else if mapPointType == .userBike || mapPointType == .userHome {
// If we can't find your bike or home, let's make a new one
self?.addUserMapPoint(type: mapPointType)
}
}
}
sidebarButtons.placePinAction = { [weak self] sender in
self?.addUserMapPoint(type: .userStar)
}
sidebarButtons.searchAction = { [weak self] sender in
self?.searchButtonPressed(sender)
}
}
func addUserMapPoint(type: BRCMapPointType) {
var coordinate = BRCLocations.blackRockCityCenter
if let userLocation = self.mapView.userLocation?.location {
coordinate = userLocation.coordinate
}
// don't drop user-location pins if youre not at BM
if !BRCLocations.burningManRegion.contains(coordinate) ||
!CLLocationCoordinate2DIsValid(coordinate) {
coordinate = BRCLocations.blackRockCityCenter
}
let mapPoint = BRCUserMapPoint(title: nil, coordinate: coordinate, type: type)
userMapViewAdapter?.editMapPoint(mapPoint)
}
}
extension MainMapViewController: YapTableViewAdapterDelegate {
public func didSelectObject(_ adapter: YapTableViewAdapter, object: DataObject, in tableView: UITableView, at indexPath: IndexPath) {
let nav = presentingViewController?.navigationController ??
navigationController
let detail = BRCDetailViewController(dataObject: object.object)
nav?.pushViewController(detail, animated: true)
}
}
extension MainMapViewController: SearchCooordinator {
var searchController: UISearchController {
return search.searchController
}
}
| mpl-2.0 | 6b742cb3eeda02b3533036cdf13f2007 | 40.607595 | 152 | 0.664892 | 5.647766 | false | false | false | false |
fabriciovergal/react-native-workers | example/ios/rnapp/AppDelegate.swift | 1 | 1183 | import Foundation
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool{
//Create default worker on port 8082
RNWorkersManager.sharedInstance().initWorker()
let jsCodeLocation = RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index.ios",
fallbackResource: "main")
let rootView = RCTRootView.init(bundleURL: jsCodeLocation, moduleName: "rnapp", initialProperties: nil, launchOptions: launchOptions)
rootView?.backgroundColor = UIColor.init(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1)
let rootViewController = UIViewController()
rootViewController.view = rootView
RNWorkersManager.sharedInstance().startWorkers(with: rootView)
self.window = UIWindow.init(frame: UIScreen.main.bounds)
self.window!.rootViewController = rootViewController
self.window!.makeKeyAndVisible()
return true
}
}
| apache-2.0 | 5759f8a3cc52a192f28c19197ef47e28 | 34.848485 | 148 | 0.69907 | 5.528037 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Views/ChartCandleStickView.swift | 14 | 2618 | //
// ChartCandleStickView.swift
// SwiftCharts
//
// Created by ischuetz on 29/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public class ChartCandleStickView: UIView {
private let innerRect: CGRect
private let fillColor: UIColor
private let strokeColor: UIColor
private var currentFillColor: UIColor
private var currentStrokeColor: UIColor
private let highlightColor = UIColor.redColor()
private let strokeWidth: CGFloat
var highlighted: Bool = false {
didSet {
if self.highlighted {
self.currentFillColor = self.highlightColor
self.currentStrokeColor = self.highlightColor
} else {
self.currentFillColor = self.fillColor
self.currentStrokeColor = self.strokeColor
}
self.setNeedsDisplay()
}
}
public init(lineX: CGFloat, width: CGFloat, top: CGFloat, bottom: CGFloat, innerRectTop: CGFloat, innerRectBottom: CGFloat, fillColor: UIColor, strokeColor: UIColor = UIColor.blackColor(), strokeWidth: CGFloat = 1) {
let frameX = lineX - width / CGFloat(2)
let frame = CGRectMake(frameX, top, width, bottom - top)
let t = innerRectTop - top
let hsw = strokeWidth / 2
self.innerRect = CGRectMake(hsw, t + hsw, width - strokeWidth, innerRectBottom - top - t - strokeWidth)
self.fillColor = fillColor
self.strokeColor = strokeColor
self.currentFillColor = fillColor
self.currentStrokeColor = strokeColor
self.strokeWidth = strokeWidth
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let wHalf = self.frame.width / 2
CGContextSetLineWidth(context, self.strokeWidth)
CGContextSetStrokeColorWithColor(context, self.currentStrokeColor.CGColor)
CGContextMoveToPoint(context, wHalf, 0)
CGContextAddLineToPoint(context, wHalf, self.frame.height)
CGContextStrokePath(context)
CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0)
CGContextSetFillColorWithColor(context, self.currentFillColor.CGColor)
CGContextFillRect(context, self.innerRect)
CGContextStrokeRect(context, self.innerRect)
}
}
| mit | aabae49d0a3bd60aa016c3dddd7c5080 | 31.320988 | 220 | 0.647441 | 5.123288 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/Pods/SkeletonView/Sources/SkeletonLayer.swift | 1 | 2588 | //
// SkeletonLayer.swift
// SkeletonView-iOS
//
// Created by Juanpe Catalán on 02/11/2017.
// Copyright © 2017 SkeletonView. All rights reserved.
//
import UIKit
public typealias SkeletonLayerAnimation = (CALayer) -> CAAnimation
public enum SkeletonType {
case solid
case gradient
var layer: CALayer {
switch self {
case .solid:
return CALayer()
case .gradient:
return CAGradientLayer()
}
}
var layerAnimation: SkeletonLayerAnimation {
switch self {
case .solid:
return { $0.pulse }
case .gradient:
return { $0.sliding }
}
}
}
struct SkeletonLayer {
private var maskLayer: CALayer
private weak var holder: UIView?
var type: SkeletonType {
return maskLayer is CAGradientLayer ? .gradient : .solid
}
var contentLayer: CALayer {
return maskLayer
}
init(withType type: SkeletonType, usingColors colors: [UIColor], andSkeletonHolder holder: UIView) {
self.holder = holder
self.maskLayer = type.layer
self.maskLayer.anchorPoint = .zero
self.maskLayer.bounds = holder.maxBoundsEstimated
addMultilinesIfNeeded()
self.maskLayer.tint(withColors: colors)
}
func update(usingColors colors: [UIColor]) {
layoutIfNeeded()
self.maskLayer.tint(withColors: colors)
}
func layoutIfNeeded() {
if let bounds = self.holder?.maxBoundsEstimated {
self.maskLayer.bounds = bounds
}
updateMultilinesIfNeeded()
}
func removeLayer() {
maskLayer.removeFromSuperlayer()
}
func addMultilinesIfNeeded() {
guard let multiLineView = holder as? ContainsMultilineText else { return }
maskLayer.addMultilinesLayers(lines: multiLineView.numLines, type: type, lastLineFillPercent: multiLineView.lastLineFillingPercent, multilineCornerRadius: multiLineView.multilineCornerRadius)
}
func updateMultilinesIfNeeded() {
guard let multiLineView = holder as? ContainsMultilineText else { return }
maskLayer.updateMultilinesLayers(lastLineFillPercent: multiLineView.lastLineFillingPercent)
}
}
extension SkeletonLayer {
func start(_ anim: SkeletonLayerAnimation? = nil) {
let animation = anim ?? type.layerAnimation
contentLayer.playAnimation(animation, key: "skeletonAnimation")
}
func stopAnimation() {
contentLayer.stopAnimation(forKey: "skeletonAnimation")
}
}
| mit | 3e969f1d6dd57fbfbeba384f6a546822 | 26.221053 | 199 | 0.650039 | 4.963532 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Supporting Files/UIComponents/PickerTrayController/Cells/ActionCell.swift | 1 | 4154 | //
// ActionCell.swift
// ImagePickerTrayController
//
// Created by Laurin Brandner on 22.11.16.
// Copyright © 2016 Laurin Brandner. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
let spacing = CGPoint(x: 26, y: 14)
fileprivate let stackViewOffset: CGFloat = 6
final class ActionCell: UICollectionViewCell {
weak var imagePickerTrayController: ImagePickerTrayController?
fileprivate let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.spacing = spacing.x/2
return stackView
}()
var actions = [ImagePickerAction]() {
willSet {
if newValue.count != actions.count {
stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
}
}
didSet {
if stackView.arrangedSubviews.count != actions.count {
actions.map { ActionButton(action: $0, target: self, selector: #selector(callAction(sender:))) }
.forEach { stackView.addArrangedSubview($0) }
}
}
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true
stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10).isActive = true
stackView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
stackView.widthAnchor.constraint(equalToConstant: 80).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func checkCameraAuthorizationStatus() -> Bool {
guard AVCaptureDevice.authorizationStatus(for: .video) == .authorized else {
return false
}
return true
}
fileprivate func checkPHLibraryAuthorizationStatus() -> Bool {
guard PHPhotoLibrary.authorizationStatus() == .authorized else {
return false
}
return true
}
fileprivate func performCallAction(index: Int, message: String, sourceType: UIImagePickerController.SourceType) {
var authorizationStatus = Bool()
if sourceType == .camera {
authorizationStatus = checkCameraAuthorizationStatus()
} else {
authorizationStatus = checkPHLibraryAuthorizationStatus()
}
guard authorizationStatus else {
basicErrorAlertWith(title: basicTitleForAccessError, message: message, controller: self.imagePickerTrayController!)
return
}
actions[index].call()
}
@objc fileprivate func callAction(sender: UIButton) {
guard let index = stackView.arrangedSubviews.firstIndex(of: sender) else { return }
switch index {
case 0: /* camera */
guard AVCaptureDevice.authorizationStatus(for: .video) != .notDetermined else {
AVCaptureDevice.requestAccess(for: .video) { (isCompleted) in
self.performCallAction(index: index, message: cameraAccessDeniedMessage, sourceType: .camera)
}
return
}
performCallAction(index: index, message: cameraAccessDeniedMessage, sourceType: .camera)
break
case 1: /* photo library */
guard PHPhotoLibrary.authorizationStatus() != .notDetermined else {
PHPhotoLibrary.requestAuthorization { (status) in
self.performCallAction(index: index, message: photoLibraryAccessDeniedMessage, sourceType: .photoLibrary)
}
return
}
performCallAction(index: index, message: photoLibraryAccessDeniedMessage, sourceType: .photoLibrary)
break
default: break
}
}
}
fileprivate class ActionButton: UIButton {
init(action: ImagePickerAction, target: Any, selector: Selector) {
super.init(frame: .zero)
setImage(action.image.withRenderingMode(.alwaysTemplate), for: .normal)
imageView?.tintColor = ThemeManager.currentTheme().generalTitleColor
imageView?.contentMode = .center
backgroundColor = .clear
layer.masksToBounds = true
addTarget(target, action: selector, for: .touchUpInside)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-3.0 | 454ac6b86bb63170bba4fcf69f7b3058 | 30.225564 | 121 | 0.718517 | 4.640223 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/SoftwareVideoThumbnailLayer.swift | 1 | 2450 | //
// SoftwareVideoThumbnailLayer.swift
// Telegram
//
// Created by Mikhail Filimonov on 27/05/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import Foundation
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
private final class SoftwareVideoThumbnailLayerNullAction: NSObject, CAAction {
@objc func run(forKey event: String, object anObject: Any, arguments dict: [AnyHashable : Any]?) {
}
}
final class SoftwareVideoThumbnailView: NSView {
private var asolutePosition: (CGRect, CGSize)?
var disposable = MetaDisposable()
var ready: (() -> Void)? {
didSet {
if self.layer?.contents != nil {
self.ready?()
}
}
}
init(account: Account, fileReference: FileMediaReference, synchronousLoad: Bool) {
super.init(frame: .zero)
self.layer?.backgroundColor = NSColor.clear.cgColor
self.layer?.contentsGravity = .resizeAspectFill
self.layer?.masksToBounds = true
if let dimensions = fileReference.media.dimensions {
self.disposable.set((mediaGridMessageVideo(postbox: account.postbox, fileReference: fileReference, scale: backingScaleFactor, synchronousLoad: synchronousLoad)
|> deliverOnMainQueue).start(next: { [weak self] transform in
var boundingSize = dimensions.size.aspectFilled(CGSize(width: 93.0, height: 93.0))
let imageSize = boundingSize
boundingSize.width = min(200.0, boundingSize.width)
let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: imageSize, boundingSize: boundingSize, intrinsicInsets: NSEdgeInsets(), resizeMode: .fill(.clear))
if let image = transform.execute(arguments, transform.data)?.generateImage() {
Queue.mainQueue().async {
if let strongSelf = self {
strongSelf.layer?.contents = image
strongSelf.ready?()
}
}
}
}))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
self.disposable.dispose()
}
}
| gpl-2.0 | faa57aa77cbee2404f96a40b3387240d | 32.094595 | 194 | 0.585953 | 5.347162 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift | 1 | 2104 | //
// RxScrollViewDelegateProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/19/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Please take a look at `DelegateProxyType.swift`
class RxScrollViewDelegateProxy : DelegateProxy
, UIScrollViewDelegate
, DelegateProxyType {
private var _contentOffsetSubject: ReplaySubject<CGPoint>?
unowned let scrollView: UIScrollView
var contentOffsetSubject: Observable<CGPoint> {
if _contentOffsetSubject == nil {
_contentOffsetSubject = ReplaySubject.create(bufferSize: 1)
sendNext(_contentOffsetSubject!, self.scrollView.contentOffset)
}
return _contentOffsetSubject!
}
required init(parentObject: AnyObject) {
self.scrollView = parentObject as! UIScrollView
super.init(parentObject: parentObject)
}
// delegate methods
func scrollViewDidScroll(scrollView: UIScrollView) {
if let contentOffset = _contentOffsetSubject {
sendNext(contentOffset, self.scrollView.contentOffset)
}
self._forwardToDelegate?.scrollViewDidScroll?(scrollView)
}
// delegate proxy
override class func createProxyForObject(object: AnyObject) -> AnyObject {
let scrollView = object as! UIScrollView
return castOrFatalError(scrollView.rx_createDelegateProxy())
}
class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let collectionView: UIScrollView = castOrFatalError(object)
collectionView.delegate = castOptionalOrFatalError(delegate)
}
class func currentDelegateFor(object: AnyObject) -> AnyObject? {
let collectionView: UIScrollView = castOrFatalError(object)
return collectionView.delegate
}
deinit {
if let contentOffset = _contentOffsetSubject {
sendCompleted(contentOffset)
}
}
}
| mit | d80564118fea871926461d77ef63d39e | 29.492754 | 85 | 0.665399 | 5.910112 | false | false | false | false |
aiaio/DesignStudioExpress | Pods/GMStepper/GMStepper/GMStepper.swift | 1 | 15681 | //
// GMStepper.swift
// GMStepper
//
// Created by Gunay Mert Karadogan on 1/7/15.
// Copyright © 2015 Gunay Mert Karadogan. All rights reserved.
//
import UIKit
@IBDesignable public class GMStepper: UIControl {
/// Current value of the stepper. Defaults to 0.
@IBInspectable public var value: Double = 0 {
didSet {
value = min(maximumValue, max(minimumValue, value))
let isInteger = floor(value) == value
if showIntegerIfDoubleIsInteger && isInteger {
label.text = String(stringInterpolationSegment: Int(value))
} else {
label.text = String(stringInterpolationSegment: value)
}
if oldValue != value {
sendActionsForControlEvents(.ValueChanged)
}
}
}
/// Minimum value. Must be less than maximumValue. Defaults to 0.
@IBInspectable public var minimumValue: Double = 0 {
didSet {
value = min(maximumValue, max(minimumValue, value))
}
}
/// Maximum value. Must be more than minimumValue. Defaults to 100.
@IBInspectable public var maximumValue: Double = 100 {
didSet {
value = min(maximumValue, max(minimumValue, value))
}
}
/// Step/Increment value as in UIStepper. Defaults to 1.
@IBInspectable public var stepValue: Double = 1
/// The same as UIStepper's autorepeat. If true, holding on the buttons or keeping the pan gesture alters the value repeatedly. Defaults to true.
@IBInspectable public var autorepeat: Bool = true
/// If the value is integer, it is shown without floating point.
@IBInspectable public var showIntegerIfDoubleIsInteger: Bool = true
/// Text on the left button. Be sure that it fits in the button. Defaults to "-".
@IBInspectable public var leftButtonText: String = "-" {
didSet {
leftButton.setTitle(leftButtonText, forState: .Normal)
}
}
/// Text on the right button. Be sure that it fits in the button. Defaults to "+".
@IBInspectable public var rightButtonText: String = "+" {
didSet {
rightButton.setTitle(rightButtonText, forState: .Normal)
}
}
/// Text color of the buttons. Defaults to white.
@IBInspectable public var buttonsTextColor: UIColor = UIColor.whiteColor() {
didSet {
for button in [leftButton, rightButton] {
button.setTitleColor(buttonsTextColor, forState: .Normal)
}
}
}
/// Background color of the buttons. Defaults to dark blue.
@IBInspectable public var buttonsBackgroundColor: UIColor = UIColor(red:0.21, green:0.5, blue:0.74, alpha:1) {
didSet {
for button in [leftButton, rightButton] {
button.backgroundColor = buttonsBackgroundColor
}
backgroundColor = buttonsBackgroundColor
}
}
/// Font of the buttons. Defaults to AvenirNext-Bold, 20.0 points in size.
public var buttonsFont = UIFont(name: "AvenirNext-Bold", size: 20.0)! {
didSet {
for button in [leftButton, rightButton] {
button.titleLabel?.font = buttonsFont
}
}
}
/// Text color of the middle label. Defaults to white.
@IBInspectable public var labelTextColor: UIColor = UIColor.whiteColor() {
didSet {
label.textColor = labelTextColor
}
}
/// Text color of the middle label. Defaults to lighter blue.
@IBInspectable public var labelBackgroundColor: UIColor = UIColor(red:0.26, green:0.6, blue:0.87, alpha:1) {
didSet {
label.backgroundColor = labelBackgroundColor
}
}
/// Font of the middle label. Defaults to AvenirNext-Bold, 25.0 points in size.
public var labelFont = UIFont(name: "AvenirNext-Bold", size: 25.0)! {
didSet {
label.font = labelFont
}
}
/// Corner radius of the stepper's layer. Defaults to 4.0.
@IBInspectable public var cornerRadius: CGFloat = 4.0 {
didSet {
layer.cornerRadius = cornerRadius
clipsToBounds = true
}
}
/// Percentage of the middle label's width. Must be between 0 and 1. Defaults to 0.5. Be sure that it is wide enough to show the value.
@IBInspectable public var labelWidthWeight: CGFloat = 0.5 {
didSet {
labelWidthWeight = min(1, max(0, labelWidthWeight))
setNeedsLayout()
}
}
/// Color of the flashing animation on the buttons in case the value hit the limit.
@IBInspectable public var limitHitAnimationColor: UIColor = UIColor(red:0.26, green:0.6, blue:0.87, alpha:1)
/**
Width of the sliding animation. When buttons clicked, the middle label does a slide animation towards to the clicked button. Defaults to 5.
*/
let labelSlideLength: CGFloat = 5
/// Duration of the sliding animation
let labelSlideDuration = NSTimeInterval(0.1)
/// Duration of the animation when the value hits the limit.
let limitHitAnimationDuration = NSTimeInterval(0.1)
lazy var leftButton: UIButton = {
let button = UIButton()
button.setTitle(self.leftButtonText, forState: .Normal)
button.setTitleColor(self.buttonsTextColor, forState: .Normal)
button.backgroundColor = self.buttonsBackgroundColor
button.titleLabel?.font = self.buttonsFont
button.addTarget(self, action: "leftButtonTouchDown:", forControlEvents: .TouchDown)
button.addTarget(self, action: "buttonTouchUp:", forControlEvents: UIControlEvents.TouchUpInside)
button.addTarget(self, action: "buttonTouchUp:", forControlEvents: UIControlEvents.TouchUpOutside)
return button
}()
lazy var rightButton: UIButton = {
let button = UIButton()
button.setTitle(self.rightButtonText, forState: .Normal)
button.setTitleColor(self.buttonsTextColor, forState: .Normal)
button.backgroundColor = self.buttonsBackgroundColor
button.titleLabel?.font = self.buttonsFont
button.addTarget(self, action: "rightButtonTouchDown:", forControlEvents: .TouchDown)
button.addTarget(self, action: "buttonTouchUp:", forControlEvents: UIControlEvents.TouchUpInside)
button.addTarget(self, action: "buttonTouchUp:", forControlEvents: UIControlEvents.TouchUpOutside)
return button
}()
lazy var label: UILabel = {
let label = UILabel()
label.textAlignment = .Center
if self.showIntegerIfDoubleIsInteger && floor(self.value) == self.value {
label.text = String(stringInterpolationSegment: Int(self.value))
} else {
label.text = String(stringInterpolationSegment: self.value)
}
label.textColor = self.labelTextColor
label.backgroundColor = self.labelBackgroundColor
label.font = self.labelFont
label.userInteractionEnabled = true
let panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
panRecognizer.maximumNumberOfTouches = 1
label.addGestureRecognizer(panRecognizer)
return label
}()
var labelOriginalCenter: CGPoint!
var labelMaximumCenterX: CGFloat!
var labelMinimumCenterX: CGFloat!
enum LabelPanState {
case Stable, HitRightEdge, HitLeftEdge
}
var panState = LabelPanState.Stable
enum StepperState {
case Stable, ShouldIncrease, ShouldDecrease
}
var stepperState = StepperState.Stable {
didSet {
if stepperState != .Stable {
updateValue()
if autorepeat {
scheduleTimer()
}
}
}
}
/// Timer used for autorepeat option
var timer: NSTimer?
/** When UIStepper reaches its top speed, it alters the value with a time interval of ~0.05 sec.
The user pressing and holding on the stepper repeatedly:
- First 2.5 sec, the stepper changes the value every 0.5 sec.
- For the next 1.5 sec, it changes the value every 0.1 sec.
- Then, every 0.05 sec.
*/
let timerInterval = NSTimeInterval(0.05)
/// Check the handleTimerFire: function. While it is counting the number of fires, it decreases the mod value so that the value is altered more frequently.
var timerFireCount = 0
var timerFireCountModulo: Int {
if timerFireCount > 80 {
return 1 // 0.05 sec * 1 = 0.05 sec
} else if timerFireCount > 50 {
return 2 // 0.05 sec * 2 = 0.1 sec
} else {
return 10 // 0.05 sec * 10 = 0.5 sec
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup() {
addSubview(leftButton)
addSubview(rightButton)
addSubview(label)
backgroundColor = buttonsBackgroundColor
layer.cornerRadius = cornerRadius
clipsToBounds = true
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reset", name: UIApplicationWillResignActiveNotification, object: nil)
}
public override func layoutSubviews() {
let buttonWidth = bounds.size.width * ((1 - labelWidthWeight) / 2)
let labelWidth = bounds.size.width * labelWidthWeight
leftButton.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: bounds.size.height)
label.frame = CGRect(x: buttonWidth, y: 0, width: labelWidth, height: bounds.size.height)
rightButton.frame = CGRect(x: labelWidth + buttonWidth, y: 0, width: buttonWidth, height: bounds.size.height)
labelMaximumCenterX = label.center.x + labelSlideLength
labelMinimumCenterX = label.center.x - labelSlideLength
labelOriginalCenter = label.center
}
func updateValue() {
if stepperState == .ShouldIncrease {
value += stepValue
} else if stepperState == .ShouldDecrease {
value -= stepValue
}
}
deinit {
resetTimer()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/// Useful closure for logging the timer interval. You can call this in the timer handler to test the autorepeat option. Not used in the current implementation.
// lazy var printTimerGaps: () -> () = {
// var prevTime: CFAbsoluteTime?
//
// return { _ in
// var now = CFAbsoluteTimeGetCurrent()
// if let prevTime = prevTime {
// print(now - prevTime)
// }
// prevTime = now
// }
// }()
}
// MARK: Pan Gesture
extension GMStepper {
func handlePan(gesture: UIPanGestureRecognizer) {
switch gesture.state {
case .Began:
leftButton.enabled = false
rightButton.enabled = false
case .Changed:
let translation = gesture.translationInView(label)
gesture.setTranslation(CGPointZero, inView: label)
let slidingRight = gesture.velocityInView(label).x > 0
let slidingLeft = gesture.velocityInView(label).x < 0
// Move the label with pan
if slidingRight {
label.center.x = min(labelMaximumCenterX, label.center.x + translation.x)
} else if slidingLeft {
label.center.x = max(labelMinimumCenterX, label.center.x + translation.x)
}
// When the label hits the edges, increase/decrease value and change button backgrounds
if label.center.x == labelMaximumCenterX {
// If not hit the right edge before, increase the value and start the timer. If already hit the edge, do nothing. Timer will handle it.
if panState != .HitRightEdge {
stepperState = .ShouldIncrease
panState = .HitRightEdge
}
animateLimitHitIfNeeded()
} else if label.center.x == labelMinimumCenterX {
if panState != .HitLeftEdge {
stepperState = .ShouldDecrease
panState = .HitLeftEdge
}
animateLimitHitIfNeeded()
} else {
panState = .Stable
stepperState = .Stable
resetTimer()
self.rightButton.backgroundColor = self.buttonsBackgroundColor
self.leftButton.backgroundColor = self.buttonsBackgroundColor
}
case .Ended, .Cancelled, .Failed:
reset()
default:
break
}
}
func reset() {
panState = .Stable
stepperState = .Stable
resetTimer()
leftButton.enabled = true
rightButton.enabled = true
label.userInteractionEnabled = true
UIView.animateWithDuration(self.labelSlideDuration, animations: {
self.label.center = self.labelOriginalCenter
self.rightButton.backgroundColor = self.buttonsBackgroundColor
self.leftButton.backgroundColor = self.buttonsBackgroundColor
})
}
}
// MARK: Button Events
extension GMStepper {
func leftButtonTouchDown(button: UIButton) {
rightButton.enabled = false
label.userInteractionEnabled = false
resetTimer()
if value == minimumValue {
animateLimitHitIfNeeded()
} else {
stepperState = .ShouldDecrease
animateSlideLeft()
}
}
func rightButtonTouchDown(button: UIButton) {
leftButton.enabled = false
label.userInteractionEnabled = false
resetTimer()
if value == maximumValue {
animateLimitHitIfNeeded()
} else {
stepperState = .ShouldIncrease
animateSlideRight()
}
}
func buttonTouchUp(button: UIButton) {
reset()
}
}
// MARK: Animations
extension GMStepper {
func animateSlideLeft() {
UIView.animateWithDuration(labelSlideDuration) {
self.label.center.x -= self.labelSlideLength
}
}
func animateSlideRight() {
UIView.animateWithDuration(labelSlideDuration) {
self.label.center.x += self.labelSlideLength
}
}
func animateToOriginalPosition() {
if self.label.center != self.labelOriginalCenter {
UIView.animateWithDuration(labelSlideDuration) {
self.label.center = self.labelOriginalCenter
}
}
}
func animateLimitHitIfNeeded() {
if value == minimumValue {
animateLimitHitForButton(leftButton)
} else if value == maximumValue {
animateLimitHitForButton(rightButton)
}
}
func animateLimitHitForButton(button: UIButton){
UIView.animateWithDuration(limitHitAnimationDuration) {
button.backgroundColor = self.limitHitAnimationColor
}
}
}
// MARK: Timer
extension GMStepper {
func handleTimerFire(timer: NSTimer) {
timerFireCount += 1
if timerFireCount % timerFireCountModulo == 0 {
updateValue()
}
}
func scheduleTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(timerInterval, target: self, selector: "handleTimerFire:", userInfo: nil, repeats: true)
}
func resetTimer() {
if let timer = timer {
timer.invalidate()
self.timer = nil
timerFireCount = 0
}
}
} | mit | a29bd3ec644909385c1ca7982c51cc85 | 32.941558 | 164 | 0.619643 | 5.074434 | false | false | false | false |
norio-nomura/Base32 | Sources/Base32/Base16.swift | 1 | 4222 | //
// Base16.swift
// Base32
//
// Created by 野村 憲男 on 2/7/15.
//
// Copyright (c) 2015 Norio Nomura
//
// 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: - Base16 Data <-> String
public func base16Encode(_ data: Data, uppercase: Bool = true) -> String {
return data.withUnsafeBytes {
base16encode($0.baseAddress!, $0.count, uppercase)
}
}
public func base16DecodeToData(_ string: String) -> Data? {
return base16decode(string)?.withUnsafeBufferPointer(Data.init(buffer:))
}
// MARK: - Base16 [UInt8] <-> String
public func base16Encode(_ array: [UInt8], uppercase: Bool = true) -> String {
return base16encode(array, array.count, uppercase)
}
public func base16Decode(_ string: String) -> [UInt8]? {
return base16decode(string)
}
// MARK: extensions
extension String {
// base16
public var base16DecodedData: Data? {
return base16DecodeToData(self)
}
public var base16EncodedString: String {
return utf8CString.withUnsafeBufferPointer {
base16encode($0.baseAddress!, $0.count - 1)
}
}
public func base16DecodedString(_ encoding: String.Encoding = .utf8) -> String? {
return base16DecodedData.flatMap {
String(data: $0, encoding: .utf8)
}
}
}
extension Data {
// base16
public var base16EncodedString: String {
return base16Encode(self)
}
public var base16EncodedData: Data {
return base16EncodedString.dataUsingUTF8StringEncoding
}
public var base16DecodedData: Data? {
return String(data: self, encoding: .utf8).flatMap(base16DecodeToData)
}
}
// MARK: encode
private func base16encode(_ data: UnsafeRawPointer, _ length: Int, _ uppercase: Bool = true) -> String {
let array = UnsafeBufferPointer.init(start: data.bindMemory(to: UInt8.self, capacity: length), count: length)
return array.map { String(format: uppercase ? "%02X" : "%02x", $0) }.reduce("", +)
}
// MARK: decode
extension UnicodeScalar {
fileprivate var hexToUInt8: UInt8? {
switch self {
case "0"..."9": return UInt8(value - UnicodeScalar("0").value)
case "a"..."f": return UInt8(0xa) + UInt8(value - UnicodeScalar("a").value)
case "A"..."F": return UInt8(0xa) + UInt8(value - UnicodeScalar("A").value)
default:
print("base16decode: Invalid hex character \(self)")
return nil
}
}
}
private func base16decode(_ string: String) -> [UInt8]? {
// validate length
let lenght = string.utf8CString.count - 1
if lenght % 2 != 0 {
print("base16decode: String must contain even number of characters")
return nil
}
var g = string.unicodeScalars.makeIterator()
var buffer = Array<UInt8>(repeating: 0, count: lenght / 2)
var index = 0
while let msn = g.next() {
if let msn = msn.hexToUInt8 {
if let lsn = g.next()?.hexToUInt8 {
buffer[index] = msn << 4 | lsn
} else {
return nil
}
} else {
return nil
}
index += 1
}
return buffer
}
| mit | 654814d43a5e4bb34e3f12c36667262c | 31.415385 | 113 | 0.649264 | 3.971725 | false | false | false | false |
kzaher/RxSwift | Tests/RxSwiftTests/SchedulerTests.swift | 2 | 4903 | //
// SchedulerTests.swift
// Tests
//
// Created by Krunoslav Zaher on 7/22/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import XCTest
#if os(Linux)
import Glibc
import Dispatch
#endif
import Foundation
class ConcurrentDispatchQueueSchedulerTests: RxTest {
func createScheduler() -> SchedulerType {
ConcurrentDispatchQueueScheduler(qos: .userInitiated)
}
}
final class SerialDispatchQueueSchedulerTests: RxTest {
func createScheduler() -> SchedulerType {
SerialDispatchQueueScheduler(qos: .userInitiated)
}
}
class OperationQueueSchedulerTests: RxTest {
}
extension ConcurrentDispatchQueueSchedulerTests {
func test_scheduleRelative() {
let expectScheduling = expectation(description: "wait")
let start = Date()
var interval = 0.0
let scheduler = self.createScheduler()
_ = scheduler.scheduleRelative(1, dueTime: .milliseconds(500)) { _ -> Disposable in
interval = Date().timeIntervalSince(start)
expectScheduling.fulfill()
return Disposables.create()
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(interval, 0.5, accuracy: 0.2)
}
func test_scheduleRelativeCancel() {
let expectScheduling = expectation(description: "wait")
let start = Date()
var interval = 0.0
let scheduler = self.createScheduler()
let disposable = scheduler.scheduleRelative(1, dueTime: .milliseconds(100)) { _ -> Disposable in
interval = Date().timeIntervalSince(start)
expectScheduling.fulfill()
return Disposables.create()
}
disposable.dispose()
DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(200)) {
expectScheduling.fulfill()
}
waitForExpectations(timeout: 0.5) { error in
XCTAssertNil(error)
}
XCTAssertEqual(interval, 0.0, accuracy: 0.0)
}
func test_schedulePeriodic() {
let expectScheduling = expectation(description: "wait")
let start = Date()
let times = Synchronized([Date]())
let scheduler = self.createScheduler()
let disposable = scheduler.schedulePeriodic(0, startAfter: .milliseconds(200), period: .milliseconds(300)) { state -> Int in
times.mutate { $0.append(Date()) }
if state == 1 {
expectScheduling.fulfill()
}
return state + 1
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
disposable.dispose()
XCTAssertEqual(times.value.count, 2)
XCTAssertEqual(times.value[0].timeIntervalSince(start), 0.2, accuracy: 0.1)
XCTAssertEqual(times.value[1].timeIntervalSince(start), 0.5, accuracy: 0.2)
}
func test_schedulePeriodicCancel() {
let expectScheduling = expectation(description: "wait")
var times = [Date]()
let scheduler = self.createScheduler()
let disposable = scheduler.schedulePeriodic(0, startAfter: .milliseconds(200), period: .milliseconds(300)) { state -> Int in
times.append(Date())
return state + 1
}
disposable.dispose()
DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(300)) {
expectScheduling.fulfill()
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(times.count, 0)
}
}
extension OperationQueueSchedulerTests {
func test_scheduleWithPriority() {
let expectScheduling = expectation(description: "wait")
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
let highPriority = OperationQueueScheduler(operationQueue: operationQueue, queuePriority: .high)
let lowPriority = OperationQueueScheduler(operationQueue: operationQueue, queuePriority: .low)
var times = [String]()
_ = highPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 0.4)
times.append("HIGH")
return Disposables.create()
}
_ = lowPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 1)
times.append("LOW")
expectScheduling.fulfill()
return Disposables.create()
}
_ = highPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 0.2)
times.append("HIGH")
return Disposables.create()
}
waitForExpectations(timeout: 4.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(["HIGH", "HIGH", "LOW"], times)
}
}
| mit | d374c2650020ac008228a1fc72298527 | 27.33526 | 132 | 0.618319 | 4.971602 | false | true | false | false |
anisimovsergey/lumino-ios | Lumino/ColorLineLayer.swift | 1 | 509 | //
// ColorLineLayer.swift
// Lumino
//
// Created by Sergey Anisimov on 02/04/2017.
// Copyright © 2017 Sergey Anisimov. All rights reserved.
//
import UIKit
class ColorLineLayer: CAGradientLayer {
override func layoutSublayers() {
super.layoutSublayers()
let path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.width / 2)
let mask = CAShapeLayer()
mask.path = path.cgPath
mask.fillColor = UIColor.black.cgColor
self.mask = mask
}
}
| mit | b846f508b0e5673c44371563656f4240 | 22.090909 | 84 | 0.659449 | 4.198347 | false | false | false | false |
tungvoduc/DTPagerController | DTPagerController/Classes/DTPagerController.swift | 1 | 23574 | //
// DTPagerController.swift
// Pods
//
// Created by tungvoduc on 15/09/2017.
//
//
import UIKit
/// PagerViewControllerDelegate
@objc public protocol DTPagerControllerDelegate: NSObjectProtocol {
@objc optional func pagerController(_ pagerController: DTPagerController, didChangeSelectedPageIndex index: Int)
@objc optional func pagerController(_ pagerController: DTPagerController, willChangeSelectedPageIndex index: Int, fromPageIndex oldIndex: Int)
@objc optional func pagerController(_ pagerController: DTPagerController, pageScrollViewDidScroll: UIScrollView)
}
/// DTPagerController
/// Used to create a pager controller of multiple view controllers.
open class DTPagerController: UIViewController, UIScrollViewDelegate {
/// scrollIndicator below the segmented control bar.
/// Default background color is blue.
open fileprivate(set) lazy var scrollIndicator: UIView = {
let bar = UIView()
bar.backgroundColor = UIColor.blue
return bar
}()
/// Delegate
@objc open weak var delegate: DTPagerControllerDelegate?
/// Preferred height of segmented control bar.
/// Default value is 44.
/// If viewControllers has less than 2 items, actual height is 0.
open var preferredSegmentedControlHeight: CGFloat = 44 {
didSet {
view.setNeedsLayout()
}
}
/// Height of segmented control bar
/// Get only
open var segmentedControlHeight: CGFloat {
return numberOfPages <= 1 ? 0 : preferredSegmentedControlHeight
}
/// Preferred of scroll indicator.
/// Default value is 2.
/// If viewControllers has less than 2 items, actual height is 0.
open var perferredScrollIndicatorHeight: CGFloat = 2 {
didSet {
// Update height and vertical position
scrollIndicator.bounds.size.height = scrollIndicatorHeight
scrollIndicator.frame.origin.y = segmentedControlHeight - scrollIndicatorHeight
}
}
/// Height of segmented indicator
/// Get only
open var scrollIndicatorHeight: CGFloat {
return numberOfPages <= 1 ? 0 : perferredScrollIndicatorHeight
}
var previousPageIndex: Int = 0
/// Automatically handle child view controllers' appearance transitions when switching between tabs
/// If you don't want viewWillAppear/viewDidAppear/viewWillDisappear/viewDidDisappear of child view
/// controllers to be called when switching tabs, this should be set to false.
/// Default value is true
open var automaticallyHandleAppearanceTransitions: Bool = true
/// View controllers in Pager View Controller
/// Get only.
open var viewControllers: [UIViewController] {
didSet {
removeChildViewControllers(oldValue)
setUpViewControllers()
}
}
/// Current index of pager
/// Setting selectedPageIndex before viewDidLoad is called will not have any effect.
/// Update selectedPageIndex will perform animation.
/// If you want to change page index without performing animation, use method setSelectedPageIndex(_: Int, animated: Bool).
/// - seealso: setSelectedPageIndex(_: Int, animated: Bool)
open var selectedPageIndex: Int {
set {
pageSegmentedControl.selectedSegmentIndex = newValue
if newValue != previousPageIndex {
pageSegmentedControl.sendActions(for: UIControl.Event.valueChanged)
}
}
get {
//pageSegmentedControl.selectedSegmentIndex can sometimes return -1, so return 0 instead
return pageSegmentedControl.selectedSegmentIndex < 0 ? 0 : pageSegmentedControl.selectedSegmentIndex
}
}
/// Normal text color in segmented control bar
/// Default value is UIColor.lightGray
public var textColor: UIColor = UIColor.lightGray {
didSet {
if viewIfLoaded != nil {
updateSegmentedNormalTitleTextAttributes()
}
}
}
/// Selected text color in segmented control bar
/// Default value is UIColor.black
public var selectedTextColor: UIColor = UIColor.blue {
didSet {
if viewIfLoaded != nil {
updateSegmentedSelectedTitleTextAttributes()
}
}
}
/// Normal text color in segmented control bar
/// Default value is UIColor.lightGray
public var font: UIFont = UIFont.systemFont(ofSize: UIFont.systemFontSize) {
didSet {
if viewIfLoaded != nil {
updateSegmentedNormalTitleTextAttributes()
}
}
}
/// Selected text color in segmented control bar
/// Default value is UIColor.black
public var selectedFont: UIFont = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize) {
didSet {
if viewIfLoaded != nil {
updateSegmentedSelectedTitleTextAttributes()
}
}
}
/// Page segmented control
open var pageSegmentedControl: UIControl & DTSegmentedControlProtocol
/// Page scroll view
/// This should not be exposed. Changing behavior of pageScrollView will destroy functionality of DTPagerController
public private(set) lazy var pageScrollView: UIScrollView = {
let pageScrollView = UIScrollView()
pageScrollView.showsHorizontalScrollIndicator = false
pageScrollView.isPagingEnabled = true
pageScrollView.scrollsToTop = false
return pageScrollView
}()
/// Initializer
/// - parameters:
/// - viewControllers: array of child view controllers displayed in pager controller.
public init(viewControllers controllers: [UIViewController]) {
pageSegmentedControl = DTSegmentedControl(items: [])
viewControllers = controllers
super.init(nibName: nil, bundle: nil)
}
/// Initializer
/// - parameters:
/// - viewControllers: array of child view controllers displayed in pager controller.
/// - pageSegmentedControl: segmented control used in pager controller.
public init(viewControllers controllers: [UIViewController], pageSegmentedControl segmentedControl: UIControl & DTSegmentedControlProtocol) {
pageSegmentedControl = segmentedControl
viewControllers = controllers
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
viewControllers = []
pageSegmentedControl = DTSegmentedControl(items: [])
super.init(coder: aDecoder)
}
deinit {
unobserveScrollViewDelegate(pageScrollView)
}
override open func loadView() {
super.loadView()
automaticallyAdjustsScrollViewInsets = false
edgesForExtendedLayout = UIRectEdge()
}
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
pageScrollView.delegate = self
observeScrollViewDelegate(pageScrollView)
setUpViewControllers()
updateSegmentedTitleTextAttributes()
// Add subviews
view.addSubview(pageScrollView)
view.addSubview(pageSegmentedControl)
view.addSubview(scrollIndicator)
}
open override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Update segmented control frame
pageSegmentedControl.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: segmentedControlHeight)
// Scroll view
setUpPageScrollView()
// Update child view controllers' view frame
for (index, viewController) in viewControllers.enumerated() {
if let view = viewController.viewIfLoaded {
view.frame = frameForChildViewController(at: index, numberOfPages: numberOfPages)
}
}
// Update scroll indicator's vertical position
setUpScrollIndicator()
}
// MARK: Segmented control action
@objc func pageSegmentedControlValueChanged() {
performUpdate(with: selectedPageIndex, previousPageIndex: previousPageIndex)
}
/// Update selected tab with or without animation
open func setSelectedPageIndex(_ selectedPageIndex: Int, animated: Bool) {
performUpdate(with: selectedPageIndex, previousPageIndex: previousPageIndex, animated: animated)
}
public var numberOfPages: Int { return viewControllers.count }
// Update selected tab
private func performUpdate(with selectedPageIndex: Int, previousPageIndex: Int, animated: Bool = true) {
if selectedPageIndex != previousPageIndex {
// Call delegate method before changing value
delegate?.pagerController?(self, willChangeSelectedPageIndex: selectedPageIndex, fromPageIndex: previousPageIndex)
let oldViewController = viewControllers[previousPageIndex]
let newViewController = viewControllers[selectedPageIndex]
if automaticallyHandleAppearanceTransitions {
oldViewController.beginAppearanceTransition(false, animated: true)
newViewController.beginAppearanceTransition(true, animated: true)
}
// Call these two methods to notify that two view controllers are being removed or added to container view controller (Check Documentation)
oldViewController.willMove(toParent: nil)
addChild(newViewController)
let animationDuration = animated ? 0.5 : 0.0
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 1.5, initialSpringVelocity: 5, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
self.pageScrollView.contentOffset = self.contentOffset(forSegmentedIndex: selectedPageIndex, withScrollViewWidth: self.pageScrollView.frame.width, numberOfPages: self.numberOfPages)
// Update status bar
self.setNeedsStatusBarAppearanceUpdate()
}, completion: { (_) -> Void in
//Call delegate method after changing value
self.delegate?.pagerController?(self, didChangeSelectedPageIndex: self.selectedPageIndex)
})
oldViewController.removeFromParent()
newViewController.didMove(toParent: self)
// Call these two methods to notify that two view controllers are already removed or added to container view controller (Check Documentation)
if automaticallyHandleAppearanceTransitions {
oldViewController.endAppearanceTransition()
newViewController.endAppearanceTransition()
}
// Setting up new previousPageIndex for next change
self.previousPageIndex = selectedPageIndex
}
}
// Remove all current child view controllers
private func removeChildViewControllers(_ childViewControllers: [UIViewController]) {
// Remove each child view controller and its view from parent view controller and its view hierachy
for viewController in childViewControllers {
if automaticallyHandleAppearanceTransitions {
viewController.beginAppearanceTransition(false, animated: false)
}
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
if automaticallyHandleAppearanceTransitions {
viewController.endAppearanceTransition()
}
}
}
// Setup new child view controllers
// Called in viewDidLoad or each time a new array of viewControllers is set
private func setUpViewControllers() {
if viewIfLoaded != nil {
// Setup page scroll view
setUpPageScrollView()
// Page segmented control
var titles = [String]()
for (_, viewController) in viewControllers.enumerated() {
titles.append(viewController.title ?? "")
}
// Set up segmented control
setUpSegmentedControl(viewControllers: viewControllers)
let indices = pageScrollView.visiblePageIndices()
// Then add subview, we do this later to prevent viewDidLoad of child view controllers to be called before page segment is allocated.
for (index, viewController) in viewControllers.enumerated() {
// Add view controller's view if it must be visible in scroll view
if let _ = indices.firstIndex(of: index) {
// Add to call viewDidLoad if needed
pageScrollView.addSubview(viewController.view)
viewController.view.frame = frameForChildViewController(at: index, numberOfPages: numberOfPages)
// This will call viewWillAppear
addChild(viewController)
// This will call viewDidAppear
viewController.didMove(toParent: self)
}
}
// Scroll indicator
setUpScrollIndicator()
}
}
public func setTitle(_ title: String?, forSegmentAt segment: Int) {
pageSegmentedControl.setTitle(title, forSegmentAt: segment)
}
public func setImage(_ image: UIImage?, forSegmentAt segment: Int) {
pageSegmentedControl.setImage(image, forSegmentAt: segment)
}
func setUpPageScrollView() {
let size = view.bounds.size
// Updating pageScrollView's frame or contentSize will automatically trigger scrollViewDidScroll(_: UIScrollView) and update selectedPageIndex
// We need to save the value of selectedPageIndex and update pageScrollView's horizontal content offset correctly.
let index = selectedPageIndex
pageScrollView.frame = CGRect(x: 0, y: segmentedControlHeight, width: size.width, height: size.height - segmentedControlHeight)
pageScrollView.contentSize = CGSize(width: pageScrollView.frame.width * CGFloat(numberOfPages), height: 0)
pageScrollView.contentOffset = contentOffset(forSegmentedIndex: index, withScrollViewWidth: pageScrollView.frame.width, numberOfPages: numberOfPages)
}
/// Setup pageSegmentedControl
/// This method is called every time new array of view controllers is set or in viewDidLoad.
/// If you provide a custom segmented control, all of your setup could be here. For example, create a new custom segmented control based on number of items in viewControllers and set with new titles.
open func setUpSegmentedControl(viewControllers: [UIViewController]) {
// Only remove all segments if using UISegmentedControl
if let pageSegmentedControl = pageSegmentedControl as? UISegmentedControl {
pageSegmentedControl.removeAllSegments()
}
for (index, _) in viewControllers.enumerated() {
// Only insert new segment if using default UISegmentedControl
if let pageSegmentedControl = pageSegmentedControl as? UISegmentedControl {
pageSegmentedControl.insertSegment(withTitle: "", at: index, animated: false)
}
// Call this method to setup appearance for every single segmented.
updateAppearanceForSegmentedItem(at: index)
}
// Add target if needed
if self != (pageSegmentedControl.target(forAction: #selector(pageSegmentedControlValueChanged), withSender: UIControl.Event.valueChanged) as? DTPagerController) {
pageSegmentedControl.addTarget(self, action: #selector(pageSegmentedControlValueChanged), for: UIControl.Event.valueChanged)
}
selectedPageIndex = previousPageIndex
}
open func setUpScrollIndicator() {
if numberOfPages > 0 {
scrollIndicator.frame.size = CGSize(width: view.bounds.width/CGFloat(numberOfPages), height: scrollIndicatorHeight)
}
scrollIndicator.frame.origin.y = segmentedControlHeight - scrollIndicatorHeight
updateScrollIndicatorHorizontalPosition(with: pageScrollView)
}
/// Use this method to set up appearance of segmented item at a certain index.
/// If you use custom segmented control, for example, with image and title, here is where you can customize appearance of each segmented item.
/// Please do not call super if you do not want the default behavior.
/// If not overriden, title of current view controller will be used for segmented item.
open func updateAppearanceForSegmentedItem(at index: Int) {
if let title = viewControllers[index].title {
pageSegmentedControl.setTitle(title, forSegmentAt: index)
}
}
// MARK: UIScrollViewDelegate's method
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
// Disable animation
UIView.setAnimationsEnabled(false)
// Delegate
delegate?.pagerController?(self, pageScrollViewDidScroll: scrollView)
// Add child view controller's view if needed
let indices = pageScrollView.visiblePageIndices()
for index in indices {
let viewController = viewControllers[index]
viewController.view.frame = frameForChildViewController(at: index, numberOfPages: numberOfPages)
pageScrollView.addSubview(viewController.view)
}
// Enable animation back
UIView.setAnimationsEnabled(true)
// Update bar position
updateScrollIndicatorHorizontalPosition(with: scrollView)
let index = segmentIndex(from: scrollView)
// Update segmented selected state only
if pageSegmentedControl.selectedSegmentIndex != index {
pageSegmentedControl.selectedSegmentIndex = index
}
}
private func frameForChildViewController(at index: Int, numberOfPages: Int) -> CGRect {
let offset = contentOffset(forSegmentedIndex: index, withScrollViewWidth: pageScrollView.frame.width, numberOfPages: numberOfPages)
return CGRect(x: offset.x, y: 0, width: pageScrollView.frame.width, height: pageScrollView.frame.height)
}
private func segmentIndex(from scrollView: UIScrollView) -> Int {
if scrollView.frame.width == 0 {
return 0
} else {
if UIView.userInterfaceLayoutDirection(for: view.semanticContentAttribute) == .rightToLeft {
// The view is shown in right-to-left mode right now.
return Int(round((scrollView.contentSize.width - scrollView.frame.width - scrollView.contentOffset.x) / scrollView.frame.width))
} else {
return Int(round(scrollView.contentOffset.x / scrollView.frame.width))
}
}
}
private func contentOffset(forSegmentedIndex index: Int, withScrollViewWidth width: CGFloat, numberOfPages: Int) -> CGPoint {
if numberOfPages == 0 { return .zero }
assert(index < numberOfPages, "Page index must be smaller than number of pages.")
if width == 0 || index >= numberOfPages { return .zero }
if UIView.userInterfaceLayoutDirection(for: view.semanticContentAttribute) == .rightToLeft {
return CGPoint(x: width * CGFloat(numberOfPages - index - 1), y: 0)
} else {
return CGPoint(x: width * CGFloat(index), y: 0)
}
}
// Update indicator center
open func updateScrollIndicatorHorizontalPosition(with scrollView: UIScrollView) {
let offsetRatio = scrollView.contentOffset.x / scrollView.contentSize.width
updateScrollIndicator(with: offsetRatio, scrollView: scrollView)
}
/// Update scroll indicator with offset ratio
open func updateScrollIndicator(with offsetRatio: CGFloat, scrollView: UIScrollView) {
if numberOfPages > 0 {
scrollIndicator.center.x = (offsetRatio + 1 / (CGFloat(numberOfPages) * 2 )) * scrollView.frame.width
}
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
selectedPageIndex = segmentIndex(from: scrollView)
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
selectedPageIndex = segmentIndex(from: scrollView)
}
}
// Observer
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
if let scrollView = object as? UIScrollView {
if scrollView == pageScrollView {
if keyPath == #keyPath(UIScrollView.delegate) {
if scrollView.delegate != nil {
fatalError("Cannot set delegate of pageScrollView to different object than the DTPagerController that owns it.")
}
}
}
}
}
// MARK: Segmented control setup
func updateSegmentedNormalTitleTextAttributes() {
pageSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor], for: .normal)
pageSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: textColor.withAlphaComponent(0.5)], for: [.normal, .highlighted])
}
func updateSegmentedSelectedTitleTextAttributes() {
pageSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: selectedFont, NSAttributedString.Key.foregroundColor: selectedTextColor], for: .selected)
pageSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: selectedFont, NSAttributedString.Key.foregroundColor: selectedTextColor.withAlphaComponent(0.5)], for: [.selected, .highlighted])
}
func updateSegmentedTitleTextAttributes() {
updateSegmentedNormalTitleTextAttributes()
updateSegmentedSelectedTitleTextAttributes()
}
// Observe delegate value changed to disallow that
// Called in viewDidLoad
func observeScrollViewDelegate(_ scrollView: UIScrollView) {
scrollView.addObserver(self, forKeyPath: #keyPath(UIScrollView.delegate), options: NSKeyValueObservingOptions.new, context: nil)
}
func unobserveScrollViewDelegate(_ scrollView: UIScrollView) {
// observeScrollViewDelegate is called in viewDidLoad
// check if viewDidLoad has been called before remove observer
if viewIfLoaded != nil {
scrollView.removeObserver(self, forKeyPath: #keyPath(UIScrollView.delegate), context: nil)
}
}
}
extension UIScrollView {
// Return page indices that are visible
func visiblePageIndices() -> [Int] {
guard frame.width > 0 else { return [] }
let numberOfPages = Int(ceil(contentSize.width / frame.width))
guard numberOfPages > 0 else { return [] }
let offsetRatio: CGFloat
if UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) == .rightToLeft {
offsetRatio = (contentSize.width - frame.width - contentOffset.x) / bounds.width
} else {
offsetRatio = contentOffset.x / bounds.width
}
if offsetRatio <= 0 {
return [0]
} else if offsetRatio >= CGFloat(numberOfPages - 1) {
return [numberOfPages - 1]
}
let floorValue = Int(floor(offsetRatio))
let ceilingValue = Int(ceil(offsetRatio))
if floorValue == ceilingValue {
return [floorValue]
}
return [floorValue, ceilingValue]
}
}
| mit | 323f741544f22688fb49fd7870a4e62f | 39.927083 | 211 | 0.677781 | 5.957544 | false | false | false | false |
chicio/RangeUISlider | RangeUISliderDemo/SetupProgrammaticViewController.swift | 1 | 4252 | //
// SetupProgrammaticViewController.swift
// Demo
//
// Created by Fabrizio Duroni on 03/05/2018.
// 2018 Fabrizio Duroni.
//
// swiftlint:disable function_body_length
import UIKit
import RangeUISlider
class SetupProgrammaticViewController: UIViewController, RangeUISliderDelegate {
private var rangeSlider: RangeUISlider!
override func viewDidLoad() {
super.viewDidLoad()
rangeSlider = RangeUISlider(frame: CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 100, height: 50)))
rangeSlider.translatesAutoresizingMaskIntoConstraints = false
rangeSlider.delegate = self
rangeSlider.scaleMinValue = 0 // If you don't set any value the default is 0
rangeSlider.scaleMaxValue = 100 // If you don't set any value the default is 1
rangeSlider.defaultValueLeftKnob = 25 // If the scale is the default one insert a value between 0 and 1
rangeSlider.defaultValueRightKnob = 75 // If the scale is the default one insert a value between 0 and 1
rangeSlider.rangeSelectedGradientColor1 = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
rangeSlider.rangeSelectedGradientColor2 = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
rangeSlider.rangeSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.rangeNotSelectedGradientColor1 = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
rangeSlider.rangeNotSelectedGradientColor2 = #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1)
rangeSlider.rangeNotSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeNotSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.barHeight = 20
rangeSlider.barCorners = 10
rangeSlider.leftKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.leftKnobWidth = 40
rangeSlider.leftKnobHeight = 40
rangeSlider.leftKnobCorners = 20
rangeSlider.rightKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.rightKnobWidth = 40
rangeSlider.rightKnobHeight = 40
rangeSlider.rightKnobCorners = 20
self.view.addSubview(rangeSlider)
// Setup slide with programmatic autolayout.
NSLayoutConstraint.activate([
NSLayoutConstraint(item: rangeSlider!,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: -20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .top,
relatedBy: .equal,
toItem: self.view,
attribute: .top,
multiplier: 1.0,
constant: 100),
NSLayoutConstraint(item: rangeSlider!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 50)
])
}
func rangeChangeFinished(event: RangeUISliderChangeFinishedEvent) {
print("FINISH min: \(event.minValueSelected) - max: \(event.maxValueSelected)")
}
func rangeIsChanging(event: RangeUISliderChangeEvent) {
print("min: \(event.minValueSelected) - max: \(event.maxValueSelected)")
}
}
| mit | 48e5413625cffef585a29f9c6d22135c | 47.873563 | 138 | 0.586783 | 5.080048 | false | false | false | false |
shaps80/Peek | Pod/Classes/Helpers/UIView+Extensions.swift | 1 | 2616 | /*
Copyright © 23/04/2016 Shaps
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
extension UIView {
/**
Returns the UIViewController that owns this view
- returns: The owning view controller
*/
@objc internal func owningViewController() -> UIViewController? {
var responder: UIResponder? = self
while !(responder is UIViewController) && superview != nil {
if let next = responder?.next {
responder = next
}
}
return responder as? UIViewController
}
/**
Returns the CGRect representing this view, within the coordinates of Peek's overlay view
- parameter view: The view to translate
- returns: A CGRect in the coordinate space of Peek's overlay view
*/
func frameInPeek(_ view: UIView) -> CGRect {
return convert(bounds, to: view)
}
/**
Returns the CGRect representing this view, excluding the current CGAffineTransform being applied to it
- parameter view: The view to translate
- returns: A CGRect in the coordinator space of Peek's overlay view
*/
func frameInPeekWithoutTransform(_ view: UIView) -> CGRect {
let center = self.center
let size = self.bounds.size
let rect = CGRect(x: center.x - size.width / 2, y: center.y - size.height / 2, width: size.width, height: size.height)
if let superview = self.superview {
return superview.convert(rect, to: view)
}
return CGRect.zero
}
}
| mit | 6b7e0c5fad1bb6fadcff5f34e279d2cb | 34.337838 | 126 | 0.67457 | 4.971483 | false | false | false | false |
MLSDev/AppRouter | Tests/Navigations/AppRouterNavigationsTests.swift | 1 | 9065 | //
// AppRouterNavigationsTests.swift
// AppRouter
//
// Created by Antihevich on 8/5/16.
// Copyright © 2016 Artem Antihevich. All rights reserved.
//
import XCTest
import AppRouter
class AppRouterNavigationsTests: XCTestCase {
override func setUp() {
AppRouter.rootViewController = nil
}
func testTabBarSelectedChange() {
let tabBar = UITabBarController()
let nav = NavigationControllerWithExpectations()
let first = AppRouterPresenterBaseController()
let second = AppRouterPresenterAdditionalController()
nav.viewControllers = [first]
tabBar.viewControllers = [nav, second]
XCTAssertTrue(tabBar.selectedViewController == nav)
XCTAssertTrue(tabBar.setSelectedViewController(AppRouterPresenterAdditionalController.self))
XCTAssertTrue(tabBar.selectedViewController == second)
XCTAssertTrue(tabBar.setSelectedViewController(AppRouterPresenterBaseController.self))
XCTAssertTrue(tabBar.selectedViewController == nav)
XCTAssertFalse(tabBar.setSelectedViewController(AppRouterPresenterTabBarController.self))
}
func testNavAccessors() {
let nav = UINavigationController()
let first = AppRouterPresenterBaseController()
let second = AppRouterPresenterAdditionalController()
nav.viewControllers = [first, second]
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
OperationQueue.main.addOperation {
guard let popped = nav.popToViewController(AppRouterPresenterBaseController.self, animated: false) else { return XCTFail() }
XCTAssertTrue(popped.count == 1)
XCTAssertNotNil(popped.first == second)
expectation.fulfill()
}
XCTAssertTrue(nav.topViewController == second)
XCTAssertNil(nav.popToViewController(AppRouterPresenterTabBarController.self, animated: false))
waitForExpectations(timeout: 1, handler: nil)
}
func testPopFromTop() {
let nav = UINavigationController()
let first = AppRouterPresenterBaseController()
let second = AppRouterPresenterAdditionalController()
nav.viewControllers = [first, second]
AppRouter.rootViewController = nav
XCTAssertTrue(AppRouter.topViewController == second)
let expectation = self.expectation(description: "")
AppRouter.popFromTopNavigation(animated: false, completion: {
XCTAssertTrue(AppRouter.topViewController == first)
expectation.fulfill()
})
waitForExpectations(timeout: 1, handler: nil)
}
func testPopViewController() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
let third = ThirdController()
XCTAssertNil(nav.popViewController(animated: false, completion: { XCTFail() }))
nav.viewControllers = [first]
XCTAssertNil(first.pop(animated: false, completion: { XCTFail() }))
nav.viewControllers = [first, second, third]
XCTAssertNil(first.pop(animated: true, completion: { XCTFail() }))
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
var popped : [UIViewController]? = []
popped = second.pop(animated: false) {
delay(0) {
XCTAssertTrue(popped?.first == second)
XCTAssertTrue(popped?.last == third)
XCTAssertNil(first.pop(animated: false))
expectation.fulfill()
}
}
waitForExpectations(timeout: 4, handler: nil)
}
func testPopGenericViewController() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
let third = ThirdController()
nav.viewControllers = [first, second, third]
XCTAssertNil(nav.popToViewController(UITabBarController.self, animated: false, completion: { XCTFail() }))
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
var popped : [UIViewController]? = []
popped = nav.popToViewController(FirstController.self, animated: false) {
delay(0){
XCTAssertTrue(popped?.first == second)
XCTAssertTrue(popped?.last == third)
XCTAssertTrue(nav.viewControllers.last == first)
expectation.fulfill()
}
}
waitForExpectations(timeout: 4, handler: nil)
}
func testPopToRootViewController() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
let third = ThirdController()
nav.viewControllers = [first, second, third]
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
var popped : [UIViewController]? = []
popped = nav.popToRootViewController(animated: false) {
delay(0){
XCTAssertTrue(popped?.first == second)
XCTAssertTrue(popped?.last == third)
XCTAssertTrue(nav.viewControllers.last == first)
expectation.fulfill()
}
}
waitForExpectations(timeout: 4, handler: nil)
}
func testCloseViewControllerAnimated() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
let third = ThirdController()
nav.viewControllers = [first, second]
AppRouter.rootViewController = nav
second.present(third, animated: false, completion: nil)
let expectation = self.expectation(description: "")
delay(0) {
XCTAssertTrue(third.close(){
XCTAssertNil(third.presentingViewController)
XCTAssertTrue(second.close(){
XCTAssertTrue(nav.topViewController == first)
XCTAssertFalse(nav.close())
expectation.fulfill()
})
})
}
waitForExpectations(timeout: 4, handler: nil)
}
func testCloseViewController() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
let third = ThirdController()
nav.viewControllers = [first, second]
AppRouter.rootViewController = nav
second.present(third, animated: false, completion: nil)
let expectation = self.expectation(description: "")
delay(0) {
XCTAssertTrue(third.close(animated: false){
XCTAssertNil(third.presentingViewController)
XCTAssertTrue(second.close(animated: false){
XCTAssertTrue(nav.topViewController == first)
XCTAssertFalse(nav.close(animated: false))
expectation.fulfill()
})
})
}
waitForExpectations(timeout: 4, handler: nil)
}
func testPushOnNavigationController() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
nav.viewControllers = [first]
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
delay(0) {
nav.pushViewController(second, animated: false) {
XCTAssertTrue(nav.viewControllers.last == second)
nav.pushViewController(second, animated: false, completion: {
XCTFail()
})
delay(0.1) {
expectation.fulfill()
}
}
}
waitForExpectations(timeout: 4, handler: nil)
}
func testPushOnNavigationControllerAnimated() {
let nav = UINavigationController()
let first = FirstController()
let second = SecondController()
nav.viewControllers = [first]
AppRouter.rootViewController = nav
let expectation = self.expectation(description: "")
delay(0) {
nav.pushViewController(second, animated: true) {
XCTAssertTrue(nav.viewControllers.last == second)
nav.pushViewController(second, animated: true, completion: {
XCTFail()
})
delay(0.5) {
expectation.fulfill()
}
}
}
waitForExpectations(timeout: 4, handler: nil)
}
}
internal func delay(_ delay:Double, _ closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
| mit | 0a281e3ab15d1ae423234cc291b63c60 | 36.147541 | 136 | 0.606906 | 5.747622 | false | true | false | false |
zarghol/SwiftZlib | Sources/ZStream.swift | 1 | 7690 | //
// File.swift
// SwiftZlib
//
// Created by Clément Nonn on 05/11/2016.
//
//
import Foundation
enum WrapperType {
case none
case gzip
case zlib
case any
}
class ZStream {
private static let maxWBits = 15 // 32K LZ77 window
private static let defWBits = ZStream.maxWBits
var next_in: [UInt8] // next input byte
var next_in_index: Int
var avail_in: Int // number of bytes available at next_in
var total_in: Int // total nb of input bytes read so far
var next_out: [UInt8] // next output byte should be put there
var next_out_index: Int
var avail_out: Int // remaining free space at next_out
var total_out: Int // total nb of bytes output so far
var msg: String
var dstate: Deflate?
var istate: Inflate?
var dataType: BlockType // best guess about the data type: ascii or binary
var adler: Checksum
init(adler: Checksum = Adler32()) {
self.adler = adler
}
// MARK:- Inflate
func inflateInit(wrapperType: WrapperType) throws {
try inflateInit(w: ZStream.defWBits, wrapperType: wrapperType)
}
func inflateInit(w: Int, wrapperType: WrapperType) throws {
var w = w
var nowrap = false
switch wrapperType {
case .none:
nowrap = true
case .gzip:
w += 16
default:
break
}
try inflateInit(w: w, nowrap: nowrap)
}
func inflateInit(w: Int = ZStream.defWBits, nowrap: Bool = false) throws {
try istate = Inflate(self, nowrap ? -w : w)
}
func inflate(f: Int) throws {
guard let inflate = istate else {
throw ZError.streamError
}
try inflate.inflate(f)
}
func inflateEnd() throws {
guard let inflate = istate else {
throw ZError.streamError
}
try inflate.inflateEnd()
}
func inflateSync() throws {
guard let inflate = istate else {
throw ZError.streamError
}
try inflate.inflateSync()
}
func inflateSyncPoint() throws {
guard let inflate = istate else {
throw ZError.streamError
}
try inflate.inflateSyncPoint()
}
func inflateSetDictionary(dictionary: [UInt8], dictLength: Int) throws {
guard let inflate = istate else {
throw ZError.streamError
}
try inflate.inflateSetDictionary(dictionary, dictLength)
}
func inflateFinished() -> Bool {
return istate?.mode == 12 /*DONE*/
}
// MARK:- Deflate
func deflateInit(level: Int, bits: Int, memlevel: Int, wrapperType: WrapperType) throws {
guard bits > 8 && bits < 16 else {
throw ZError.streamError
}
var bits = bits
switch wrapperType {
case .none:
bits *= -1
case .gzip:
bits += 16
case .any:
throw ZError.streamError
default:
break
}
try self.deflateInit(level: level, bits: bits, memlevel: memlevel)
}
func deflateInit(level: Int, bits: Int, memlevel: Int) throws {
dstate = try Deflate(stream: self, level: level, bits: bits, memlevel: memlevel)
}
func deflateInit(level: Int, bits: Int = ZStream.maxWBits, nowrap: Bool = false) throws {
dstate = try Deflate(stream: self, level: level, bits: nowrap ? -bits : bits)
}
func deflate(flush: Flush) throws {
guard let deflate = dstate else {
throw ZError.streamError
}
try deflate.deflate(flush: flush)
}
// func deflateEnd() throws {
// guard let deflate = dstate else {
// throw ZError.streamError
// }
// try deflate.deflateEnd()
// dstate = nil
// }
func deflateParams(level: Int, strategy: Strategy) throws {
guard let deflate = dstate else {
throw ZError.streamError
}
try deflate.deflateParams(level: level, strategy: strategy)
}
func deflateSetDictionary (dictionary: [UInt8], dictLength: Int) throws {
guard let deflate = dstate else {
throw ZError.streamError
}
try deflate.deflateSetDictionary(dictionary: dictionary, dictLength: dictLength)
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
func flush_pending() {
guard let deflate = dstate else {
return
}
let len = min(deflate.pending, avail_out)
if len == 0 {
return
}
// if dstate.pending_buf.length <= dstate.pending_out || next_out.length<=next_out_index || dstate.pending_buf.length<(dstate.pending_out+len) ||
// next_out.length<(next_out_index+len) {
// //System.out.println(dstate.pending_buf.length+", "+dstate.pending_out+
// // ", "+next_out.length+", "+next_out_index+", "+len);
// //System.out.println("avail_out="+avail_out);
// }
for i in 0..<len {
next_out[next_out_index + i] = deflate.pendingBuf[deflate.pendingOut + i]
}
next_out_index += len
deflate.pendingOut += len
total_out += len
avail_out -= len
deflate.pending -= len
if deflate.pending == 0 {
deflate.pendingOut = 0
}
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
func read_buf(buf: [UInt8], start: Int, size: Int) -> Int {
// FIXME: weird things with buf... should be a pointer ??
var buf = buf
guard let deflate = dstate else {
return 0
}
let len = min(avail_in, size)
if len == 0 {
return 0
}
avail_in -= len
if deflate.wrap != 0 {
adler.update(buf: next_in, index: next_in_index, length: len)
}
for i in 0..<len {
buf[start + i] = next_in[next_in_index + i]
}
next_in_index += len
total_in += len
return len
}
// MARK:- Others
var adlerValue: Int {
return self.adler.getValue()
}
func free() {
next_in.removeAll()
next_out.removeAll()
msg = ""
}
func setOutput(buf: [UInt8]) {
setOutput(buf: buf, offset: 0, length: buf.count)
}
func setOutput(buf: [UInt8], offset: Int, length: Int) {
next_out = buf
next_out_index = offset
avail_out = length
}
func setInput(buf: [UInt8], offset: Int, length: Int, append: Bool) {
// change || to && because nonsense of if
guard length > 0 && append && next_in.count == 0 else {
return
}
if avail_in > 0 && append {
next_in.append(contentsOf: buf)
next_in_index = 0
avail_in += length
} else {
next_in = buf
next_in_index = offset
avail_in = length
}
}
}
| mit | 004769dc1aac9272b21eea88aaed576f | 26.96 | 152 | 0.546235 | 4.290737 | false | false | false | false |
wangyuanou/Operation | testQueue/CLRequest.swift | 1 | 8148 | //
// CLRequest.swift
// testQueue
//
// Created by 王渊鸥 on 16/5/3.
// Copyright © 2016年 王渊鸥. All rights reserved.
//
import Foundation
import UIKit
class CLRequest {
var session:NSURLSession
var request:NSURLRequest
init(session:NSURLSession, request:NSURLRequest) {
self.session = session
self.request = request
}
func jsonArrayResponse(response:([AnyObject]?)->()) -> NSURLSession {
session.dataTaskWithRequest(request) { (data, resp, error) in
if let data = data {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if json is [AnyObject] {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(json as? [AnyObject])
})
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
} catch _ {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
}.resume()
return session
}
func jsonDictResponse(response:([String:AnyObject]?)->()) -> NSURLSession {
session.dataTaskWithRequest(request) { (data, resp, error) in
if let data = data {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if json is [String:AnyObject] {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(json as? [String:AnyObject])
})
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
} catch _ {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
}.resume()
return session
}
func stringResponse(response:(String?)->()) -> NSURLSession {
session.dataTaskWithRequest(request) { (data, resp, error) in
if let data = data {
let text = NSString(data: data, encoding: NSUTF8StringEncoding)
NSOperationQueue.mainQueue().addOperationWithBlock({
response(text as? String)
})
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
}.resume()
return session
}
func dataResponse(response:(NSData?)->()) -> NSURLSession {
session.dataTaskWithRequest(request) { (data, resp, error) in
NSOperationQueue.mainQueue().addOperationWithBlock({
response(data)
})
}.resume()
return session
}
func imageReponse(response:(UIImage?)->()) -> NSURLSession {
session.dataTaskWithRequest(request) { (data, resp, error) in
if let data = data {
let image = UIImage(data: data)
NSOperationQueue.mainQueue().addOperationWithBlock({
response(image)
})
} else {
NSOperationQueue.mainQueue().addOperationWithBlock({
response(nil)
})
}
}.resume()
return session
}
}
extension NSURLSession {
func POST(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 120)
request.HTTPMethod = "POST"
request.HTTPBody = NSData.setting {
let param = $0
parameters.forEach{ param.set($0.0, value: $0.1) }
}
return CLRequest(session: self, request: request)
}
func GET(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
let urlParam = parameters.reduce(url+"?") { $0+$1.0+":"+$1.1+"&" }
let request = NSMutableURLRequest(URL: NSURL(string: urlParam)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 120)
request.HTTPMethod = "GET"
return CLRequest(session: self, request: request)
}
func DELETE(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 120)
request.HTTPMethod = "DELETE"
request.HTTPBody = NSData.setting {
let param = $0
parameters.forEach{ param.set($0.0, value: $0.1) }
}
return CLRequest(session: self, request: request)
}
func OPTION(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 120)
request.HTTPMethod = "OPTION"
request.HTTPBody = NSData.setting {
let param = $0
parameters.forEach{ param.set($0.0, value: $0.1) }
}
return CLRequest(session: self, request: request)
}
}
class CLRequestClient {
var session:NSURLSession
static var baseURL = ""
static var shareParameters:[String:String] = [:]
init(session:NSURLSession) {
self.session = session
}
func getParameters(parameters:[String:String]) -> [String:String] {
var param = parameters
CLRequestClient.shareParameters.forEach{ param[$0.0] = $0.1 }
return param
}
func getURL(url:String) -> String {
let urlGap = CLRequestClient.baseURL.isEmpty||CLRequestClient.baseURL.hasSuffix("/") ? "" : "/"
return CLRequestClient.baseURL + urlGap + url
}
func POST(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
return session.POST(getURL(url), getParameters(parameters))
}
func GET(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
return session.GET(getURL(url), getParameters(parameters))
}
func DELETE(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
return session.DELETE(getURL(url), getParameters(parameters))
}
func OPTION(url:String, _ parameters:[String:String] = [:]) -> CLRequest {
return session.OPTION(getURL(url), getParameters(parameters))
}
}
extension NSOperationQueue {
//MARK:Session
func realTimeSession() -> NSURLSession {
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
return NSURLSession(configuration: config, delegate: nil, delegateQueue: self)
}
func cacheSession() -> NSURLSession {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
return NSURLSession(configuration: config, delegate: nil, delegateQueue: self)
}
//MARK:Client
func realTimeClient() -> CLRequestClient {
return CLRequestClient(session: realTimeSession())
}
func cacheClient() -> CLRequestClient {
return CLRequestClient(session: cacheSession())
}
static func setClientBaseURL(url:String) {
CLRequestClient.baseURL = url
}
static func setClientCommonParameters(parameters:[String:String]) {
CLRequestClient.shareParameters = parameters
}
}
| apache-2.0 | 1118a8312d699d1ac2ba9769475ed8e7 | 35.146667 | 156 | 0.563876 | 5.425617 | false | false | false | false |
allbto/WayThere | ios/WayThere/Pods/Nimble/Nimble/Matchers/BeLogical.swift | 156 | 3145 | import Foundation
internal func beBool(#expectedValue: BooleanType, #stringValue: String, #falseMatchesNil: Bool) -> MatcherFunc<BooleanType> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be \(stringValue)"
let actual = actualExpression.evaluate()
if expectedValue {
return actual?.boolValue == expectedValue.boolValue
} else if !falseMatchesNil {
return actual != nil && actual!.boolValue != !expectedValue.boolValue
} else {
return actual?.boolValue != !expectedValue.boolValue
}
}
}
// MARK: beTrue() / beFalse()
/// A Nimble matcher that succeeds when the actual value is exactly true.
/// This matcher will not match against nils.
public func beTrue() -> NonNilMatcherFunc<Bool> {
return basicMatcherWithFailureMessage(equal(true)) { failureMessage in
failureMessage.postfixMessage = "be true"
}
}
/// A Nimble matcher that succeeds when the actual value is exactly false.
/// This matcher will not match against nils.
public func beFalse() -> NonNilMatcherFunc<Bool> {
return basicMatcherWithFailureMessage(equal(false)) { failureMessage in
failureMessage.postfixMessage = "be false"
}
}
// MARK: beTruthy() / beFalsy()
/// A Nimble matcher that succeeds when the actual value is not logically false.
public func beTruthy() -> MatcherFunc<BooleanType> {
return beBool(expectedValue: true, stringValue: "truthy", falseMatchesNil: true)
}
/// A Nimble matcher that succeeds when the actual value is logically false.
/// This matcher will match against nils.
public func beFalsy() -> MatcherFunc<BooleanType> {
return beBool(expectedValue: false, stringValue: "falsy", falseMatchesNil: true)
}
extension NMBObjCMatcher {
public class func beTruthyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? }
return beTruthy().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalsyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? }
return beFalsy().matches(expr, failureMessage: failureMessage)
}
}
public class func beTrueMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? }
return beTrue().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalseMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? }
return beFalse().matches(expr, failureMessage: failureMessage)
}
}
}
| mit | 1dbf38e5a0e02c97966ac989f258bd0d | 40.381579 | 125 | 0.690302 | 5.105519 | false | false | false | false |
Incipia/Goalie | Goalie/SFXPlayer.swift | 1 | 3336 | //
// SFXPlayer.swift
// Goalie
//
// Created by Gregory Klein on 1/12/16.
// Copyright © 2016 Incipia. All rights reserved.
//
import Foundation
import AVFoundation
class SFXPlayer
{
fileprivate static let _sharedInstance = SFXPlayer()
fileprivate let _urlNames = ["Celeste", "DrumRoll", "Horns", "Kalimba", "MusicBox", "RockOn", "VSSPiano"]
fileprivate var _soundURLs: [URL] = []
fileprivate var _currentURLIndex = 0
fileprivate var _player = AVAudioPlayer()
init()
{
_setupURLs()
}
fileprivate func _setupURLs()
{
for name in _urlNames {
if let url = Bundle.main.url(forResource: name, withExtension: "mp3") {
_soundURLs.append(url)
}
}
}
fileprivate func _playCompleted()
{
let soundName = CharacterManager.currentCharacter.taskCompletedSoundName
if let url = Bundle.main.url(forResource: soundName, withExtension: "mp3") {
do {
_player = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
}
catch let error as NSError {
print(error.description)
}
_player.volume = 0.25
_player.enableRate = true
_player.rate = 1.5
_player.play()
}
}
fileprivate func _playDelete()
{
if let url = Bundle.main.url(forResource: "Delete", withExtension: "mp3") {
do {
_player = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
}
catch let error as NSError {
print(error.description)
}
_player.volume = 0.04
_player.play()
}
}
fileprivate func _playPriorityChange()
{
if let url = Bundle.main.url(forResource: "ChangePriorityRight", withExtension: "mp3") {
do {
_player = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
}
catch let error as NSError {
print(error.description)
}
_player.volume = 0.1
_player.play()
}
}
fileprivate func _advanceCompletedSound()
{
_currentURLIndex += 1
if _currentURLIndex >= _soundURLs.count {
_currentURLIndex = 0
}
}
fileprivate func _decrementCompletedSound()
{
_currentURLIndex -= 1
if _currentURLIndex < 0 {
_currentURLIndex = _soundURLs.count - 1
}
}
static func playCurrentCompletedSound()
{
_sharedInstance._playCompleted()
}
static func playDeleteSound()
{
_sharedInstance._playDelete()
}
static func playPriorityChangeSound()
{
_sharedInstance._playPriorityChange()
}
static func advanceCompletedSound()
{
_sharedInstance._advanceCompletedSound()
}
static func decrementCompletedSound()
{
_sharedInstance._decrementCompletedSound()
}
static func currentCompletedSoundName() -> String?
{
return _sharedInstance._urlNames[_sharedInstance._currentURLIndex]
}
}
extension GoalieCharacter
{
var taskCompletedSoundName: String {
switch self {
case .goalie: return "Kalimba"
case .fox: return "FoxSoundMstr"
case .bizeeBee: return "BusyBeeCompleted"
case .checklistor: return "AlienSoundMstr"
case .unknown: return ""
}
}
}
| apache-2.0 | 49295049a6fd8765fbc72c4e101e6f89 | 22.992806 | 108 | 0.597001 | 4.393939 | false | false | false | false |
johnnysay/GoodAccountsMakeGoodFriends | Good Accounts/Controllers/EventsViewController/EventViewController.swift | 1 | 6695 | //
// EventViewController.swift
// Good Accounts
//
// Created by Johnny on 12/02/2016.
// Copyright © 2016 fake. All rights reserved.
//
import UIKit
import XLPagerTabStrip
import RealmSwift
import Reusable
final class EventViewController: UIViewController, StoryboardBased {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var stackViewCenterYConstraint: NSLayoutConstraint!
var activeField: UITextField?
@IBOutlet weak var eventNameTextField: UITextField!
@IBOutlet weak var eventDateTextField: UITextField!
let accounts = RealmManager.getRealm().objects(Accounts.self).first
var selectedDate: Date? {
didSet {
if let selectedDate = selectedDate {
eventDateTextField.text = accounts?.formatted(date: selectedDate)
}
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
stackViewCenterYConstraint.constant -= navigationController?.navigationBar.bounds.height ?? 0
eventNameTextField.delegate = self
eventDateTextField.delegate = self
eventNameTextField.text = accounts?.name
eventDateTextField.text = accounts?.formattedSavedDate()
selectedDate = accounts?.date
addKeyboardToolbar()
registerForKeyboardNotifications()
}
// MARK: - Scrolling with keyboard appearing / disappearing
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWasShown(notification:)),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillBeHidden(notification:)),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
private func keyboardSize(from notification: NSNotification) -> CGSize? {
guard let info = notification.userInfo else { return nil }
return (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
}
@objc func keyboardWasShown(notification: NSNotification) {
guard let keyboardSize = keyboardSize(from: notification) else { return }
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
var aRect = view.frame
aRect.size.height -= keyboardSize.height
guard let activeField = activeField else { return }
if !aRect.contains(activeField.frame.origin) {
scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
@objc func keyboardWillBeHidden(notification: NSNotification) {
scrollView.contentInset = .zero
scrollView.scrollIndicatorInsets = .zero
}
// MARK: - DatePicker selector
@objc func datePickerValueChanged(_ sender: UIDatePicker) {
selectedDate = sender.date
}
// MARK: - Keyboard
func addKeyboardToolbar() {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: 50))
toolbar.barStyle = .default
let previousBarButtonItem = UIBarButtonItem(title: "Préc.", style: .plain, target: self, action: #selector(previousButtonAction))
let nextBarButtonItem = UIBarButtonItem(title: "Suiv.", style: .plain, target: self, action: #selector(nextButtonAction))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBarButtonItem = UIBarButtonItem(title: "OK", style: .done, target: self, action: #selector(doneButtonAction))
var items = [UIBarButtonItem]()
items.append(previousBarButtonItem)
items.append(nextBarButtonItem)
items.append(flexibleSpace)
items.append(doneBarButtonItem)
toolbar.items = items
toolbar.sizeToFit()
eventNameTextField.inputAccessoryView = toolbar
eventDateTextField.inputAccessoryView = toolbar
}
@objc func previousButtonAction() {
if eventNameTextField.isFirstResponder {
eventNameTextField.resignFirstResponder()
} else if eventDateTextField.isFirstResponder {
eventNameTextField.becomeFirstResponder()
}
}
@objc func nextButtonAction() {
if eventNameTextField.isFirstResponder {
eventDateTextField.becomeFirstResponder()
} else if eventDateTextField.isFirstResponder {
eventDateTextField.resignFirstResponder()
}
}
@objc func doneButtonAction() {
eventNameTextField.resignFirstResponder()
eventDateTextField.resignFirstResponder()
}
}
// MARK: - UITextFieldDelegate
extension EventViewController: UITextFieldDelegate {
func textFieldShouldClear(_ textField: UITextField) -> Bool {
selectedDate = nil
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == eventDateTextField {
let datePickerView = UIDatePicker()
datePickerView.datePickerMode = .date
eventDateTextField.inputView = datePickerView
if selectedDate == nil {
selectedDate = Date()
}
datePickerView.date = selectedDate ?? Date()
datePickerView.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)
}
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
activeField = nil
let realm = RealmManager.getRealm()
switch textField {
case eventNameTextField:
try! realm.write {
if eventNameTextField.text == "" {
accounts?.name = nil
} else {
accounts?.name = eventNameTextField.text
}
}
case eventDateTextField:
try! realm.write {
accounts?.date = selectedDate
}
default:
break
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
// MARK: - IndicatorInfoProvider
extension EventViewController: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return IndicatorInfo(title: "ÉVÉNEMENT")
}
}
| mit | 510d7be2b6f222480c8b698bfa0de01a | 30.861905 | 131 | 0.662532 | 5.60855 | false | false | false | false |
tzef/BmoImageLoader | BmoImageLoader/Classes/ProgressAnimation/CircleBrushProgressAnimation.swift | 1 | 8396 | //
// CircleBrushProgressAnimation.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/7.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
class CircleBrushProgressAnimation: BaseProgressAnimation, BmoProgressHelpProtocol {
var darkerView = BmoProgressHelpView()
var containerView: BmoProgressHelpView!
var containerViewMaskLayer = CAShapeLayer()
var newImageView = BmoProgressImageView()
let newImageViewMaskLayer = CAShapeLayer()
var oldImage: UIImage?
var borderShape: Bool!
convenience init(imageView: UIImageView, newImage: UIImage?, borderShape: Bool) {
self.init()
self.borderShape = borderShape
self.imageView = imageView
self.newImage = newImage
self.oldImage = imageView.image
self.containerView = BmoProgressHelpView(delegate: self)
marginPercent = (borderShape ? 0.1 : 0.5)
self.resetAnimation().closure()
}
// MARK : - Override
override func displayLinkAction(_ dis: CADisplayLink) {
if let helpPoint = helpPointView.layer.presentation()?.bounds.origin {
if helpPoint.x == CGFloat(self.progress.fractionCompleted) {
self.displayLink?.invalidate()
self.displayLink = nil
}
let radius = sqrt(pow(newImageView.bounds.width / 2, 2) + pow(newImageView.bounds.height / 2, 2))
let startAngle = CGFloat(-1 * Double.pi/2)
let circlePath = UIBezierPath(arcCenter: newImageView.center,
radius: radius,
startAngle: startAngle,
endAngle: helpPoint.x * CGFloat(Double.pi * 2) + startAngle,
clockwise: true)
circlePath.addLine(to: newImageView.center)
newImageViewMaskLayer.path = circlePath.cgPath
}
}
override func successAnimation(_ imageView: UIImageView) {
if self.borderShape == false {
imageView.image = self.newImage
UIView.animate(withDuration: self.transitionDuration, animations: {
self.darkerView.alpha = 0.0
self.containerView.alpha = 0.0
}, completion: { (finished) in
self.completionBlock?(.success(self.newImage))
imageView.bmo_removeProgressAnimation()
})
} else {
UIView.transition(
with: imageView,
duration: self.transitionDuration,
options: .transitionCrossDissolve,
animations: {
self.newImageView.alpha = 1.0
self.newImageView.image = self.newImage
}, completion: { (finished) in
var maskPath: UIBezierPath!
if let maskLayer = imageView.layer.mask as? CAShapeLayer, maskLayer.path != nil {
maskPath = UIBezierPath(cgPath: maskLayer.path!)
} else {
maskPath = UIBezierPath(rect: imageView.bounds)
}
self.containerViewMaskLayer.path = maskPath.cgPath
CATransaction.begin()
CATransaction.setCompletionBlock({
self.imageView?.image = self.newImage
self.completionBlock?(.success(self.newImage))
imageView.bmo_removeProgressAnimation()
})
let animateEnlarge = CABasicAnimation(keyPath: "transform")
let translatePoint = CGPoint(
x: maskPath.bounds.width * self.marginPercent / 2 + maskPath.bounds.origin.x * self.marginPercent,
y: maskPath.bounds.height * self.marginPercent / 2 + maskPath.bounds.origin.y * self.marginPercent)
var transform3D = CATransform3DIdentity
transform3D = CATransform3DTranslate(transform3D, translatePoint.x, translatePoint.y, 0)
transform3D = CATransform3DScale(transform3D, 1 - self.marginPercent, 1 - self.marginPercent, 1)
animateEnlarge.duration = self.enlargeDuration
animateEnlarge.fromValue = NSValue(caTransform3D: transform3D)
self.containerViewMaskLayer.add(animateEnlarge, forKey: "enlarge")
CATransaction.commit()
}
)
}
}
override func failureAnimation(_ imageView: UIImageView, error: NSError?) {
UIView.animate(withDuration: self.transitionDuration, animations: {
self.darkerView.alpha = 0.0
imageView.image = self.oldImage
}, completion: { (finished) in
if finished {
self.completionBlock?(.failure(error))
imageView.bmo_removeProgressAnimation()
}
})
}
//MARK: - ProgressAnimator Protocol
override func resetAnimation() -> BmoProgressAnimator {
guard let strongImageView = self.imageView else {
return self
}
strongImageView.layoutIfNeeded()
strongImageView.bmo_removeProgressAnimation()
helpPointView.frame = CGRect.zero
strongImageView.addSubview(helpPointView)
strongImageView.addSubview(darkerView)
if strongImageView.image != nil {
darkerView.backgroundColor = UIColor.black
darkerView.alpha = 0.4
} else {
if let checkerBoard = CIFilter(name: "CICheckerboardGenerator", withInputParameters: [
"inputColor0" : CIColor(color: UIColor.black),
"inputColor1" : CIColor(color: UIColor.white),
kCIInputWidthKey : 10
])?.outputImage {
let context = CIContext()
let drawRect = CGRect(x: 0.0, y: 0.0, width: 40, height: 40)
let outputImage = context.createCGImage(checkerBoard, from: drawRect)
darkerView.backgroundColor = UIColor(patternImage: UIImage(cgImage: outputImage!))
} else {
darkerView.backgroundColor = UIColor.white
}
}
darkerView.autoFit(strongImageView)
strongImageView.addSubview(containerView)
containerView.autoFit(strongImageView)
newImageView.contentMode = strongImageView.contentMode
newImageView.layer.masksToBounds = strongImageView.layer.masksToBounds
containerView.addSubview(newImageView)
newImageView.autoFit(containerView)
if borderShape == true {
if let maskLayer = strongImageView.layer.mask as? CAShapeLayer, maskLayer.path != nil {
containerViewMaskLayer.path = maskLayer.path!.insetPath(marginPercent)
} else {
containerViewMaskLayer.path = CGPath(rect: strongImageView.bounds, transform: nil).insetPath(marginPercent)
}
} else {
containerViewMaskLayer.path = BmoShapeHelper.getShapePath(.circle, rect: strongImageView.bounds).insetPath(marginPercent)
}
containerView.layer.mask = containerViewMaskLayer
if let image = newImage {
strongImageView.image = image
newImageView.image = image
} else {
newImageView.backgroundColor = progressColor
newImageView.alpha = 0.4
}
newImageViewMaskLayer.path = CGMutablePath()
newImageView.layer.mask = newImageViewMaskLayer
return self
}
//MARK: - ProgressHelpProtocol
func layoutChanged(_ target: AnyObject) {
guard let strongImageView = self.imageView else {
return
}
if borderShape == true {
if let maskLayer = strongImageView.layer.mask as? CAShapeLayer, maskLayer.path != nil {
containerViewMaskLayer.path = maskLayer.path!.insetPath(marginPercent)
} else {
containerViewMaskLayer.path = CGPath(rect: strongImageView.bounds, transform: nil).insetPath(marginPercent)
}
} else {
containerViewMaskLayer.path = BmoShapeHelper.getShapePath(.circle, rect: strongImageView.bounds).insetPath(marginPercent)
}
}
}
| mit | 6755dd9636c9c36f3a61e70cf2ea9f68 | 42.942408 | 133 | 0.595258 | 5.547257 | false | false | false | false |
crazypoo/PTools | Pods/SwifterSwift/Sources/SwifterSwift/Shared/EdgeInsetsExtensions.swift | 1 | 6331 | //
// EdgeInsetsExtensions.swift
// SwifterSwift
//
// Created by Guy Kogus on 03/01/2020.
// Copyright © 2020 SwifterSwift
//
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
/// SwifterSwift: EdgeInsets
public typealias EdgeInsets = UIEdgeInsets
#elseif os(macOS)
import Foundation
/// SwifterSwift: EdgeInsets
public typealias EdgeInsets = NSEdgeInsets
public extension NSEdgeInsets {
/// SwifterSwift: An edge insets struct whose top, left, bottom, and right fields are all set to 0.
static let zero = NSEdgeInsets()
}
// swiftlint:disable missing_swifterswift_prefix
extension NSEdgeInsets: Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func == (lhs: NSEdgeInsets, rhs: NSEdgeInsets) -> Bool {
return lhs.top == rhs.top &&
lhs.left == rhs.left &&
lhs.bottom == rhs.bottom &&
lhs.right == rhs.right
}
}
// swiftlint:enable missing_swifterswift_prefix
#endif
#if os(iOS) || os(tvOS) || os(watchOS) || os(macOS)
// MARK: - Properties
public extension EdgeInsets {
/// SwifterSwift: Return the vertical insets. The vertical insets is composed by top + bottom.
///
var vertical: CGFloat {
// Source: https://github.com/MessageKit/MessageKit/blob/master/Sources/SwifterSwift/EdgeInsets%2BExtensions.swift
return top + bottom
}
/// SwifterSwift: Return the horizontal insets. The horizontal insets is composed by left + right.
///
var horizontal: CGFloat {
// Source: https://github.com/MessageKit/MessageKit/blob/master/Sources/SwifterSwift/EdgeInsets%2BExtensions.swift
return left + right
}
}
// MARK: - Methods
public extension EdgeInsets {
/// SwifterSwift: Creates an `EdgeInsets` with the inset value applied to all (top, bottom, right, left)
///
/// - Parameter inset: Inset to be applied in all the edges.
init(inset: CGFloat) {
self.init(top: inset, left: inset, bottom: inset, right: inset)
}
/// SwifterSwift: Creates an `EdgeInsets` with the horizontal value equally divided and applied to right and left.
/// And the vertical value equally divided and applied to top and bottom.
///
///
/// - Parameter horizontal: Inset to be applied to right and left.
/// - Parameter vertical: Inset to be applied to top and bottom.
init(horizontal: CGFloat, vertical: CGFloat) {
self.init(top: vertical / 2, left: horizontal / 2, bottom: vertical / 2, right: horizontal / 2)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and top offset.
///
/// - Parameters:
/// - top: Offset to be applied in to the top edge.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(top: CGFloat) -> EdgeInsets {
return EdgeInsets(top: self.top + top, left: left, bottom: bottom, right: right)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and left offset.
///
/// - Parameters:
/// - left: Offset to be applied in to the left edge.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(left: CGFloat) -> EdgeInsets {
return EdgeInsets(top: top, left: self.left + left, bottom: bottom, right: right)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and bottom offset.
///
/// - Parameters:
/// - bottom: Offset to be applied in to the bottom edge.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(bottom: CGFloat) -> EdgeInsets {
return EdgeInsets(top: top, left: left, bottom: self.bottom + bottom, right: right)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and right offset.
///
/// - Parameters:
/// - right: Offset to be applied in to the right edge.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(right: CGFloat) -> EdgeInsets {
return EdgeInsets(top: top, left: left, bottom: bottom, right: self.right + right)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and horizontal value equally divided and applied to right offset and left offset.
///
/// - Parameters:
/// - horizontal: Offset to be applied to right and left.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(horizontal: CGFloat) -> EdgeInsets {
return EdgeInsets(top: top, left: left + horizontal / 2, bottom: bottom, right: right + horizontal / 2)
}
/// SwifterSwift: Creates an `EdgeInsets` based on current value and vertical value equally divided and applied to top and bottom.
///
/// - Parameters:
/// - vertical: Offset to be applied to top and bottom.
/// - Returns: EdgeInsets offset with given offset.
func insetBy(vertical: CGFloat) -> EdgeInsets {
return EdgeInsets(top: top + vertical / 2, left: left, bottom: bottom + vertical / 2, right: right)
}
}
// MARK: - Operators
public extension EdgeInsets {
/// SwifterSwift: Add all the properties of two `EdgeInsets` to create their addition.
///
/// - Parameters:
/// - lhs: The left-hand expression
/// - rhs: The right-hand expression
/// - Returns: A new `EdgeInsets` instance where the values of `lhs` and `rhs` are added together.
static func + (_ lhs: EdgeInsets, _ rhs: EdgeInsets) -> EdgeInsets {
return EdgeInsets(top: lhs.top + rhs.top,
left: lhs.left + rhs.left,
bottom: lhs.bottom + rhs.bottom,
right: lhs.right + rhs.right)
}
/// SwifterSwift: Add all the properties of two `EdgeInsets` to the left-hand instance.
///
/// - Parameters:
/// - lhs: The left-hand expression to be mutated
/// - rhs: The right-hand expression
static func += (_ lhs: inout EdgeInsets, _ rhs: EdgeInsets) {
lhs.top += rhs.top
lhs.left += rhs.left
lhs.bottom += rhs.bottom
lhs.right += rhs.right
}
}
#endif
| mit | c1e80b673128ee904285cafb10543185 | 36.904192 | 150 | 0.639179 | 4.271255 | false | false | false | false |
IngmarStein/swift | stdlib/public/SDK/Intents/Intents.swift | 2 | 592 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// IMPORTANT: This file is required by the build system. Don't remove it.
| apache-2.0 | 826df12897136ebda36f533c82c94e4f | 44.538462 | 80 | 0.538851 | 5.333333 | false | false | false | false |
bryzinski/skype-ios-app-sdk-samples | BankingAppSwift/BankingAppSwift/ChatTableViewController.swift | 1 | 3568 | //+----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Module name: ChatTableViewController.swift
//----------------------------------------------------------------
import UIKit
/**
* Enum to identify type of chat source.
* They can be status message, chat from self, or chat from others
*/
enum ChatSource : Int {
case status
case mySelf
case participant
}
class ChatMessage: NSObject {
var chatDisplayName: String = ""
var chatMessage: String = ""
var chatSource: ChatSource?
}
let ParticipantCellIdentifier: String = "participantCell"
let SelfCellIdentifier: String = "selfCell"
let StatusCellIdentifier: String = "statusCell"
/**
* Handles UI of chat table
*/
class ChatTableViewController: UITableViewController {
var myDataSource:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
self.addStatus("Waiting for an agent")
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 160.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - ACTIONS
// Add a status type message
func addStatus(_ message: String) {
let newMessage: ChatMessage = ChatMessage()
newMessage.chatMessage = message
newMessage.chatSource = .status
self.myDataSource.add(newMessage)
self.updateTable()
}
// Add a chat message
func addMessage(_ message: String, from name: String, origin source: ChatSource) {
let newMessage: ChatMessage = ChatMessage()
newMessage.chatDisplayName = name
newMessage.chatMessage = message
newMessage.chatSource = source
self.myDataSource.add(newMessage)
self.updateTable()
}
func updateTable() {
self.tableView.reloadData()
let row: IndexPath = IndexPath(row: self.myDataSource.count - 1, section: 0)
self.tableView.scrollToRow(at: row, at: .top, animated: true)
}
// MARK: - TABLE VIEW DATA SOURCE
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myDataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let chatMessage: ChatMessage = self.myDataSource[indexPath.row] as! ChatMessage
var cell: UITableViewCell
switch (chatMessage.chatSource!) {
case .status:
cell = tableView.dequeueReusableCell(withIdentifier: StatusCellIdentifier, for: indexPath)
case .mySelf:
cell = tableView.dequeueReusableCell(withIdentifier: SelfCellIdentifier, for: indexPath)
case .participant:
cell = tableView.dequeueReusableCell(withIdentifier: ParticipantCellIdentifier, for: indexPath)
}
self.setUpCell(cell, withChatMessage: chatMessage)
return cell
}
func setUpCell(_ cell: UITableViewCell, withChatMessage message: ChatMessage) {
if message.chatSource == .status {
cell.textLabel?.text = message.chatMessage
}
else {
((cell as! ChatCell)).nameLabel.text = message.chatDisplayName
((cell as! ChatCell)).messageLabel.text = message.chatMessage
}
}
}
| mit | 90160b4c8cc484124081b1e52b8bd4c8 | 30.857143 | 109 | 0.633408 | 5.301634 | false | false | false | false |
TimurBK/SwiftSampleProject | Pods/RealmSwift/RealmSwift/SortDescriptor.swift | 2 | 8302 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
#if swift(>=3.0)
/**
A `SortDescriptor` stores a key path and a sort order for use with `sorted(sortDescriptors:)`. It is similar to
`NSSortDescriptor`, but supports only the subset of functionality which can be efficiently run by Realm's query engine.
*/
public struct SortDescriptor {
// MARK: Properties
/// The key path which the sort descriptor orders results by.
public let keyPath: String
/// Whether this descriptor sorts in ascending or descending order.
public let ascending: Bool
/// Converts the receiver to an `RLMSortDescriptor`.
internal var rlmSortDescriptorValue: RLMSortDescriptor {
return RLMSortDescriptor(keyPath: keyPath, ascending: ascending)
}
// MARK: Initializers
/**
Creates a sort descriptor with the given key path and sort order values.
- parameter keyPath: The key path which the sort descriptor orders results by.
- parameter ascending: Whether the descriptor sorts in ascending or descending order.
*/
public init(keyPath: String, ascending: Bool = true) {
self.keyPath = keyPath
self.ascending = ascending
}
/**
Creates a sort descriptor with the given property and sort order values.
- parameter property: The property which the sort descriptor orders results by.
- parameter ascending: Whether the descriptor sorts in ascending or descending order.
*/
@available(*, deprecated, renamed: "init(keyPath:ascending:)")
public init(property: String, ascending: Bool = true) {
self.init(keyPath: property, ascending: ascending)
}
// MARK: Functions
/// Returns a copy of the sort descriptor with the sort order reversed.
public func reversed() -> SortDescriptor {
return SortDescriptor(keyPath: keyPath, ascending: !ascending)
}
/// The key path which the sort descriptor orders results by.
@available(*, deprecated, renamed: "keyPath")
public var property: String { return keyPath }
}
// MARK: CustomStringConvertible
extension SortDescriptor: CustomStringConvertible {
/// A human-readable description of the sort descriptor.
public var description: String {
let direction = ascending ? "ascending" : "descending"
return "SortDescriptor(keyPath: \(keyPath), direction: \(direction))"
}
}
// MARK: Equatable
extension SortDescriptor: Equatable {
/// Returns whether the two sort descriptors are equal.
public static func == (lhs: SortDescriptor, rhs: SortDescriptor) -> Bool {
// swiftlint:disable:previous valid_docs
return lhs.keyPath == rhs.keyPath &&
lhs.ascending == lhs.ascending
}
}
// MARK: StringLiteralConvertible
extension SortDescriptor: ExpressibleByStringLiteral {
public typealias UnicodeScalarLiteralType = StringLiteralType
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
/**
Creates a `SortDescriptor` out of a Unicode scalar literal.
- parameter unicodeScalarLiteral: Property name literal.
*/
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(keyPath: value)
}
/**
Creates a `SortDescriptor` out of a character literal.
- parameter extendedGraphemeClusterLiteral: Property name literal.
*/
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(keyPath: value)
}
/**
Creates a `SortDescriptor` out of a string literal.
- parameter stringLiteral: Property name literal.
*/
public init(stringLiteral value: StringLiteralType) {
self.init(keyPath: value)
}
}
#else
/**
A `SortDescriptor` stores a property name and a sort order for use with
`sorted(sortDescriptors:)`. It is similar to `NSSortDescriptor`, but supports
only the subset of functionality which can be efficiently run by Realm's query
engine.
*/
public struct SortDescriptor {
// MARK: Properties
/// The key path which the sort descriptor orders results by.
public let keyPath: String
/// Whether the descriptor sorts in ascending or descending order.
public let ascending: Bool
/// Converts the receiver to an `RLMSortDescriptor`
internal var rlmSortDescriptorValue: RLMSortDescriptor {
return RLMSortDescriptor(keyPath: keyPath, ascending: ascending)
}
// MARK: Initializers
/**
Creates a sort descriptor with the given key path and sort order values.
- parameter keyPath: The key path which the sort descriptor orders results by.
- parameter ascending: Whether the descriptor sorts in ascending or descending order.
*/
public init(keyPath: String, ascending: Bool = true) {
self.keyPath = keyPath
self.ascending = ascending
}
/**
Creates a sort descriptor with the given key path and sort order values.
- parameter property: The property which the sort descriptor orders results by.
- parameter ascending: Whether the descriptor sorts in ascending or descending order.
*/
@available(*, deprecated, renamed="init(keyPath:ascending:)")
public init(property: String, ascending: Bool = true) {
self.init(keyPath: property, ascending: ascending)
}
// MARK: Functions
/// Returns a copy of the sort descriptor with the sort order reversed.
public func reversed() -> SortDescriptor {
return SortDescriptor(keyPath: keyPath, ascending: !ascending)
}
/// The key which the sort descriptor orders results by.
@available(*, deprecated, renamed="keyPath")
public var property: String { return keyPath }
}
// MARK: CustomStringConvertible
extension SortDescriptor: CustomStringConvertible {
/// Returns a human-readable description of the sort descriptor.
public var description: String {
let direction = ascending ? "ascending" : "descending"
return "SortDescriptor(keyPath: \(keyPath), direction: \(direction))"
}
}
// MARK: Equatable
extension SortDescriptor: Equatable {}
/// Returns whether the two sort descriptors are equal.
public func == (lhs: SortDescriptor, rhs: SortDescriptor) -> Bool {
// swiftlint:disable:previous valid_docs
return lhs.keyPath == rhs.keyPath &&
lhs.ascending == lhs.ascending
}
// MARK: StringLiteralConvertible
extension SortDescriptor: StringLiteralConvertible {
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias UnicodeScalarLiteralType = StringLiteralType
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
/**
Creates a `SortDescriptor` from a `UnicodeScalarLiteralType`.
- parameter unicodeScalarLiteral: Property name literal.
*/
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(keyPath: value)
}
/**
Creates a `SortDescriptor` from an `ExtendedGraphemeClusterLiteralType`.
- parameter extendedGraphemeClusterLiteral: Property name literal.
*/
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(keyPath: value)
}
/**
Creates a `SortDescriptor` from a `StringLiteralType`.
- parameter stringLiteral: Property name literal.
*/
public init(stringLiteral value: StringLiteralType) {
self.init(keyPath: value)
}
}
#endif
| mit | 4a048ecb25f37dc9786aedb5919655cd | 31.814229 | 120 | 0.6967 | 5.271111 | false | false | false | false |
tqtifnypmb/SwiftyImage | Examples/Eamples/Eamples/ViewController.swift | 2 | 1871 | //
// ViewController.swift
// Framenderer
//
// Created by tqtifnypmb on 08/12/2016.
// Copyright © 2016 tqitfnypmb. All rights reserved.
//
import UIKit
import CoreImage
import Framenderer
class ViewController: UIViewController {
@IBOutlet weak var originImageView: UIImageView!
@IBOutlet weak var processedImageView: UIImageView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let origin = UIImage(named: "lena")
// let blend = UIImage(named: "lena")
//
// let context = CIContext()
//
// let filter = CIFilter(name: "CIAdditionCompositing")!
//filter.setValue(CIImage(cgImage: origin!.cgImage!), forKey: kCIInputImageKey)
// filter.setValue(2, forKey: kCIInputAngleKey)
//filter.setValue(CIImage(cgImage: blend!.cgImage!), forKey: kCIInputBackgroundImageKey)
//let result = filter.outputImage!
//let cgImage = context.createCGImage(result, from: result.extent)
//originImageView.image = UIImage(cgImage: cgImage!)
originImageView.image = origin
let canva = ImageCanvas(image: origin!.cgImage!)
let canny = CannyFilter(lowerThresh: 0.0, upperThresh: 1.0)
canva.filters = [PassthroughFilter(), HistogramFilter()]
// canva.filters = canny.expand()
// canva.filters.append(PassthroughFilter())
canva.processAsync {[weak self] result, error in
if let error = error {
print(glGetError())
print(error.localizedDescription)
} else {
let processed = UIImage(cgImage: result!)
DispatchQueue.main.async {
self?.processedImageView.image = processed
}
}
}
}
}
| mit | 616a5728357edde7e81f728c99653799 | 31.807018 | 96 | 0.603209 | 4.734177 | false | false | false | false |
MaTriXy/androidtool-mac | AndroidTool/scriptsPopoverViewController.swift | 1 | 3443 | //
// scriptsPopoverViewController.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/26/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
@objc protocol UserScriptDelegate : class {
func userScriptStarted()
func userScriptEnded()
func userScriptWantsSerial() -> String
}
class scriptsPopoverViewController: NSViewController {
let buttonHeight:CGFloat = 30
// accepted answer here http://stackoverflow.com/questions/26180268/interface-builder-iboutlet-and-protocols-for-delegate-and-datasource-in-swift
@IBOutlet var delegate : UserScriptDelegate!
let fileM = NSFileManager.defaultManager()
func setup(){
let folder = Util().getSupportFolderScriptPath()
let allScripts = Util().getFilesInScriptFolder(folder)
if allScripts?.count > 0 {
addScriptsToView(allScripts!, view: self.view)
}
}
func addScriptsToView(scripts:[String], view:NSView){
var i:CGFloat = 1
view.frame.size.height = CGFloat(scripts.count) * (buttonHeight+3) + buttonHeight
let folderButton = NSButton(frame: NSRect(x: 10.0, y: 3,
width: view.bounds.width-15.0,
height: buttonHeight))
folderButton.image = NSImage(named: "revealFolder")
folderButton.bordered = false
folderButton.action = "revealScriptFolderClicked:"
folderButton.target = self
view.addSubview(folderButton)
for script in scripts {
let scriptButton = NSButton(frame: NSRect(x: 10.0, y: (i*buttonHeight+3),
width: view.bounds.width-15.0,
height: buttonHeight))
let friendlyScriptName = script.stringByReplacingOccurrencesOfString(".sh", withString: "")
scriptButton.title = friendlyScriptName
if #available(OSX 10.10.3, *) {
scriptButton.setButtonType(NSButtonType.AcceleratorButton)
} else {
// Fallback on earlier versions
}
scriptButton.bezelStyle = NSBezelStyle.RoundedBezelStyle
scriptButton.action = "runScriptClicked:"
scriptButton.target = self
view.addSubview(scriptButton)
i++
}
}
func runScript(scriptPath:String){
delegate.userScriptStarted()
let serial:String = delegate.userScriptWantsSerial()
print("ready to run on \(serial)")
ShellTasker(scriptFile: scriptPath).run(arguments: ["\(serial)"], isUserScript: true) { (output) -> Void in
self.delegate.userScriptEnded()
}
}
func runScriptClicked(sender:NSButton){
let scriptName = "\(sender.title).sh"
let scriptPath = "\(Util().getSupportFolderScriptPath())/\(scriptName)"
print("ready to run \(scriptPath)")
runScript(scriptPath)
}
func revealScriptFolderClicked(sender:NSButton) {
Util().revealScriptsFolder()
}
override func viewDidLoad() {
if #available(OSX 10.10, *) {
super.viewDidLoad()
} else {
// Fallback on earlier versions
}
// Do view setup here.
}
override func awakeFromNib() {
// println("awake from nib-style")
setup()
}
}
| apache-2.0 | ca2381d0c92775bdb5edee0f239fa610 | 31.17757 | 149 | 0.602963 | 4.883688 | false | false | false | false |
IBM-Swift/Swift-cfenv | Sources/CloudFoundryEnv/CollectionUtils.swift | 1 | 1150 | /**
* Copyright IBM Corporation 2017
*
* 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.
**/
extension Array
{
func toDictionary<K, V>(converter: (Element) -> (K, V)) -> Dictionary<K, V> {
var dict = Dictionary<K,V>()
self.forEach({ item in
let (k,v) = converter(item)
dict[k] = v
})
return dict
}
}
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
func filterWithRegex(regex: String) -> Dictionary<Key, Value> {
return self.filter({
let k: String = String(describing: $0.key)
return (k.range(of: regex, options: .regularExpression) != nil)
}).toDictionary(converter: {$0})
}
}
| apache-2.0 | 9ff66ec54afe588f7fa0b43d6ed52a1e | 30.944444 | 79 | 0.693913 | 3.820598 | false | false | false | false |
zhuyunfeng1224/XHGuideViewController | XHGuideViewControllerSample/AppDelegate.swift | 1 | 3754 | //
// AppDelegate.swift
// XHGuideViewController
//
// Created by echo on 16/7/26.
// Copyright © 2016年 羲和. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let vc1: XHGuideContentViewController = XHGuideContentViewController(imageNameOrUrl: "1.jpg", imageType: .system, buttonTitle: nil)
vc1.imageView.contentMode = .scaleAspectFit
vc1.tapAtIndex = {(index: Int) in
print("tap at index:\(index)")
}
let vc2: XHGuideContentViewController = XHGuideContentViewController(imageNameOrUrl: "2.jpg", imageType: .system, buttonTitle: nil)
vc2.imageView.contentMode = .scaleAspectFit
vc2.tapAtIndex = {(index: Int) in
print("tap at index:\(index)")
}
let vc3: XHGuideContentViewController = XHGuideContentViewController(imageNameOrUrl: "3.jpg", imageType: .system, buttonTitle: nil)
vc3.imageView.contentMode = .scaleAspectFit
vc3.tapAtIndex = {(index: Int) in
print("tap at index:\(index)")
}
let guideVC: XHGuideViewController = XHGuideViewController()
guideVC.viewControllers = [vc1, vc2, vc3]
guideVC.autoClose = true
guideVC.showSkipButton = true
guideVC.backgroundImageView.image = UIImage(named: "bg.jpg")
guideVC.backgroundImageView.alpha = 0.3
guideVC.showTime = 30
guideVC.actionSkip = {
let vc: ViewController = ViewController()
vc.modalTransitionStyle = .crossDissolve
guideVC.present(vc, animated: true, completion: nil)
}
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
self.window?.rootViewController = guideVC
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 32b794ec0a7a3dab734b53704ae94bda | 46.43038 | 285 | 0.703763 | 5.284908 | false | false | false | false |
tonilopezmr/Learning-Swift | My First IOS App/My First IOS App/ServiceLocator.swift | 1 | 2498 | //
// ServiceLocator.swift
// My First IOS App
//
// Created by Antonio López Marín on 28/01/16.
// Copyright © 2016 Antonio López Marín. All rights reserved.
//
import Foundation
import UIKit
class ServiceLocator {
private func provideDataSource() -> SQLiteDataSource{
return SQLiteDataSource()
}
private func provideSubjectRepository() -> SubjectRespositoryProtocol {
return SubjectRepository(datasource: provideDataSource())
}
private func provideUseCases() -> UseCase {
let repository = provideSubjectRepository()
let getSubjectList = GetSubjects(repository: repository)
let getSubject = GetSubject(repository: repository)
let createSubject = CreateSubject(repository: repository)
let deleteSubject = DeleteSubject(repository: repository)
let updateSubject = UpdateSubject(repository: repository)
return UseCase(getSubjectList: getSubjectList, getSubject: getSubject, createSubject: createSubject, deleteSubject: deleteSubject, updateSubject: updateSubject)
}
private func provideSubjectPresenter(ui: SubjectUI) -> SubjectPresenter {
return SubjectPresenter(ui: ui, useCase: provideUseCases())
}
private func provideSubjectDataSource() -> SubjectTableViewDataSource {
return SubjectTableViewDataSource()
}
private func provideStoryBoard() -> UIStoryboard{
return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
}
func provideRootViewController() -> UIViewController{
let uiStoryBoard = provideStoryBoard()
let navigationController = uiStoryBoard.instantiateInitialViewController() as! UINavigationController
navigationController.viewControllers = [provideSubjectController()]
return navigationController
}
func provideSubjectController() -> UIViewController {
let uiStoryBoard = provideStoryBoard()
let subjectViewController: ViewController = uiStoryBoard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
let presenter = provideSubjectPresenter(subjectViewController)
let dataSource = provideSubjectDataSource()
subjectViewController.presenter = presenter
subjectViewController.dataSource = dataSource
subjectViewController.delegate = SubjectTableViewNavigationDelegate(dataSource: dataSource, presenter: presenter)
return subjectViewController
}
} | apache-2.0 | b1e94324c656cd9cf3a7c0440c6f3705 | 39.225806 | 168 | 0.731649 | 6.140394 | false | false | false | false |
nothing2lose/YSLTransitionAnimator | YSLTransitionAnimatorSwift/UIViewController+YSLTransitionSwift.swift | 1 | 7919 | //
// UIViewController+YSLTransition.swift
// YSLTransitionAnimatorDemo
//
// Created by jeju on 2015. 9. 18..
// Copyright © 2015년 h.yamaguchi. All rights reserved.
//
import Foundation
import UIKit
var AOPopTranstionHandle: UInt8 = 0
var AOScrollViewHandle: UInt8 = 0
var AOToViewControllerImagePointYHandle: UInt8 = 0
var AOCancelAnimationPointYHandle: UInt8 = 0
var AOAnimationDuration: UInt8 = 0
var isScrollView = false
extension UIViewController: UINavigationControllerDelegate {
// MARK:- Properties
var interactivePopTransition: UIPercentDrivenInteractiveTransition? {
get {
return objc_getAssociatedObject(self, &AOPopTranstionHandle) as? UIPercentDrivenInteractiveTransition
}
set {
objc_setAssociatedObject(self, &AOPopTranstionHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var yslScrollView: UIScrollView? {
get {
return objc_getAssociatedObject(self, &AOScrollViewHandle) as! UIScrollView?
}
set {
objc_setAssociatedObject(self, &AOScrollViewHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var toViewControllerImagePointY: NSNumber? {
get {
return objc_getAssociatedObject(self, &AOToViewControllerImagePointYHandle) as! NSNumber?
}
set {
objc_setAssociatedObject(self, &AOToViewControllerImagePointYHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var cancelAnimationPointY: NSNumber? {
get {
return objc_getAssociatedObject(self, &AOCancelAnimationPointYHandle) as! NSNumber?
}
set {
objc_setAssociatedObject(self, &AOCancelAnimationPointYHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var animationDuration: NSNumber? {
get {
return objc_getAssociatedObject(self , &AOAnimationDuration) as! NSNumber?
}
set {
objc_setAssociatedObject(self, &AOAnimationDuration, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK:- P6ublic methods
func ysl_pushTransitionAnimationWithToViewControllerImagePointY(toViewControllerImagePointY: CGFloat, animationDuration: CGFloat) -> Void{
self.toViewControllerImagePointY = NSNumber(float: Float(toViewControllerImagePointY))
self.animationDuration = NSNumber(float: Float(animationDuration))
}
func ysl_popTransitionAnimationWithCurrentScrollView(scrollView: UIScrollView?, cancelAnimationPointY: CGFloat, animationDuration: CGFloat, isInteractiveTransition: Bool) -> Void {
if let sc = scrollView {
self.yslScrollView = sc
isScrollView = true
}
self.cancelAnimationPointY = NSNumber(float: Float(cancelAnimationPointY))
self.animationDuration = NSNumber(float: Float(animationDuration))
if true == isInteractiveTransition {
let popRecognizer: UIScreenEdgePanGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: Selector("handlePopRecognizer:"))
popRecognizer.edges = UIRectEdge.Left
self.view.addGestureRecognizer(popRecognizer)
}
}
func ysl_addTransitionDelegate(viewController: UIViewController?) {
self.navigationController?.delegate = self as UINavigationControllerDelegate
if let vc = viewController {
if vc.isKindOfClass(UITableViewController) {
let viewController = vc as! UITableViewController
viewController.clearsSelectionOnViewWillAppear = false
} else if vc.isKindOfClass(UICollectionViewController) {
let viewController = vc as! UICollectionViewController
viewController.clearsSelectionOnViewWillAppear = false
}
}
}
func ysl_removeTransitionDelegate() {
if let delegate = self.navigationController?.delegate where delegate === self {
self.navigationController?.delegate = nil
}
}
// MARK:- UINavigationControllerDelegate
public func navigationController(navigationController: UINavigationController, interactionControllerForAnimationController animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if nil == self.interactivePopTransition {
return nil
}
return self.interactivePopTransition
}
public func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if let _ = fromVC as? YSLTransitionAnimatorDataSource, _ = toVC as? YSLTransitionAnimatorDataSource {
if operation == UINavigationControllerOperation.Push {
if operation != UINavigationControllerOperation.Push { return nil }
let animator: YSLTransitionAnimator = YSLTransitionAnimator()
animator.isForward = (operation == UINavigationControllerOperation.Push)
if let pointY = self.toViewControllerImagePointY {
animator.toViewControllerImagePointY = CGFloat(pointY)
}
if let animDuration = self.animationDuration {
animator.animationDuration = animDuration.doubleValue as NSTimeInterval
}
return animator
} else if (operation == UINavigationControllerOperation.Pop) {
if operation != UINavigationControllerOperation.Pop { return nil }
if let cancelAnimPointY = self.cancelAnimationPointY, scrollView = self.yslScrollView where cancelAnimPointY.floatValue != 0 && true == isScrollView {
if Double(scrollView.contentOffset.y) > cancelAnimPointY.doubleValue {
return nil
}
}
let animator: YSLTransitionAnimator = YSLTransitionAnimator()
animator.isForward = (operation == UINavigationControllerOperation.Push)
if let animDuration = self.animationDuration {
animator.animationDuration = animDuration.doubleValue as NSTimeInterval
}
return animator
} else {
return nil
}
} else {
return nil
}
}
// MARK:- UIGestureRecognizer handlers
func handlePopRecognizer(recognizer: UIScreenEdgePanGestureRecognizer) {
var progress: CGFloat = recognizer .translationInView(self.view).x / (self.view.bounds.size.width)
progress = min(1.0, max(0.0, progress))
switch recognizer.state {
case UIGestureRecognizerState.Began:
self.interactivePopTransition = UIPercentDrivenInteractiveTransition()
self.navigationController?.popViewControllerAnimated(true)
break
case UIGestureRecognizerState.Changed:
self.interactivePopTransition?.updateInteractiveTransition(progress)
break
case UIGestureRecognizerState.Ended, UIGestureRecognizerState.Cancelled:
if progress > 0.5 {
self.interactivePopTransition?.finishInteractiveTransition()
} else {
self.interactivePopTransition?.cancelInteractiveTransition()
}
self.interactivePopTransition = nil
break
default: ()
}
}
} | mit | 21b6d8ec079469b678178f447080755d | 43.22905 | 288 | 0.663972 | 6.348035 | false | false | false | false |
huangboju/HYAlertController | Carthage/Checkouts/SnapKit/Source/ConstraintItem.swift | 1 | 2055 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintItem: Equatable {
internal weak var target: AnyObject?
internal let attributes: ConstraintAttributes
internal init(target: AnyObject?, attributes: ConstraintAttributes) {
self.target = target
self.attributes = attributes
}
internal var layoutConstraintItem: LayoutConstraintItem? {
return self.target as? LayoutConstraintItem
}
}
public func ==(lhs: ConstraintItem, rhs: ConstraintItem) -> Bool {
// pointer equality
guard lhs !== rhs else {
return true
}
// must both have valid targets and identical attributes
guard let target1 = lhs.target,
let target2 = rhs.target,
target1 === target2 && lhs.attributes == rhs.attributes else {
return false
}
return true
}
| mit | 1716a602ca44375620d428d2ceeff1c1 | 33.830508 | 81 | 0.712409 | 4.526432 | false | false | false | false |
MiniDOM/MiniDOM | Tests/MiniDOMTests/ParserSimpleTests.swift | 1 | 3886 | //
// ParserSimpleTests.swift
// MiniDOM
//
// Copyright 2017-2020 Anodized Software, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
import MiniDOM
import XCTest
class ParserSimpleTests: XCTestCase {
var source: String!
var document: Document!
override func setUp() {
super.setUp()
source = [
"<?xml version=\"1.0\" encoding=\"utf-8\"?>",
"<foo>",
" <!-- This is a comment -->",
" <bar attr1=\"value1\" attr2=\"value2\"/>",
" <?target attr=\"value\"?>",
" <![CDATA[<div>This is some HTML</div>]]>",
" <baz>",
" <fnord>",
" This is some text",
" </fnord>",
" <fnord>",
" This is some more text",
" </fnord>",
" </baz>",
"</foo>"
].joined(separator: "\n")
document = loadXML(string: source)
}
func testTopLevelElement() {
let documentElement = document.documentElement
XCTAssertNotNil(documentElement)
XCTAssertEqual(documentElement?.nodeName, "foo")
XCTAssertEqual(documentElement?.tagName, "foo")
}
func testDocumentElementChildNodes() {
let children = document.documentElement?.children.filter({ $0.nodeType != .text })
XCTAssertNotNil(children)
XCTAssertEqual(children?.isEmpty, false)
XCTAssertEqual(children?.count, 5)
XCTAssertEqual(children?[0].nodeName, "#comment")
XCTAssertEqual(children?[0].nodeValue, " This is a comment ")
XCTAssertEqual(children?[1].nodeName, "bar")
XCTAssertNil(children?[1].nodeValue)
XCTAssertEqual(children?[2].nodeName, "target")
XCTAssertEqual(children?[2].nodeValue, "attr=\"value\"")
XCTAssertEqual(children?[3].nodeName, "#cdata-section")
XCTAssertEqual(children?[3].nodeValue, "<div>This is some HTML</div>")
XCTAssertEqual(children?[4].nodeName, "baz")
XCTAssertNil(children?[4].nodeValue)
let bar = children?[1] as? Element
XCTAssertNotNil(bar)
XCTAssertEqual(bar?.attributes ?? [:], [
"attr1": "value1",
"attr2": "value2"
])
}
func testTwoElementsNamedFnord() {
let fnords = document.elements(withTagName: "fnord")
XCTAssertEqual(fnords.count, 2)
XCTAssertEqual(fnords[0].children.count, 1)
XCTAssertEqual(fnords[0].firstChild?.nodeType, .text)
XCTAssertEqual(fnords[0].firstChild?.nodeValue?.trimmed, "This is some text")
XCTAssertEqual(fnords[1].children.count, 1)
XCTAssertEqual(fnords[1].firstChild?.nodeType, .text)
XCTAssertEqual(fnords[1].firstChild?.nodeValue?.trimmed, "This is some more text")
}
}
| mit | 701ccacc5db88fa5f367b41ad44613e0 | 34.651376 | 90 | 0.629696 | 4.441143 | false | true | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Common/UI/FetchedPlaceholderView.swift | 2 | 1320 | //
// FetchedPlaceholderView.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 28/05/2017.
// Copyright © 2017 Will Baumann. All rights reserved.
//
class FetchedPlaceholderView: UIView {
private let MARGIN: CGFloat = 25
private var placeholderLabel: UILabel!
init(frame: CGRect, title: String) {
super.init(frame: frame)
backgroundColor = UIColor.white
placeholderLabel = UILabel(frame: CGRect.zero)
placeholderLabel.numberOfLines = 0
placeholderLabel.font = UIFont.systemFont(ofSize: 15)
placeholderLabel.textColor = UIColor.black
setTitle(title)
addSubview(placeholderLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setTitle(_ title: String?) {
placeholderLabel.text = title
let sizeBefore = CGSize(width: bounds.width - MARGIN * 2, height: 0)
let size = placeholderLabel.sizeThatFits(sizeBefore)
placeholderLabel.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
placeholderLabel.center = CGPoint(x: bounds.width/2, y: bounds.height/2)
}
override func layoutSubviews() {
setTitle(placeholderLabel.text)
}
}
| agpl-3.0 | e65473cad6fa058bc74f44c3b2427f07 | 29.674419 | 91 | 0.648976 | 4.62807 | false | false | false | false |
loudnate/Loop | Loop/View Controllers/CarbEntryViewController.swift | 1 | 18400 | //
// CarbEntryViewController.swift
// CarbKit
//
// Created by Nathan Racklyeft on 1/15/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import HealthKit
import LoopKit
import LoopKitUI
import LoopCore
import LoopUI
final class CarbEntryViewController: ChartsTableViewController, IdentifiableClass {
var navigationDelegate = CarbEntryNavigationDelegate()
var defaultAbsorptionTimes: CarbStore.DefaultAbsorptionTimes? {
didSet {
if let times = defaultAbsorptionTimes {
orderedAbsorptionTimes = [times.fast, times.medium, times.slow]
}
}
}
fileprivate var orderedAbsorptionTimes = [TimeInterval]()
var preferredUnit = HKUnit.gram()
var maxQuantity = HKQuantity(unit: .gram(), doubleValue: 250)
/// Entry configuration values. Must be set before presenting.
var absorptionTimePickerInterval = TimeInterval(minutes: 30)
var maxAbsorptionTime = TimeInterval(hours: 8)
var maximumDateFutureInterval = TimeInterval(hours: 4)
var glucoseUnit: HKUnit = .milligramsPerDeciliter
var originalCarbEntry: StoredCarbEntry? {
didSet {
if let entry = originalCarbEntry {
quantity = entry.quantity
date = entry.startDate
foodType = entry.foodType
absorptionTime = entry.absorptionTime
absorptionTimeWasEdited = true
usesCustomFoodType = true
shouldBeginEditingQuantity = false
}
}
}
fileprivate var quantity: HKQuantity? {
didSet {
updateContinueButtonEnabled()
}
}
fileprivate var date = Date() {
didSet {
updateContinueButtonEnabled()
}
}
fileprivate var foodType: String? {
didSet {
updateContinueButtonEnabled()
}
}
fileprivate var absorptionTime: TimeInterval? {
didSet {
updateContinueButtonEnabled()
}
}
private var selectedDefaultAbsorptionTimeEmoji: String?
fileprivate var absorptionTimeWasEdited = false
fileprivate var usesCustomFoodType = false
private var shouldBeginEditingQuantity = true
private var shouldBeginEditingFoodType = false
var updatedCarbEntry: NewCarbEntry? {
if let quantity = quantity,
let absorptionTime = absorptionTime ?? defaultAbsorptionTimes?.medium
{
if let o = originalCarbEntry, o.quantity == quantity && o.startDate == date && o.foodType == foodType && o.absorptionTime == absorptionTime {
return nil // No changes were made
}
return NewCarbEntry(
quantity: quantity,
startDate: date,
foodType: foodType,
absorptionTime: absorptionTime,
externalID: originalCarbEntry?.externalID
)
} else {
return nil
}
}
private var isSampleEditable: Bool {
return originalCarbEntry?.createdByCurrentApp != false
}
private(set) lazy var footerView: SetupTableFooterView = {
let footerView = SetupTableFooterView(frame: .zero)
footerView.primaryButton.addTarget(self, action: #selector(continueButtonPressed), for: .touchUpInside)
footerView.primaryButton.isEnabled = quantity != nil && quantity!.doubleValue(for: preferredUnit) > 0
return footerView
}()
private var lastContentHeight: CGFloat = 0
override func createChartsManager() -> ChartsManager {
// Consider including a chart on this screen to demonstrate how absorption time affects prediction
ChartsManager(colors: .default, settings: .default, charts: [], traitCollection: traitCollection)
}
override func glucoseUnitDidChange() {
// Consider including a chart on this screen to demonstrate how absorption time affects prediction
}
override func viewDidLoad() {
super.viewDidLoad()
// This gets rid of the empty space at the top.
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 0.01))
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
tableView.register(DateAndDurationTableViewCell.nib(), forCellReuseIdentifier: DateAndDurationTableViewCell.className)
if originalCarbEntry != nil {
title = NSLocalizedString("carb-entry-title-edit", value: "Edit Carb Entry", comment: "The title of the view controller to edit an existing carb entry")
} else {
title = NSLocalizedString("carb-entry-title-add", value: "Add Carb Entry", comment: "The title of the view controller to create a new carb entry")
}
navigationItem.rightBarButtonItem = UIBarButtonItem(title: footerView.primaryButton.titleLabel?.text, style: .plain, target: self, action: #selector(continueButtonPressed))
navigationItem.rightBarButtonItem?.isEnabled = false
// Sets text for back button on bolus screen
navigationItem.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Carb Entry", comment: "Back button text for bolus screen to return to carb entry screen"), style: .plain, target: nil, action: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if shouldBeginEditingQuantity, let cell = tableView.cellForRow(at: IndexPath(row: Row.value.rawValue, section: 0)) as? DecimalTextFieldTableViewCell {
shouldBeginEditingQuantity = false
cell.textField.becomeFirstResponder()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Reposition footer view if necessary
if tableView.contentSize.height != lastContentHeight {
lastContentHeight = tableView.contentSize.height
tableView.tableFooterView = nil
let footerSize = footerView.systemLayoutSizeFitting(CGSize(width: tableView.frame.size.width, height: UIView.layoutFittingCompressedSize.height))
footerView.frame.size = footerSize
tableView.tableFooterView = footerView
}
}
private var foodKeyboard: EmojiInputController!
// MARK: - Table view data source
fileprivate enum Row: Int {
case value
case date
case foodType
case absorptionTime
static let count = 4
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Row.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch Row(rawValue: indexPath.row)! {
case .value:
let cell = tableView.dequeueReusableCell(withIdentifier: DecimalTextFieldTableViewCell.className) as! DecimalTextFieldTableViewCell
if let quantity = quantity {
cell.number = NSNumber(value: quantity.doubleValue(for: preferredUnit))
}
cell.textField.isEnabled = isSampleEditable
cell.unitLabel?.text = String(describing: preferredUnit)
cell.delegate = self
return cell
case .date:
let cell = tableView.dequeueReusableCell(withIdentifier: DateAndDurationTableViewCell.className) as! DateAndDurationTableViewCell
cell.titleLabel.text = NSLocalizedString("Date", comment: "Title of the carb entry date picker cell")
cell.datePicker.isEnabled = isSampleEditable
cell.datePicker.datePickerMode = .dateAndTime
cell.datePicker.maximumDate = Date(timeIntervalSinceNow: maximumDateFutureInterval)
cell.datePicker.minuteInterval = 1
cell.date = date
cell.delegate = self
return cell
case .foodType:
if usesCustomFoodType {
let cell = tableView.dequeueReusableCell(withIdentifier: TextFieldTableViewCell.className, for: indexPath) as! TextFieldTableViewCell
cell.textField.text = foodType
cell.delegate = self
if let textField = cell.textField as? CustomInputTextField {
if foodKeyboard == nil {
foodKeyboard = CarbAbsorptionInputController()
foodKeyboard.delegate = self
}
textField.customInput = foodKeyboard
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: FoodTypeShortcutCell.className, for: indexPath) as! FoodTypeShortcutCell
if absorptionTime == nil {
cell.selectionState = .medium
}
selectedDefaultAbsorptionTimeEmoji = cell.selectedEmoji
cell.delegate = self
return cell
}
case .absorptionTime:
let cell = tableView.dequeueReusableCell(withIdentifier: DateAndDurationTableViewCell.className) as! DateAndDurationTableViewCell
cell.titleLabel.text = NSLocalizedString("Absorption Time", comment: "Title of the carb entry absorption time cell")
cell.datePicker.isEnabled = isSampleEditable
cell.datePicker.datePickerMode = .countDownTimer
cell.datePicker.minuteInterval = Int(absorptionTimePickerInterval.minutes)
if let duration = absorptionTime ?? defaultAbsorptionTimes?.medium {
cell.duration = duration
}
cell.maximumDuration = maxAbsorptionTime
cell.delegate = self
return cell
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
switch Row(rawValue: indexPath.row)! {
case .value, .date:
break
case .foodType:
if usesCustomFoodType, shouldBeginEditingFoodType, let cell = cell as? TextFieldTableViewCell {
shouldBeginEditingFoodType = false
cell.textField.becomeFirstResponder()
}
case .absorptionTime:
break
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return NSLocalizedString("Choose a longer absorption time for larger meals, or those containing fats and proteins. This is only guidance to the algorithm and need not be exact.", comment: "Carb entry section footer text explaining absorption time")
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
tableView.endEditing(false)
tableView.beginUpdates()
hideDatePickerCells(excluding: indexPath)
return indexPath
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch tableView.cellForRow(at: indexPath) {
case is FoodTypeShortcutCell:
usesCustomFoodType = true
shouldBeginEditingFoodType = true
tableView.reloadRows(at: [IndexPath(row: Row.foodType.rawValue, section: 0)], with: .none)
default:
break
}
tableView.endUpdates()
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Navigation
override func restoreUserActivityState(_ activity: NSUserActivity) {
if let entry = activity.newCarbEntry {
quantity = entry.quantity
date = entry.startDate
if let foodType = entry.foodType {
self.foodType = foodType
usesCustomFoodType = true
}
if let absorptionTime = entry.absorptionTime {
self.absorptionTime = absorptionTime
absorptionTimeWasEdited = true
}
}
}
@objc private func continueButtonPressed() {
tableView.endEditing(true)
guard validateInput(), let updatedEntry = updatedCarbEntry else {
return
}
let bolusVC = BolusViewController.instance()
bolusVC.deviceManager = deviceManager
bolusVC.glucoseUnit = glucoseUnit
if let originalEntry = originalCarbEntry {
bolusVC.configuration = .updatedCarbEntry(from: originalEntry, to: updatedEntry)
} else {
bolusVC.configuration = .newCarbEntry(updatedEntry)
}
bolusVC.selectedDefaultAbsorptionTimeEmoji = selectedDefaultAbsorptionTimeEmoji
show(bolusVC, sender: footerView.primaryButton)
}
private func validateInput() -> Bool {
guard let absorptionTime = absorptionTime ?? defaultAbsorptionTimes?.medium else {
return false
}
guard absorptionTime <= maxAbsorptionTime else {
navigationDelegate.showAbsorptionTimeValidationWarning(for: self, maxAbsorptionTime: maxAbsorptionTime)
return false
}
guard let quantity = quantity, quantity.doubleValue(for: preferredUnit) > 0 else { return false }
guard quantity.compare(maxQuantity) != .orderedDescending else {
navigationDelegate.showMaxQuantityValidationWarning(for: self, maxQuantityGrams: maxQuantity.doubleValue(for: .gram()))
return false
}
return true
}
private func updateContinueButtonEnabled() {
let hasValidQuantity = quantity != nil && quantity!.doubleValue(for: preferredUnit) > 0
let haveChangesBeenMade = updatedCarbEntry != nil
let readyToContinue = hasValidQuantity && haveChangesBeenMade
footerView.primaryButton.isEnabled = readyToContinue
navigationItem.rightBarButtonItem?.isEnabled = readyToContinue
}
}
extension CarbEntryViewController: TextFieldTableViewCellDelegate {
func textFieldTableViewCellDidBeginEditing(_ cell: TextFieldTableViewCell) {
// Collapse any date picker cells to save space
tableView.beginUpdates()
hideDatePickerCells()
tableView.endUpdates()
}
func textFieldTableViewCellDidEndEditing(_ cell: TextFieldTableViewCell) {
guard let row = tableView.indexPath(for: cell)?.row else { return }
switch Row(rawValue: row) {
case .value?:
if let cell = cell as? DecimalTextFieldTableViewCell, let number = cell.number {
quantity = HKQuantity(unit: preferredUnit, doubleValue: number.doubleValue)
} else {
quantity = nil
}
case .foodType?:
foodType = cell.textField.text
default:
break
}
}
func textFieldTableViewCellDidChangeEditing(_ cell: TextFieldTableViewCell) {
guard let row = tableView.indexPath(for: cell)?.row else { return }
switch Row(rawValue: row) {
case .value?:
if let cell = cell as? DecimalTextFieldTableViewCell, let number = cell.number {
quantity = HKQuantity(unit: preferredUnit, doubleValue: number.doubleValue)
} else {
quantity = nil
}
default:
break
}
}
}
extension CarbEntryViewController: DatePickerTableViewCellDelegate {
func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
guard let row = tableView.indexPath(for: cell)?.row else { return }
switch Row(rawValue: row) {
case .date?:
date = cell.date
case .absorptionTime?:
absorptionTime = cell.duration
absorptionTimeWasEdited = true
default:
break
}
}
}
extension CarbEntryViewController: FoodTypeShortcutCellDelegate {
func foodTypeShortcutCellDidUpdateSelection(_ cell: FoodTypeShortcutCell) {
var absorptionTime: TimeInterval?
switch cell.selectionState {
case .fast:
absorptionTime = defaultAbsorptionTimes?.fast
case .medium:
absorptionTime = defaultAbsorptionTimes?.medium
case .slow:
absorptionTime = defaultAbsorptionTimes?.slow
case .custom:
tableView.beginUpdates()
usesCustomFoodType = true
shouldBeginEditingFoodType = true
tableView.reloadRows(at: [IndexPath(row: Row.foodType.rawValue, section: 0)], with: .fade)
tableView.endUpdates()
}
if let absorptionTime = absorptionTime {
self.absorptionTime = absorptionTime
if let cell = tableView.cellForRow(at: IndexPath(row: Row.absorptionTime.rawValue, section: 0)) as? DateAndDurationTableViewCell {
cell.duration = absorptionTime
}
}
selectedDefaultAbsorptionTimeEmoji = cell.selectedEmoji
}
}
extension CarbEntryViewController: EmojiInputControllerDelegate {
func emojiInputControllerDidAdvanceToStandardInputMode(_ controller: EmojiInputController) {
if let cell = tableView.cellForRow(at: IndexPath(row: Row.foodType.rawValue, section: 0)) as? TextFieldTableViewCell, let textField = cell.textField as? CustomInputTextField, textField.customInput != nil {
let customInput = textField.customInput
textField.customInput = nil
textField.resignFirstResponder()
textField.becomeFirstResponder()
textField.customInput = customInput
}
}
func emojiInputControllerDidSelectItemInSection(_ section: Int) {
guard !absorptionTimeWasEdited, section < orderedAbsorptionTimes.count else {
return
}
let lastAbsorptionTime = self.absorptionTime
self.absorptionTime = orderedAbsorptionTimes[section]
if let cell = tableView.cellForRow(at: IndexPath(row: Row.absorptionTime.rawValue, section: 0)) as? DateAndDurationTableViewCell {
cell.duration = max(lastAbsorptionTime ?? 0, orderedAbsorptionTimes[section])
}
}
}
extension DateAndDurationTableViewCell: NibLoadable {}
| apache-2.0 | 9e9db95a9b121ca123abb386ed6828dd | 35.724551 | 256 | 0.651503 | 5.904685 | false | false | false | false |
glessard/swift | SwiftCompilerSources/Sources/SIL/Operand.swift | 1 | 3631 | //===--- Operand.swift - Instruction operands -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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
//
//===----------------------------------------------------------------------===//
import SILBridging
/// An operand of an instruction.
public struct Operand : CustomStringConvertible, CustomReflectable {
fileprivate let bridged: BridgedOperand
init(_ bridged: BridgedOperand) {
self.bridged = bridged
}
public var value: Value {
Operand_getValue(bridged).value
}
public static func ==(lhs: Operand, rhs: Operand) -> Bool {
return lhs.bridged.op == rhs.bridged.op
}
public var instruction: Instruction {
return Operand_getUser(bridged).instruction
}
public var index: Int { instruction.operands.getIndex(of: self) }
/// True if the operand is used to describe a type dependency, but it's not
/// used as value.
public var isTypeDependent: Bool { Operand_isTypeDependent(bridged) != 0 }
public var description: String { "operand #\(index) of \(instruction)" }
public var customMirror: Mirror { Mirror(self, children: []) }
}
public struct OperandArray : RandomAccessCollection, CustomReflectable {
private let opArray: BridgedArrayRef
init(opArray: BridgedArrayRef) {
self.opArray = opArray
}
public var startIndex: Int { return 0 }
public var endIndex: Int { return Int(opArray.numElements) }
public subscript(_ index: Int) -> Operand {
assert(index >= 0 && index < endIndex)
return Operand(BridgedOperand(op: opArray.data! + index &* BridgedOperandSize))
}
public func getIndex(of operand: Operand) -> Int {
let idx = (operand.bridged.op - UnsafeRawPointer(opArray.data!)) /
BridgedOperandSize
assert(self[idx].bridged.op == operand.bridged.op)
return idx
}
public var customMirror: Mirror {
let c: [Mirror.Child] = map { (label: nil, value: $0.value) }
return Mirror(self, children: c)
}
/// Returns a sub-array defined by `bounds`.
///
/// Note: this does not return a Slice. The first index of the returnd array is always 0.
public subscript(bounds: Range<Int>) -> OperandArray {
assert(bounds.lowerBound >= 0)
assert(bounds.upperBound <= endIndex)
return OperandArray(opArray: BridgedArrayRef(
data: opArray.data! + bounds.lowerBound &* BridgedOperandSize,
numElements: bounds.upperBound - bounds.lowerBound))
}
}
public struct UseList : CollectionLikeSequence {
public struct Iterator : IteratorProtocol {
var currentOpPtr: UnsafeRawPointer?
public mutating func next() -> Operand? {
if let opPtr = currentOpPtr {
let bridged = BridgedOperand(op: opPtr)
currentOpPtr = Operand_nextUse(bridged).op
return Operand(bridged)
}
return nil
}
}
private let firstOpPtr: UnsafeRawPointer?
init(_ firstOpPtr: OptionalBridgedOperand) {
self.firstOpPtr = firstOpPtr.op
}
public var singleUse: Operand? {
if let opPtr = firstOpPtr {
if Operand_nextUse(BridgedOperand(op: opPtr)).op != nil { return nil }
return Operand(BridgedOperand(op: opPtr))
}
return nil
}
public var isSingleUse: Bool { singleUse != nil }
public func makeIterator() -> Iterator {
return Iterator(currentOpPtr: firstOpPtr)
}
}
| apache-2.0 | 602dbeec1c55b32f780692a54f0e831a | 29.771186 | 91 | 0.666483 | 4.449755 | false | false | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/generic_tuple/main.swift | 2 | 1722 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 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
//
// -----------------------------------------------------------------------------
func use<T>(_ t : T) {}
func single<T>(_ t : T) {
let x = t
use(x) //% self.expect('expr -d run-target -- t', substrs=['hello'])
//% self.expect('expr -d run-target -- x', substrs=['hello'])
//% self.expect('fr var -d run-target t', substrs=['String', 'hello'])
//% self.expect('fr var -d run-target x', substrs=['hello'])
}
func string_tuple<T, U>(_ t : (T, U)) {
let (_, y) = t
use(y) //% self.expect('expr -d run-target -- t', substrs=['hello', 'hello'])
//% self.expect('expr -d run-target -- y', substrs=['hello'])
//% self.expect('fr var -d run-target t',
//% substrs=['(String, String)', 'hello', 'hello'])
//% self.expect('fr var -d run-target y', substrs=['hello'])
}
func int_tuple<T, U>(_ t : (T, U)) {
let (_, y) = t
use(y) //% self.expect('expr -d run-target -- t',
//% substrs=['(Int32, Int64)', '111', '222'])
//% self.expect('expr -d run-target -- y', substrs=['222'])
//% self.expect('fr var -d run-target t',
//% substrs=['(Int32, Int64)', '111', '222'])
//% self.expect('fr var -d run-target y', substrs=['222'])
}
let s = "hello"
single(s)
string_tuple((s, s))
int_tuple((Int32(111), Int64(222)))
| apache-2.0 | c35caa231c4903b71eabef6730605d9a | 38.136364 | 80 | 0.526713 | 3.444 | false | false | false | false |
JJMoon/MySwiftCheatSheet | Operation/HoldingTimeView.swift | 1 | 3091 | //
// HoldingTimeView.swift
// Trainer
//
// Created by Jongwoo Moon on 2016. 2. 17..
// Copyright © 2016년 IMLab. All rights reserved.
//
import Foundation
// Heartisense Operation View
class HovHoldingTimeView : UIView {
var log = HtLog(cName: "HovHoldingTimeView")
var dObj = HsBleManager.inst().dataObj
var currentStep = HsBleManager.inst().bleState
@IBOutlet weak var labelSecond: UILabel!
@IBOutlet weak var labelHoldTimeMsg: UILabel!
func update() {
let stage = HsBleManager.inst().stage
currentStep = HsBleManager.inst().bleState
// 압박 중단 시간 표시...
let theTimer = HsBleManager.inst().calcManager.compHoldTimer // HtTimer 타이머..
let holdTime: Double = theTimer.GetSecond(dObj.count)
labelSecond.text = "\(Int(holdTime))" //[NSString stringWithFormat: @"%d", (int)holdTime];
if 10 < Int(holdTime) {
labelSecond.textColor = UIColor.redColor()
labelHoldTimeMsg.textColor = UIColor.redColor()
} else {
labelSecond.textColor = colorBarBgGrn
labelHoldTimeMsg.textColor = colorBarBgGrn
}
switch currentStep {
case .S_WHOLESTEP_AED, .S_WHOLESTEP_DESCRIPTION, .S_WHOLESTEP_BREATH:
self.hidden = true; return
default: break
}
if (self.hidden) { // 안보이면..
if (currentStep == .S_WHOLESTEP_COMPRESSION) {
if (dObj.count == 0 && HsBleManager.inst().stage > 1) { // 스테이지 바뀌고 나서 켜는 경우..
self.hidden = false;
log.logThis(" count \(dObj.count) == 0 && stage \(stage) > 1 ", lnum: 5)
return
} // 2스테이지 이상 처음 공백..
if (HsBleManager.inst().calcManager.isCycleStart == false && holdTime > 2) {
if stage == 1 && dObj.count == 0 { return } // 처음의 예외..
log.logThis(" holdTime :: \(holdTime) > 2 && stage \(stage) > 1 ", lnum: 5)
self.hidden = false;
return
} // 켜고.
}
} else { // 보이는 상태에선 끄는 조건.
if (currentStep == .S_WHOLESTEP_COMPRESSION && HsBleManager.inst().stage == 1 && dObj.count == 0) {
self.hidden = true; return
}
if (currentStep != .S_WHOLESTEP_COMPRESSION || ( dObj.count > 0 && holdTime < 0 )) { // 호흡에서 바뀐 경우는 무조건 켜주기.. 압박이 들어오는 경우.
log.logThis(" @116 호흡에서 바뀐 경우는 무조건 켜주기.. 압박이 들어오는 경우. ", lnum: 5)
self.hidden = true;
} // else ; // 그냥 놔두고..
}
}
// MARK: 언어 세팅.
func setLanguageString() {
//bttnSaveData.setTitle(local Str("save_data"), forState: UIControlState.Normal)
labelHoldTimeMsg.text = langStr.obj.hands_off_time // local Str("hold_time")
}
}
| apache-2.0 | 7cf4e9309c4256f635529b3c19b6e666 | 34.775 | 135 | 0.546471 | 3.427545 | false | false | false | false |
phatblat/realm-cocoa | Realm/ObjectServerTests/TimeoutProxyServer.swift | 2 | 3249 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////
#if os(macOS)
import Foundation
import Network
@available(OSX 10.14, *)
@objc(TimeoutProxyServer)
public class TimeoutProxyServer: NSObject {
let port: NWEndpoint.Port
let targetPort: NWEndpoint.Port
let queue = DispatchQueue(label: "TimeoutProxyServer")
var listener: NWListener!
var connections = [NWConnection]()
let serverEndpoint = NWEndpoint.Host("127.0.0.1")
private var _delay: Double = 0
@objc public var delay: Double {
get {
_delay
}
set {
queue.sync {
_delay = newValue
}
}
}
@objc public init(port: UInt16, targetPort: UInt16) {
self.port = NWEndpoint.Port(rawValue: port)!
self.targetPort = NWEndpoint.Port(rawValue: targetPort)!
}
@objc public func start() throws {
listener = try NWListener(using: NWParameters.tcp, on: port)
listener.newConnectionHandler = { incomingConnection in
self.connections.append(incomingConnection)
incomingConnection.start(queue: self.queue)
let targetConnection = NWConnection(host: self.serverEndpoint, port: self.targetPort, using: .tcp)
targetConnection.start(queue: self.queue)
self.connections.append(targetConnection)
self.queue.asyncAfter(deadline: .now() + self.delay) {
self.copy(from: incomingConnection, to: targetConnection)
self.copy(from: targetConnection, to: incomingConnection)
}
}
listener.start(queue: self.queue)
}
@objc public func stop() {
listener.cancel()
queue.sync {
for connection in connections {
connection.forceCancel()
}
}
}
private func copy(from: NWConnection, to: NWConnection) {
from.receive(minimumIncompleteLength: 1, maximumLength: 8192) { [weak self] (data, context, isComplete, _) in
guard let data = data else {
if !isComplete {
self?.copy(from: from, to: to)
}
return
}
to.send(content: data, contentContext: context ?? .defaultMessage,
isComplete: isComplete, completion: .contentProcessed({ [weak self] _ in
if !isComplete {
self?.copy(from: from, to: to)
}
}))
}
}
}
#endif // os(macOS)
| apache-2.0 | 659df0722c7366df106630ea3a456ef5 | 32.153061 | 117 | 0.572484 | 4.634807 | false | false | false | false |
jkolb/Swiftish | Tests/SwiftishTests/Matrix3Tests.swift | 1 | 1841 | /*
The MIT License (MIT)
Copyright (c) 2015-2017 Justin Kolb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import XCTest
@testable import Swiftish
class Matrix3Tests: XCTestCase {
static var allTests = [
("testInverse", testInverse),
]
func testInverse() {
let col0 = Vector3<Float>(0.6, 0.2, 0.3)
let col1 = Vector3<Float>(0.2, 0.7, 0.5)
let col2 = Vector3<Float>(0.3, 0.5, 0.7)
let a = Matrix3x3<Float>(col0, col1, col2)
let ai = Matrix3x3.invert(a)
let im = a * ai
let id = a / a
let i = Matrix3x3<Float>()
// Multiplication
XCTAssertTrue(Matrix3x3.approx(im, i, epsilon: 1e-6), "\(im) not identity")
// Division
XCTAssertTrue(Matrix3x3.approx(id, i, epsilon: 1e-6), "\(id) not identity")
}
}
| mit | fd35693d014ebe93203e032f89092c7f | 36.571429 | 83 | 0.692015 | 4.037281 | false | true | false | false |
toggl/superday | teferi/Services/Implementations/Persistency/DefaultSmartGuessService.swift | 1 | 4743 | import Foundation
import RxSwift
class DefaultSmartGuessService : SmartGuessService
{
typealias KNNInstance = (location: LocationEntity, timeStamp: Date, category: Category, timeSlot: TimeSlotEntity?)
//MARK: Private Properties
private let distanceThreshold = 400.0 //TODO: We have to think about the 400m constant. Might be too low or too high.
private let kNeighbors = 3
private let categoriesToSkip : [Category] = [.commute]
private let timeService : TimeService
private let loggingService: LoggingService
private let settingsService: SettingsService
//MARK: Initializers
init(timeService: TimeService,
loggingService: LoggingService,
settingsService: SettingsService)
{
self.timeService = timeService
self.loggingService = loggingService
self.settingsService = settingsService
}
//MARK: Public Methods
func get(forLocation location: Location) -> Observable<TimeSlotEntity?>
{
let locationEntity = location.toEntity()
return getTimeSlotMatches(forLocation: locationEntity)
.map(applyKnnAlgorithm(forLocation: locationEntity))
}
//MARK: Private Methods
private func applyKnnAlgorithm(forLocation location: LocationEntity) -> ([TimeSlotEntity]) -> TimeSlotEntity?
{
return { [unowned self] bestMatches in
guard bestMatches.count > 0 else { return nil }
let knnInstances = bestMatches.map { (location: $0.activities.first!.location, timeStamp: $0.activities.first!.location.timeStamp, category: $0.category, timeSlot: Optional($0)) }
let startTimeForKNN = Date()
let k = knnInstances.count >= self.kNeighbors ? self.kNeighbors : knnInstances.count
let bestKnnMatch = KNN<KNNInstance, Category>
.prediction(
for: (location: location, timeStamp: location.timeStamp, category: Category.unknown, timeSlot: nil),
usingK: k,
with: knnInstances,
decisionType: .maxScoreSum,
customDistance: self.distance,
labelAction: { $0.category })
self.loggingService.log(withLogLevel: .debug, message: "KNN executed in \(Date().timeIntervalSince(startTimeForKNN)) with k = \(k) on a dataset of \(knnInstances.count)")
guard let bestMatch = bestKnnMatch?.timeSlot else { return nil }
self.loggingService.log(withLogLevel: .debug, message: "TimeSlot found for location: \(location.latitude),\(location.longitude) -> \(bestMatch.category)")
return bestMatch
}
}
private func getTimeSlotMatches(forLocation location: LocationEntity) -> Observable<[TimeSlotEntity]>
{
let startDate = timeService.now.add(days: -15)
let getTimeSlotsSinceDate = InteractorFactory.shared.createGetTimeSlotsSinceDateInteractor(since: startDate)
return getTimeSlotsSinceDate.execute()
.map(nonCommuteSlots)
.map(haveActivities)
.map(areWithinDistanceThreshold(from: location))
}
private func areWithinDistanceThreshold(from location: LocationEntity) -> ([TimeSlotEntity]) -> [TimeSlotEntity]
{
return { timeSlots in
return timeSlots.filter {
// Getting just the first location is a temporal fix, the new algo won't work like this
guard let tsLocation = $0.activities.first?.location else { return false }
return tsLocation.distance(from: location) <= self.distanceThreshold
}
}
}
private func distance(instance1: KNNInstance, instance2: KNNInstance) -> Double
{
var accumulator = 0.0
let locationDifference = instance1.location.distance(from: instance2.location) / distanceThreshold
accumulator += pow(locationDifference, 2)
return sqrt(accumulator)
}
private func nonCommuteSlots(_ timeSlots: [TimeSlotEntity]) -> [TimeSlotEntity]
{
return timeSlots.filter {
$0.category != .commute
}
}
private func haveActivities(_ timeSlots: [TimeSlotEntity]) -> [TimeSlotEntity]
{
return timeSlots.filter {
$0.activities.count > 0
}
}
}
fileprivate extension Location
{
func toEntity() -> LocationEntity
{
return LocationEntity(
timeStamp: timestamp,
latitude: latitude,
longitude: longitude,
altitude: altitude,
accuracy: horizontalAccuracy
)
}
}
| bsd-3-clause | 990d948f1f772b6dfabcb95abb8b7555 | 36.944 | 191 | 0.6323 | 5.089056 | false | false | false | false |
CoreAnimationAsSwift/WZHQZhiBo | ZhiBo/ZhiBo/Main/View/CollectionBaseCell.swift | 1 | 950 | //
// CollectionBaseCell.swift
// ZhiBo
//
// Created by mac on 16/11/1.
// Copyright © 2016年 mac. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var onLineBtn: UIButton!
var anchor:AnchorModel? {
didSet {
guard let anchor = anchor else {return}
guard let url = URL(string: anchor.vertical_src) else {return}
iconImageView.kf.setImage(with: url)
nickNameLabel.text = anchor.nickname
var title : String = ""
if anchor.online > 10000 {
title = "\(Int(anchor.online / 10000))万人在线"
}else {
title = "\(anchor.online)人在线"
}
onLineBtn.setTitle(title, for: UIControlState())
}
}
}
| mit | 4a6d34ea55f8012fd44813075cfb1f65 | 24.916667 | 74 | 0.56806 | 4.507246 | false | false | false | false |
CatalystOfNostalgia/hoot | Hoot/Hoot/ProductParser.swift | 1 | 4488 | //
// ProductParser.swift
// Hoot
//
// Created by Eric Luan on 4/12/16.
// Copyright © 2016 Eric Luan. All rights reserved.
//
import Foundation
// Handles parsing the JSON returned from the server
class ProductParser {
// Useful JSON Keys for getting information
let PRODUCT_NAME_KEY = "product_name"
let PRODUCT_EMOTION_KEY = "sentic_values"
let PRODUCT_IMAGE_URL_KEY = "image_url"
let PRODUCT_SUMMARY_KEY = "sumy"
let PRODUCT_COMMENTS_KEY = "comments"
let COMMENT_RELEVANCY_KEY = "relevancy"
let COMMENT_DATA_KEY = "text"
let COMMENT_COMPOUND_EMOTIONS_KEY = "compound_emotions"
let COMMENT_SENTIC_EMOTIONS_KEY = "sentic_emotions"
let COMMENT_RATING_KEY = "rating"
let COMPOUND_EMOTION_EMOTION_KEY = "compound_emotion"
let COMPOUND_EMOTION_STRENGTH_KEY = "strength"
// Parses the high level array of products
func parseProducts(data: NSData) -> [Product] {
var products:[Product] = []
do {
let json: NSArray = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as! NSArray
for item in json {
if let productJson = item as? [String: AnyObject]{
products.append(parseProduct(productJson)!)
}
}
} catch {
print("Error has occured")
print(error)
}
return products
}
// Parses a single product
func parseProduct(product: [String: AnyObject]) -> Product? {
guard let productName = product[PRODUCT_NAME_KEY] as? String else {
return nil
}
guard let productUrl = product[PRODUCT_IMAGE_URL_KEY] as? String else {
return nil
}
guard let emotions = product[PRODUCT_EMOTION_KEY] as? [String] else {
return nil
}
guard let comments = product[PRODUCT_COMMENTS_KEY] as? NSArray else {
return nil
}
guard let productDescription = product[PRODUCT_SUMMARY_KEY] as? String else {
return nil
}
let productComments = parseComments(comments)
let productEmotions = emotions.joinWithSeparator(", ")
return Product(name: productName, description: productDescription, imageURL: productUrl, emotions: productEmotions, comments: productComments)
}
// Parse the comments for a product
func parseComments(comments: NSArray) -> [Comment] {
var parsed_comments:[Comment] = []
for comment in comments {
guard let commentJson = comment as? [String: AnyObject] else {
continue
}
guard let relevancy = commentJson[COMMENT_RELEVANCY_KEY] as? Double else {
continue
}
guard let commentText = commentJson[COMMENT_DATA_KEY] as? String else {
continue
}
guard let compoundEmotions = commentJson[COMMENT_COMPOUND_EMOTIONS_KEY] as? NSArray else {
continue
}
guard let senticEmotions = commentJson[COMMENT_SENTIC_EMOTIONS_KEY] as? [String] else {
continue
}
guard let commentRating = commentJson[COMMENT_RATING_KEY] as? Double else {
continue
}
let complexEmotions = processComplexEmotions(compoundEmotions)
let basicEmotions = senticEmotions.joinWithSeparator(", ")
parsed_comments.append(Comment(emotions: basicEmotions, comment: commentText, relevancy: relevancy, rating: commentRating, complexEmotions: complexEmotions))
}
return parsed_comments
}
// Parse the complex emotions for a comment
func processComplexEmotions(complexComments: NSArray) -> String {
var complexEmotionString: [String] = []
for complexEmotion in complexComments {
guard let emotionDict = complexEmotion as? [String: AnyObject] else {
continue
}
guard let emotionString = emotionDict[COMPOUND_EMOTION_EMOTION_KEY] as? String else {
continue
}
guard let emotionStrength = emotionDict[COMPOUND_EMOTION_STRENGTH_KEY] as? String else {
continue
}
complexEmotionString.append(emotionStrength + " " + emotionString)
}
return complexEmotionString.joinWithSeparator(", ")
}
} | mit | b918f76e10df77a0f2b81eec432315aa | 37.033898 | 169 | 0.60731 | 4.68861 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/Alert/View/StaticAlertView.swift | 2 | 1562 | //
// StaticAlertView.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 1/03/2016.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
@IBDesignable class StaticAlertView: NibView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var button0: UIButton!
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var messageButton0Constraint: NSLayoutConstraint!
// MARK: - Variables
@IBInspectable var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
@IBInspectable var message: String? {
get {
return messageLabel.text
}
set {
messageLabel.text = newValue
}
}
@IBInspectable var button0Title: String? {
get {
return button0.title(for: .normal)
}
set {
button0.setTitle(newValue, for: .normal)
}
}
@IBInspectable var button1Title: String? {
get {
return button1.title(for: .normal)
}
set {
button1.setTitle(newValue, for: .normal)
setNeedsUpdateView()
}
}
// MARK: - NibView
override func updateView() {
super.updateView()
button1.isHidden = button1Title == nil
messageLabel.activateOnlyConstraintsWithFirstVisible(in: [button1, button0])
}
}
| mit | 82112da8da0b4d3d3b5fa49193d7402e | 22.298507 | 84 | 0.581678 | 4.577713 | false | false | false | false |
SwiftKitz/Appz | Playground/Playground.playground/Contents.swift | 1 | 1553 | //: Playground - noun: a place where people can play
import UIKit
import Appz
//: # Appz 📱
//: ### Deeplinking to external applications made easy!
//: ## Features
//: Concise syntax to trigger deeplinking
let app = UIApplication.shared
app.canOpen(Applications.Instagram())
app.open(Applications.AppStore(), action: .account(id: "395107918"))
app.open(Applications.AppSettings(), action: .open)
//: Transparent web fallback
// In case the user doesn't have twitter installed, it will fallback to
// https://twitter.com/testUser/statuses/2
app.open(Applications.Twitter(), action: .status(id: "2", screenName: "testUser"))
//: Add your own application
// Applications are recommended to be part of the
// "Applicaitons" namespace
extension Applications {
// Define your application as a type that
// conforms to "ExternalApplication"
struct MyApp: ExternalApplication {
typealias ActionType = Applications.MyApp.Action
let scheme = "myapp:"
let fallbackURL = ""
let appStoreId = ""
}
}
// Finally, you define the actions your app supports
extension Applications.MyApp {
enum Action: ExternalApplicationAction {
case open
// Each action should provide an app path and web path to be
// added to the associated URL
var paths: ActionPaths {
switch self {
case .open:
return ActionPaths()
}
}
}
}
app.open(Applications.MyApp(), action: .open)
| mit | e55a6b18b512c50eea8e63dd2277928c | 25.724138 | 83 | 0.647097 | 4.572271 | false | false | false | false |
artursDerkintis/Starfly | Starfly/SFHomeController.swift | 1 | 12643 | //
// SFHomeVC.swift
// Starfly
//
// Created by Arturs Derkintis on 9/18/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
class SFHomeController: UIViewController, UIScrollViewDelegate {
var background : UIImageView!
var scrollView : UIScrollView!
var controlView : UIView?
var switcher : SFHomeSwitcher?
var historyController : SFHistoryController!
var favoritesController : SFFavoritesController!
var bookmarksController : SFBookmarksController!
var editButton : SFButton?
var imageChange : SFButton?
var radial : ALRadialMenu?
override func viewDidLoad() {
super.viewDidLoad()
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "bookcels")
view.backgroundColor = .clearColor()
background = UIImageView(frame: view.bounds)
background.contentMode = UIViewContentMode.ScaleAspectFill
background.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
let b = NSUserDefaults.standardUserDefaults().objectForKey("BACKGr")
background.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(b == nil ? "abs2" : b as! String, ofType: ".jpg")!)
view.addSubview(background!)
scrollView = UIScrollView(frame: view.bounds)
scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
scrollView.pagingEnabled = true
scrollView.delegate = self
scrollView.showsHorizontalScrollIndicator = false
scrollView.bounces = false
view.addSubview(scrollView)
favoritesController = SFFavoritesController()
favoritesController.view.frame = CGRect(x: view.bounds.width, y: 90, width: view.bounds.width, height: view.bounds.height - 90)
favoritesController.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
scrollView.addSubview(favoritesController.view)
bookmarksController = SFBookmarksController()
bookmarksController.view.frame = CGRect(x: 0, y: 90, width: view.bounds.width, height: view.bounds.height - 90)
bookmarksController.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
scrollView?.addSubview(bookmarksController.view)
historyController = SFHistoryController()
addChildViewController(historyController)
historyController.view.frame = CGRect(x: view.bounds.width * 2, y: 135, width: view.bounds.width, height: view.bounds.height - 90)
historyController.view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
historyController.tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
scrollView.addSubview(historyController.view)
controlView = UIView(frame: CGRect(x: view.frame.width * 0.5 - 150, y: view.frame.height - 80, width: 300, height: 40))
switcher = SFHomeSwitcher(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
switcher!.autoresizingMask = [UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleTopMargin]
switcher!.addTarget(self, action: "scroll:", forControlEvents: UIControlEvents.ValueChanged)
switcher!.addTarget(self, action: "scrollEnded:", forControlEvents: UIControlEvents.TouchUpInside)
editButton = SFButton(type: UIButtonType.Custom)
editButton!.frame = CGRect(x: 5, y: self.view.frame.height - 35, width: 30, height: 30)
editButton!.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin
editButton!.setImage(UIImage(named: Images.edit), forState: UIControlState.Normal)
editButton!.setImage(UIImage(named: Images.edit)?.imageWithColor(UIColor.lightGrayColor()), forState: UIControlState.Highlighted)
editButton!.contentEdgeInsets = UIEdgeInsets(top: 12.5, left: 6, bottom: 12.5, right: 6)
editButton!.layer.cornerRadius = editButton!.frame.size.height * 0.5
editButton!.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor
editButton!.layer.shadowOffset = CGSize(width: 0, height: 0)
editButton!.layer.shadowRadius = 2
editButton!.layer.shadowOpacity = 1.0
editButton!.layer.rasterizationScale = UIScreen.mainScreen().scale
editButton!.layer.shouldRasterize = true
editButton!.tag = 0
editButton!.addTarget(self, action: "editContent:", forControlEvents: UIControlEvents.TouchDown)
view.addSubview(editButton!)
controlView!.addSubview(switcher!)
view.addSubview(controlView!)
let long = UILongPressGestureRecognizer(target: self, action: "long:")
view.addGestureRecognizer(long)
imageChange = SFButton(type: UIButtonType.Custom)
imageChange!.frame = CGRect(x: view.frame.width - 35, y: self.view.frame.height - 35, width: 30, height: 30)
imageChange!.autoresizingMask = [UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleLeftMargin]
imageChange!.setImage(UIImage(named: Images.image), forState: UIControlState.Normal)
imageChange!.setImage(UIImage(named: Images.image)?.imageWithColor(UIColor.lightGrayColor()), forState: UIControlState.Highlighted)
imageChange!.setImage(UIImage(named: Images.closeTab), forState: UIControlState.Selected)
imageChange!.contentEdgeInsets = UIEdgeInsets(top: 8, left: 6, bottom: 8, right: 6)
imageChange!.layer.cornerRadius = imageChange!.frame.size.height * 0.5
imageChange!.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor
imageChange!.layer.shadowOffset = CGSize(width: 0, height: 0)
imageChange!.layer.shadowRadius = 2
imageChange!.layer.shadowOpacity = 1.0
imageChange!.layer.rasterizationScale = UIScreen.mainScreen().scale
imageChange!.layer.shouldRasterize = true
imageChange!.tag = 0
imageChange!.addTarget(self, action: "openMenu:", forControlEvents: UIControlEvents.TouchDown)
view.addSubview(imageChange!)
}
func openMenu(sender : SFButton) {
if sender.tag == 0 {
sender.tag = 1
sender.selected = true
var buttons = [ALRadialMenuButton]()
for imageName in backgroundImagesThumbnails() {
let button = ALRadialMenuButton(type: UIButtonType.Custom)
button.setImage(UIImage(named: imageName + ".jpg"), forState: UIControlState.Normal)
button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
button.tag = backgroundImagesThumbnails().indexOf(imageName)!
button.frame = CGRect(x: 0, y: 0, width: 58, height: 58)
button.imageView?.layer.cornerRadius = button.frame.size.height * 0.5
button.layer.cornerRadius = button.frame.height * 0.5
button.imageView?.layer.masksToBounds = true
button.layer.shadowColor = UIColor.blackColor().colorWithAlphaComponent(0.5).CGColor
button.layer.shadowOffset = CGSize(width: 0, height: 0)
button.layer.shadowRadius = 2
button.layer.shadowOpacity = 1.0
button.layer.rasterizationScale = UIScreen.mainScreen().scale
button.layer.shouldRasterize = true
buttons.append(button)
button.addTarget(self, action: "changeImage:", forControlEvents: UIControlEvents.TouchDown)
}
let animationOptions: UIViewAnimationOptions = [UIViewAnimationOptions.CurveEaseInOut, UIViewAnimationOptions.BeginFromCurrentState]
UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: animationOptions, animations: {
self.scrollView?.alpha = 0.001
self.editButton?.alpha = 0.001
self.switcher?.alpha = 0.001
sender.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
sender.center = CGPoint(x: CGRectGetMidX(self.view.frame), y: CGRectGetMidY(self.view.frame))
}) {(finish) -> Void in
self.radial = ALRadialMenu()
.setButtons(buttons)
.setDelay(0.01)
.setAnimationOrigin(sender.center)
.presentInView(self.view)
self.view.bringSubviewToFront(self.imageChange!)
}
} else {
sender.tag = 0
self.radial?.dismiss()
self.imageChange?.selected = false
UIView.animateWithDuration(0.5) {() -> Void in
self.scrollView?.alpha = 1
self.editButton?.alpha = 1
self.switcher?.alpha = 1
self.imageChange!.frame = CGRect(x: self.view.frame.width - 35, y: self.view.frame.height - 35, width: 30, height: 30)
self.imageChange!.contentEdgeInsets = UIEdgeInsets(top: 8, left: 6, bottom: 8, right: 6)
self.imageChange!.layer.cornerRadius = self.imageChange!.frame.size.height * 0.5
}
}
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
self.radial?.dismiss()
self.imageChange?.selected = false
UIView.animateWithDuration(0.1) {() -> Void in
self.scrollView?.alpha = 1
self.editButton?.alpha = 1
self.switcher?.alpha = 1
self.imageChange!.frame = CGRect(x: self.view.frame.width - 35, y: self.view.frame.height - 35, width: 30, height: 30)
self.imageChange!.contentEdgeInsets = UIEdgeInsets(top: 8, left: 6, bottom: 8, right: 6)
self.imageChange!.layer.cornerRadius = self.imageChange!.frame.size.height * 0.5
}
}
func changeImage(sender : ALRadialMenuButton) {
let tag = sender.tag
self.radial?.dismiss()
self.imageChange?.selected = false
background!.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource(backgroundImages() [tag], ofType: ".jpg")!)
NSUserDefaults.standardUserDefaults().setObject(backgroundImages() [tag], forKey: "BACKGr")
UIView.animateWithDuration(0.5) {() -> Void in
self.scrollView?.alpha = 1
self.editButton?.alpha = 1
self.switcher?.alpha = 1
self.imageChange!.frame = CGRect(x: self.view.frame.width - 35, y: self.view.frame.height - 35, width: 30, height: 30)
self.imageChange!.contentEdgeInsets = UIEdgeInsets(top: 8, left: 6, bottom: 8, right: 6)
self.imageChange!.layer.cornerRadius = self.imageChange!.frame.size.height * 0.5
}
}
func editContent(sender : SFButton) {
UIView.animateWithDuration(0.3, animations: {() -> Void in
sender.transform = sender.tag == 1 ? CGAffineTransformIdentity : CGAffineTransformMakeRotation(CGFloat(degreesToRadians(90)))
})
switch currentPage {
case 0:
break
case 1:
favoritesController?.favoritesProvider.switchDeleteButton(sender.tag == 1 ? false : true)
break
case 2:
historyController.showDeleteActions()
break
default:
break
}
sender.tag = sender.tag == 0 ? 1 : 0
}
func long(sender: UILongPressGestureRecognizer) {
if sender.state == .Began {
scrollView?.scrollEnabled = false
} else if sender.state == .Ended {
scrollView?.scrollEnabled = true
}
}
var currentPage : Int = 1 {
didSet {
self.editButton?.tag = 0
UIView.animateWithDuration(0.3, animations: {() -> Void in
self.editButton!.transform = CGAffineTransformIdentity
})
favoritesController.favoritesProvider.switchDeleteButton(false)
// historyController?.showActions(false)
if currentPage != oldValue {
switch currentPage {
case 0:
editButton?.hidden = true
bookmarksController?.load()
break
case 1:
editButton?.hidden = false
break
case 2:
editButton?.hidden = false
historyController?.load()
break
default:
break
}}
}
}
func scroll(sender : SFHomeSwitcher) {
let width = sender.frame.width
let rate = scrollView!.contentSize.width / width
scrollView?.contentOffset = CGPoint(x: sender.floater!.frame.origin.x * rate, y: 0)
}
func scrollEnded(sender : SFHomeSwitcher) {
scrollView?.setContentOffset(CGPoint(x: scrollView!.frame.width * CGFloat(sender.currentPage), y: 0), animated: true)
currentPage = sender.currentPage
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let width = switcher!.frame.width
let rate = width / scrollView.contentSize.width
switcher?.liveScroll(CGPoint(x: scrollView.contentOffset.x * rate, y: 0))
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
currentPage = Int(scrollView.contentOffset.x / scrollView.frame.width)
print(currentPage)
switcher?.setPage(currentPage)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
controlView?.frame = CGRect(x: view.frame.width * 0.5 - 150, y: view.frame.height - 80, width: 300, height: 40)
historyController.view.frame = CGRect(x: view.bounds.width * 2, y: 150, width: view.bounds.width, height: view.bounds.height - 90)
favoritesController.view.frame = CGRect(x: view.bounds.width, y: 90, width: view.bounds.width, height: view.bounds.height - 90)
bookmarksController.view.frame = CGRect(x: 0, y: 90, width: view.bounds.width, height: view.bounds.height - 90)
scrollView.contentSize = CGSize(width: view.frame.width * 3, height: 200)
scrollView.setContentOffset(CGPoint(x: scrollView.frame.width * CGFloat(currentPage), y: 0), animated: false)
}
}
| mit | 15c3dc55d9b393cb91c31ea3b0fae655 | 41.709459 | 142 | 0.745214 | 3.99053 | false | false | false | false |
kean/Nuke | Sources/Nuke/Processing/ImageProcessors+Composition.swift | 1 | 2318 | // The MIT License (MIT)
//
// Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean).
import Foundation
extension ImageProcessors {
/// Composes multiple processors.
public struct Composition: ImageProcessing, Hashable, CustomStringConvertible {
let processors: [any ImageProcessing]
/// Composes multiple processors.
public init(_ processors: [any ImageProcessing]) {
// note: multiple compositions are not flatten by default.
self.processors = processors
}
/// Processes the given image by applying each processor in an order in
/// which they were added. If one of the processors fails to produce
/// an image the processing stops and `nil` is returned.
public func process(_ image: PlatformImage) -> PlatformImage? {
processors.reduce(image) { image, processor in
autoreleasepool {
image.flatMap(processor.process)
}
}
}
/// Processes the given image by applying each processor in an order in
/// which they were added. If one of the processors fails to produce
/// an image the processing stops and an error is thrown.
public func process(_ container: ImageContainer, context: ImageProcessingContext) throws -> ImageContainer {
try processors.reduce(container) { container, processor in
try autoreleasepool {
try processor.process(container, context: context)
}
}
}
/// Returns combined identifier of all the underlying processors.
public var identifier: String {
processors.map({ $0.identifier }).joined()
}
/// Creates a combined hash of all the given processors.
public func hash(into hasher: inout Hasher) {
for processor in processors {
hasher.combine(processor.hashableIdentifier)
}
}
/// Compares all the underlying processors for equality.
public static func == (lhs: Composition, rhs: Composition) -> Bool {
lhs.processors == rhs.processors
}
public var description: String {
"Composition(processors: \(processors))"
}
}
}
| mit | d8260f5815bddb69c5513a8db7818b7f | 37 | 116 | 0.610871 | 5.572115 | false | false | false | false |
jkolb/midnightbacon | MidnightBacon/Modules/Comments/CommentsDataController.swift | 1 | 5000 | //
// CommentsDataController.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import FranticApparatus
import Common
import Reddit
protocol CommentsDataControllerDelegate : class {
func commentsDataControllerDidBeginLoad(commentsDataController: CommentsDataController)
func commentsDataControllerDidEndLoad(commentsDataController: CommentsDataController)
func commentsDataControllerDidLoadComments(commentsDataController: CommentsDataController)
func commentsDataController(commentsDataController: CommentsDataController, didFailWithReason reason: ErrorType)
}
class CommentsDataController {
var redditRequest: RedditRequest!
var oauthService: OAuthService!
var gateway: Gateway!
weak var delegate: CommentsDataControllerDelegate!
var link: Link
var comments: [Thing] = []
private var _isLoaded = false
var commentsPromise: Promise<(Listing, [Thing])>!
init(link: Link) {
self.link = link
}
func commentAtIndexPath(indexPath: NSIndexPath) -> Comment? {
let thing = comments[indexPath.row]
switch thing {
case let comment as Comment:
return comment
default:
return nil
}
}
func moreAtIndexPath(indexPath: NSIndexPath) -> More? {
let thing = comments[indexPath.row]
switch thing {
case let more as More:
return more
default:
return nil
}
}
var count: Int {
return comments.count
}
var isLoaded: Bool {
return _isLoaded
}
func refreshComments() {
_isLoaded = false
comments.removeAll(keepCapacity: true)
loadComments()
}
func loadComments() {
delegate.commentsDataControllerDidBeginLoad(self)
assert(!isLoaded, "Already loading comments")
let commentsRequest = redditRequest.linkComments(link)
commentsPromise = oauthLoadComments(commentsRequest).thenWithContext(self, { (controller, result) -> (Listing, [Thing]) in
let loadedLinkListing = result.0
if loadedLinkListing.children.count != 1 {
throw ThingError.UnexpectedJSON
}
let loadedLink = loadedLinkListing.children[0] as! Link
if loadedLink.id != controller.link.id {
throw ThingError.UnexpectedJSON
}
controller.link = loadedLink
controller.comments = result.1
controller.didLoadComments()
return result
}).finallyWithContext(self, { controller in
controller.commentsPromise = nil
controller.delegate?.commentsDataControllerDidEndLoad(controller)
})
}
func didLoadComments() {
if let strongDelegate = delegate {
strongDelegate.commentsDataControllerDidLoadComments(self)
}
}
func oauthLoadComments(commentsRequest: APIRequestOf<(Listing, [Thing])>, forceRefresh: Bool = false) -> Promise<(Listing, [Thing])> {
return oauthService.aquireAccessToken(forceRefresh: forceRefresh).thenWithContext(self, { (controller, accessToken) -> Promise<(Listing, [Thing])> in
return controller.gateway.performRequest(commentsRequest, accessToken: accessToken)
}).recoverWithContext(self, { (controller, error) -> Promise<(Listing, [Thing])> in
switch error {
case RedditAPIError.Unauthorized:
if forceRefresh {
throw error
} else {
return controller.oauthLoadComments(commentsRequest, forceRefresh: true)
}
default:
throw error
}
})
}
}
| mit | 72f4e1f2075908e10bad4e432039e199 | 34.460993 | 157 | 0.6538 | 5.29661 | false | false | false | false |
ryanipete/AmericanChronicle | AmericanChronicle/Code/Modules/DatePicker/View/Subviews/MonthKeyboard.swift | 1 | 2456 | import UIKit
final class MonthKeyboard: UIView {
var monthTapHandler: ((Int) -> Void)?
var selectedMonth: Int? { // 1-based (like the month in NSDateComponent)
didSet {
for (idx, button) in allMonthButtons.enumerated() {
if let selectedMonth = selectedMonth {
button.isSelected = (idx == (selectedMonth - 1))
} else {
button.isSelected = false
}
}
}
}
private var allMonthButtons: [UIButton] = []
private let mainStackView: UIStackView = {
let subview = UIStackView()
subview.translatesAutoresizingMaskIntoConstraints = false
subview.axis = .vertical
subview.spacing = spacing
subview.distribution = .fillEqually
return subview
}()
private static let spacing: CGFloat = 4.0
func commonInit() {
backgroundColor = .white
addSubview(mainStackView)
mainStackView.fillSuperview(insets: .all(MonthKeyboard.spacing))
for monthSymbol in DayMonthYear.allMonthSymbols() {
let button = KeyboardButton(title: monthSymbol)
button.addTarget(self,
action: #selector(didTapButton(_:)),
for: .touchUpInside)
allMonthButtons.append(button)
}
var buttonsToAdd = allMonthButtons // copy
while !buttonsToAdd.isEmpty {
var row: [UIButton] = []
while let buttonToAdd = buttonsToAdd.first, row.count < 4 {
row.append(buttonToAdd)
buttonsToAdd.removeFirst()
}
addRowWithButtons(row)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
@objc func didTapButton(_ button: UIButton) {
if let index = allMonthButtons.firstIndex(of: button) {
monthTapHandler?(index + 1)
}
}
private func addRowWithButtons(_ buttons: [UIButton]) {
let rowView = UIStackView(arrangedSubviews: buttons)
rowView.translatesAutoresizingMaskIntoConstraints = false
rowView.axis = .horizontal
rowView.spacing = MonthKeyboard.spacing
rowView.distribution = .fillEqually
mainStackView.addArrangedSubview(rowView)
}
}
| mit | 71c2ddd4ed788b2d86f50ec248d75a1e | 30.896104 | 76 | 0.585098 | 5.28172 | false | false | false | false |
tutsplus/iOSFromScratch-ShoppingList-1 | Shopping List/ListViewController.swift | 1 | 5183 | //
// ListViewController.swift
// Shopping List
//
// Created by Bart Jacobs on 12/12/15.
// Copyright © 2015 Envato Tuts+. All rights reserved.
//
import UIKit
class ListViewController: UITableViewController, AddItemViewControllerDelegate {
let CellIdentifier = "Cell Identifier"
var items = [Item]()
// MARK: -
// MARK: Initialization
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
// Load Items
loadItems()
}
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Set Title
title = "Items"
// Register Class
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellIdentifier)
// Create Add Button
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addItem:")
}
// MARK: -
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AddItemViewController" {
if let navigationController = segue.destinationViewController as? UINavigationController,
let addItemViewController = navigationController.viewControllers.first as? AddItemViewController {
addItemViewController.delegate = self
}
}
}
// MARK: -
// MARK: Table View Data Source Methods
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Dequeue Reusable Cell
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath)
// Fetch Item
let item = items[indexPath.row]
// Configure Table View Cell
cell.textLabel?.text = item.name
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: -
// MARK: Add Item View Controller Delegate Methods
func controller(controller: AddItemViewController, didSaveItemWithName name: String, andPrice price: Float) {
// Create Item
let item = Item(name: name, price: price)
// Add Item to Items
items.append(item)
// Add Row to Table View
tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: (items.count - 1), inSection: 0)], withRowAnimation: .None)
// Save Items
saveItems()
}
// MARK: -
// MARK: Actions
func addItem(sender: UIBarButtonItem) {
performSegueWithIdentifier("AddItemViewController", sender: self)
}
// MARK: -
// MARK: Helper Methods
private func loadItems() {
if let filePath = pathForItems() where NSFileManager.defaultManager().fileExistsAtPath(filePath) {
if let archivedItems = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [Item] {
items = archivedItems
}
}
}
private func saveItems() {
if let filePath = pathForItems() {
NSKeyedArchiver.archiveRootObject(items, toFile: filePath)
}
}
private func pathForItems() -> String? {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
if let documents = paths.first, let documentsURL = NSURL(string: documents) {
return documentsURL.URLByAppendingPathComponent("items").path
}
return nil
}
}
| bsd-2-clause | 8f5c250fce8c208730d41d52e06a190a | 31.797468 | 157 | 0.64203 | 5.542246 | false | false | false | false |
dmorenob/HermesFramework | Hermes/Hermes.swift | 1 | 8082 | //
// Hermes.swift
// Hermes
//
// Created by David Moreno Briz on 6/11/14.
// Copyright (c) 2014 David Moreno Briz. All rights reserved.
//
import Foundation
class Hermes: NSObject {
// MARK: - Attributes
// Constants related to the app
let oauth_consumer_key: String = ""
let oauth_consumer_secret: String = ""
let oauth_signature_method: String = "HMAC-SHA1"
let oauth_version: String = "1.0"
// Access token and access token secreat for a certain user.
var oauth_token: String
var oauth_token_secret: String
// Identifier, screen name and profile pic url for the current user.
var user_id: String!
var screen_name: String!
var profile_image_url_https: String!
// Init
init(accessTokenKey: String, accessTokenSecret: String){
self.oauth_token = accessTokenKey
self.oauth_token_secret = accessTokenSecret
}
// MARK: - Funcs that generates elements for a HTTP Header
// Generates an oauth_nonce
func calculateNonce() -> String {
let length: UInt = 32
var data = NSMutableData(length: Int(length))
var result = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data!.mutableBytes))
var nonce = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
return nonce
}
// Generates an oauth_timestamp
func calculateTimestamp() -> String {
var timestamp = Int(round(NSDate().timeIntervalSince1970))
return timestamp.description
}
// Generates the oauth_signature using de HTTPMethod, the base url and the query, header and body parameters
func calculateSignature(HTTPMethod: String, baseURL: String, parameters: Array<(key: String, value: String)>) -> String {
var generator: SignatureGenerator = SignatureGenerator(HTTPMethod: HTTPMethod, baseURL: baseURL, parameters: parameters) // We create a signature generator
return generator.generateSignature(self.oauth_consumer_secret,oauthTokenSecret: self.oauth_token_secret) // And generate the signature.
}
// Generates a generic Array of Header params without the signature.
func generateParamsForHeaderWhitoutSignature() -> Array<(key: String, value: String)> {
var parametersForHeader = Array<(key: String, value: String)>()
parametersForHeader += [(key: "oauth_consumer_key", value: self.oauth_consumer_key)]
parametersForHeader += [(key: "oauth_signature_method", value: self.oauth_signature_method)]
parametersForHeader += [(key: "oauth_nonce", value: self.calculateNonce())]
parametersForHeader += [(key: "oauth_timestamp", value: self.calculateTimestamp())]
parametersForHeader += [(key: "oauth_token", value: self.oauth_token)]
parametersForHeader += [(key: "oauth_version", value: self.oauth_version)]
return parametersForHeader
}
// MARK: - Funcs that perform authorized GET and POST requests to Twitter API.
// To perform a GET we need: the base URL where the petition is going to be sent (without the query), query, header (no signature) and body parameters. Also we will use a completition handler to handle results.
func get(baseURL: String, paramsForQuery: Array<(key: String, value: String)>, paramsForHeaderWhitoutSignature: Array<(key: String, value: String)>, paramsForBody: Array<(key: String, value: String)>, completitionHandler: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)){
let HTTPMethod: String = "GET"
self.performHTTPMethod(HTTPMethod, baseURL: baseURL, paramsForQuery: paramsForQuery, paramsForHeaderWhitoutSignature: paramsForHeaderWhitoutSignature, paramsForBody: paramsForBody, completitionHandler: completitionHandler)
}
// To perform a POST we need: the base URL where the petition is going to be sent (without the query), query, header (no signature) and body parameters. Also we will use a completition handler to handle results.
func post(baseURL: String, paramsForQuery: Array<(key: String, value: String)>, paramsForHeaderWhitoutSignature: Array<(key: String, value: String)>, paramsForBody: Array<(key: String, value: String)>, completitionHandler: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)){
let HTTPMethod: String = "POST"
self.performHTTPMethod(HTTPMethod, baseURL: baseURL, paramsForQuery: paramsForQuery, paramsForHeaderWhitoutSignature: paramsForHeaderWhitoutSignature, paramsForBody: paramsForBody, completitionHandler: completitionHandler)
}
// Auxiliar func to perform a generic HTTP request. It will be used by get and post funcs.
func performHTTPMethod(HTTPMethod: String, baseURL: String, paramsForQuery: Array<(key: String, value: String)>, paramsForHeaderWhitoutSignature: Array<(key: String, value: String)>, paramsForBody: Array<(key: String, value: String)>, completitionHandler: ((data: NSData!, response: NSURLResponse!, error: NSError!) -> Void)){
// We create an arrat of all the parameters (query, header and body) to genereate a signature for the request.
var paramsForSignature: Array<(key: String, value: String)> = Array<(key: String, value: String)>()
paramsForSignature += paramsForHeaderWhitoutSignature
paramsForSignature += paramsForQuery
paramsForSignature += paramsForBody
// And generate the signature.
var signature: String = self.calculateSignature(HTTPMethod, baseURL: baseURL, parameters: paramsForSignature)
// We add the signature to the parameters header
var paramsForHeader = paramsForHeaderWhitoutSignature
paramsForHeader += [(key: "oauth_signature", value: signature)]
// And generate the authorization
var authorization: String = AuthorizationGenerator.generateAuthorizationString(paramsForHeader)
// We create the request
// First we generat the complete url where the HTTP request is going to be performed: baseURL + query
var completeURL: String = baseURL
if !paramsForQuery.isEmpty {
var sortedQuery = paramsForQuery
sortedQuery.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 }
completeURL += "?"
for (idx, parameter) in enumerate(sortedQuery){
completeURL += (parameter.key).encodingForTheWin(NSUTF8StringEncoding)
completeURL += "="
completeURL += (parameter.value).encodingForTheWin(NSUTF8StringEncoding)
if idx != sortedQuery.count - 1 {
completeURL += "&"
}
}
}
// We create the request to the complete URL
var request = NSMutableURLRequest(URL: NSURL(string: completeURL)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = HTTPMethod //Add the method to the request
request.addValue(authorization, forHTTPHeaderField: "Authorization") //Add the authorization request
// If there are body parameters, we add them to the request
if !paramsForBody.isEmpty {
var sortedBody = paramsForQuery
sortedBody.sort { $0.0 == $1.0 ? $0.1 < $1.1 : $0.0 < $1.0 }
var bodyString: String = ""
for (idx, parameter) in enumerate(sortedBody){
bodyString += (parameter.key) //Maybe I should encode here
bodyString += "="
bodyString += (parameter.value) //Maybe I should encode here
if idx != sortedBody.count - 1 {
completeURL += "&"
}
}
var body: NSData = (bodyString as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPBody = body
}
// We perform the request and analyze the response using the completition handler.
var task = session.dataTaskWithRequest(request, completitionHandler)
task.resume()
}
} | mit | 319ef7f7ffc8d7f22f5099ae8ecc7035 | 55.131944 | 330 | 0.672606 | 5.032379 | false | false | false | false |
jay18001/brickkit-ios | Example/Source/Examples/HorizontalScroll/HorizontalCollectionViewController.swift | 1 | 3502 | //
// HorizontalCollectionViewController.swift
// BrickKit iOS Example
//
// Created by Ruben Cagnie on 10/13/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
import BrickKit
class HorizontalCollectionViewController: BrickViewController {
override class var brickTitle: String {
return "Collection Horizontal Scroll"
}
override class var subTitle: String {
return "Horizontally scrolling of CollectionBricks"
}
var collectionSection: BrickSection!
let numberOfCollections = 9
struct Identifiers {
static let collectionBrick = "CollectionBrick"
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .brickBackground
self.layout.scrollDirection = .horizontal
self.brickCollectionView.registerBrickClass(ImageBrick.self)
self.view.backgroundColor = .brickBackground
collectionSection = BrickSection(bricks: [
ImageBrick(width: .ratio(ratio: 1/2), height: .ratio(ratio: 1), dataSource: self),
BrickSection(width: .ratio(ratio: 1/2), bricks: [
LabelBrick(RepeatCollectionBrickViewController.Identifiers.titleLabel, backgroundColor: .brickGray2, dataSource: self),
LabelBrick(RepeatCollectionBrickViewController.Identifiers.subTitleLabel, backgroundColor: .brickGray4, dataSource: self)
])
], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5), alignRowHeights: true)
self.registerBrickClass(CollectionBrick.self)
let section = BrickSection(bricks: [
CollectionBrick(HorizontalCollectionViewController.Identifiers.collectionBrick, width: .ratio(ratio: 1/2), backgroundColor: .brickSection, dataSource: self, brickTypes: [LabelBrick.self, ImageBrick.self])
], inset: 20)
section.repeatCountDataSource = self
self.setSection(section)
}
}
extension HorizontalCollectionViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == HorizontalCollectionViewController.Identifiers.collectionBrick {
return numberOfCollections
} else {
return 1
}
}
}
extension HorizontalCollectionViewController: CollectionBrickCellDataSource {
func sectionForCollectionBrickCell(cell: CollectionBrickCell) -> BrickSection {
return collectionSection
}
}
extension HorizontalCollectionViewController: ImageBrickDataSource {
func imageForImageBrickCell(imageBrickCell: ImageBrickCell) -> UIImage? {
return UIImage(named: "image\(imageBrickCell.collectionIndex)")
}
func contentModeForImageBrickCell(imageBrickCell: ImageBrickCell) -> UIViewContentMode {
return .scaleAspectFill
}
}
extension HorizontalCollectionViewController: LabelBrickCellDataSource {
func configureLabelBrickCell(_ cell: LabelBrickCell) {
let identifier = cell.brick.identifier
let collectionIndex = cell.collectionIndex + 1
if identifier == RepeatCollectionBrickViewController.Identifiers.titleLabel {
cell.label.text = "Title \(collectionIndex)".uppercased()
} else if identifier == RepeatCollectionBrickViewController.Identifiers.subTitleLabel {
cell.label.text = "SubTitle \(collectionIndex)".uppercased()
}
}
}
| apache-2.0 | 201462e21a5272926dace8c5b334202d | 32.990291 | 216 | 0.709512 | 5.574841 | false | false | false | false |
eric1202/LZJ_Coin | LZJ_Coin/Pods/Spruce/Sources/Classes/Sort Functions/DefaultSortFunction.swift | 1 | 2350 | //
// DefaultSortFunction.swift
// Spruce
//
// Copyright (c) 2017 WillowTree, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/// The basic `SortFunction`. Use this sort function if you want to animate in all views at the same time and give an `interObjectDelay` of `0.0`. Note that this `SortFunction` will animate the views based on the order they were added to the animation view. This means that the way the views are sorted in the `subviews` array is the way that they will be sorted by this `SortFunction`.
public struct DefaultSortFunction: SortFunction {
public var interObjectDelay: TimeInterval = 0.0
public init() {
}
public init(interObjectDelay: TimeInterval) {
self.interObjectDelay = interObjectDelay
}
public func timeOffsets(view: UIView, recursiveDepth: Int) -> [TimedView] {
var timedViews: [TimedView] = []
var currentTimeOffset: TimeInterval = 0.0
let subviews = view.spruce.subviews(withRecursiveDepth: recursiveDepth)
for subView in subviews {
let timedView = TimedView(spruceView: subView, timeOffset: currentTimeOffset)
timedViews.append(timedView)
currentTimeOffset += interObjectDelay
}
return timedViews
}
}
| mit | b73cd7914184852c653a2bfc49fc0c51 | 43.339623 | 387 | 0.719574 | 4.501916 | false | false | false | false |
hirohisa/RxSwift | RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift | 15 | 4577 | //
// ConcurrentDispatchQueueScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/5/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public class ConcurrentDispatchQueueScheduler: Scheduler, PeriodicScheduler {
public typealias TimeInterval = NSTimeInterval
public typealias Time = NSDate
private let queue : dispatch_queue_t
public var now : NSDate {
get {
return NSDate()
}
}
// leeway for scheduling timers
var leeway: Int64 = 0
public init(queue: dispatch_queue_t) {
self.queue = queue
}
// Convenience init for scheduler that wraps one of the global concurrent dispatch queues.
//
// DISPATCH_QUEUE_PRIORITY_DEFAULT
// DISPATCH_QUEUE_PRIORITY_HIGH
// DISPATCH_QUEUE_PRIORITY_LOW
public convenience init(globalConcurrentQueuePriority: DispatchQueueSchedulerPriority) {
var priority: Int = 0
switch globalConcurrentQueuePriority {
case .High:
priority = DISPATCH_QUEUE_PRIORITY_HIGH
case .Default:
priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
case .Low:
priority = DISPATCH_QUEUE_PRIORITY_LOW
}
self.init(queue: dispatch_get_global_queue(priority, UInt(0)))
}
class func convertTimeIntervalToDispatchInterval(timeInterval: NSTimeInterval) -> Int64 {
return Int64(timeInterval * Double(NSEC_PER_SEC))
}
class func convertTimeIntervalToDispatchTime(timeInterval: NSTimeInterval) -> dispatch_time_t {
return dispatch_time(DISPATCH_TIME_NOW, convertTimeIntervalToDispatchInterval(timeInterval))
}
public final func schedule<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(state: StateType, action: (/*ImmediateScheduler,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
let cancel = SingleAssignmentDisposable()
dispatch_async(self.queue) {
if cancel.disposed {
return
}
_ = ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in
cancel.disposable = disposable
})
}
return success(cancel)
}
public final func scheduleRelative<StateType>(state: StateType, dueTime: NSTimeInterval, action: (/*Scheduler<NSTimeInterval, NSDate>,*/ StateType) -> RxResult<Disposable>) -> RxResult<Disposable> {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchTime(dueTime)
let compositeDisposable = CompositeDisposable()
dispatch_source_set_timer(timer, dispatchInterval, DISPATCH_TIME_FOREVER, 0)
dispatch_source_set_event_handler(timer, {
if compositeDisposable.disposed {
return
}
ensureScheduledSuccessfully(action(/*self,*/ state).map { disposable in
compositeDisposable.addDisposable(disposable)
})
})
dispatch_resume(timer)
compositeDisposable.addDisposable(AnonymousDisposable {
dispatch_source_cancel(timer)
})
return success(compositeDisposable)
}
public func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> RxResult<Disposable> {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.queue)
let initial = MainScheduler.convertTimeIntervalToDispatchTime(startAfter)
let dispatchInterval = MainScheduler.convertTimeIntervalToDispatchInterval(period)
var timerState = state
let validDispatchInterval = dispatchInterval < 0 ? 0 : UInt64(dispatchInterval)
dispatch_source_set_timer(timer, initial, validDispatchInterval, 0)
let cancel = AnonymousDisposable {
dispatch_source_cancel(timer)
}
dispatch_source_set_event_handler(timer, {
if cancel.disposed {
return
}
timerState = action(timerState)
})
dispatch_resume(timer)
return success(cancel)
}
} | mit | 83b6ce6da500345c353ac577b4b87f33 | 35.624 | 202 | 0.640813 | 5.372066 | false | false | false | false |
idapgroup/IDPDesign | Tests/iOS/Pods/Nimble/Sources/Nimble/Matchers/Contain.swift | 18 | 4041 | import Foundation
/// A Nimble matcher that succeeds when the actual sequence contains the expected value.
public func contain<S: Sequence, T: Equatable>(_ items: T...) -> Predicate<S>
where S.Iterator.Element == T {
return contain(items)
}
public func contain<S: Sequence, T: Equatable>(_ items: [T]) -> Predicate<S>
where S.Iterator.Element == T {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = items.all {
return actual.contains($0)
}
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: String...) -> Predicate<String> {
return contain(substrings)
}
public func contain(_ substrings: [String]) -> Predicate<String> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = substrings.all {
let range = actual.range(of: $0)
return range != nil && !range!.isEmpty
}
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual string contains the expected substring.
public func contain(_ substrings: NSString...) -> Predicate<NSString> {
return contain(substrings)
}
public func contain(_ substrings: [NSString]) -> Predicate<NSString> {
return Predicate.simple("contain <\(arrayAsString(substrings))>") { actualExpression in
if let actual = try actualExpression.evaluate() {
let matches = substrings.all { actual.range(of: $0.description).length != 0 }
return PredicateStatus(bool: matches)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual collection contains the expected object.
public func contain(_ items: Any?...) -> Predicate<NMBContainer> {
return contain(items)
}
public func contain(_ items: [Any?]) -> Predicate<NMBContainer> {
return Predicate.simple("contain <\(arrayAsString(items))>") { actualExpression in
guard let actual = try actualExpression.evaluate() else { return .fail }
let matches = items.all { item in
return item.map { actual.contains($0) } ?? false
}
return PredicateStatus(bool: matches)
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func containMatcher(_ expected: [NSObject]) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let location = actualExpression.location
let actualValue = try actualExpression.evaluate()
if let value = actualValue as? NMBContainer {
let expr = Expression(expression: ({ value as NMBContainer }), location: location)
// A straightforward cast on the array causes this to crash, so we have to cast the individual items
let expectedOptionals: [Any?] = expected.map({ $0 as Any? })
return try contain(expectedOptionals).matches(expr, failureMessage: failureMessage)
} else if let value = actualValue as? NSString {
let expr = Expression(expression: ({ value as String }), location: location)
return try contain(expected as! [String]).matches(expr, failureMessage: failureMessage)
} else if actualValue != nil {
// swiftlint:disable:next line_length
failureMessage.postfixMessage = "contain <\(arrayAsString(expected))> (only works for NSArrays, NSSets, NSHashTables, and NSStrings)"
} else {
failureMessage.postfixMessage = "contain <\(arrayAsString(expected))>"
}
return false
}
}
}
#endif
| bsd-3-clause | 7f8da1cd24eb30093c30e5f84e08408b | 41.536842 | 149 | 0.639693 | 4.898182 | false | false | false | false |
yanagiba/swift-ast | Tests/ParserTests/Expression/Postfix/ParserInitializerExpressionTests.swift | 2 | 3726 | /*
Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import XCTest
@testable import AST
class ParserInitializerExpressionTests: XCTestCase {
func testInitExpression() {
parseExpressionAndTest("foo.init", "foo.init", testClosure: { expr in
guard let initExpr = expr as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression")
return
}
XCTAssertTrue(initExpr.postfixExpression is IdentifierExpression)
XCTAssertTrue(initExpr.argumentNames.isEmpty)
})
}
func testArgumentName() {
parseExpressionAndTest("foo.init(bar:)", "foo.init(bar:)", testClosure: { expr in
guard let initExpr = expr as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression")
return
}
XCTAssertTrue(initExpr.postfixExpression is IdentifierExpression)
ASTTextEqual(initExpr.argumentNames, ["bar"])
})
}
func testUnderscoreAsArgumentName() {
parseExpressionAndTest("foo.init(_:)", "foo.init(_:)", testClosure: { expr in
guard let initExpr = expr as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression")
return
}
XCTAssertTrue(initExpr.postfixExpression is IdentifierExpression)
ASTTextEqual(initExpr.argumentNames, ["_"])
})
}
func testMultipleArgumentNames() {
parseExpressionAndTest("foo . init ( a :b : c:)", "foo.init(a:b:c:)", testClosure: { expr in
guard let initExpr = expr as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression")
return
}
XCTAssertTrue(initExpr.postfixExpression is IdentifierExpression)
ASTTextEqual(initExpr.argumentNames, ["a", "b", "c"])
})
}
func testNestedInitExpression() {
parseExpressionAndTest("foo.init(x:).init(y:)", "foo.init(x:).init(y:)", testClosure: { expr in
guard let outterExpr = expr as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression")
return
}
guard let innerExpr = outterExpr.postfixExpression as? InitializerExpression else {
XCTFail("Failed in getting an initializer expression as inner expr")
return
}
ASTTextEqual(outterExpr.argumentNames, ["y"])
ASTTextEqual(innerExpr.argumentNames, ["x"])
})
}
func testSourceRange() {
let testExprs: [(testString: String, expectedEndColumn: Int)] = [
("foo.init", 9),
("foo.init(bar:)", 15),
("foo.init(a:b:c:)", 17),
]
for t in testExprs {
parseExpressionAndTest(t.testString, t.testString, testClosure: { expr in
XCTAssertEqual(expr.sourceRange, getRange(1, 1, 1, t.expectedEndColumn))
})
}
}
static var allTests = [
("testInitExpression", testInitExpression),
("testArgumentName", testArgumentName),
("testUnderscoreAsArgumentName", testUnderscoreAsArgumentName),
("testMultipleArgumentNames", testMultipleArgumentNames),
("testNestedInitExpression", testNestedInitExpression),
("testSourceRange", testSourceRange),
]
}
| apache-2.0 | c1cfcb25bdac5a513268dfb0aa22b40e | 33.5 | 104 | 0.690553 | 4.928571 | false | true | false | false |
qiscus/qiscus-sdk-ios | Qiscus/Qiscus/Extension/Background.swift | 1 | 1186 | //
// Background.swift
// qonsultant
//
// Created by Ahmad Athaullah on 7/13/16.
// Copyright © 2016 qiscus. All rights reserved.
//
import UIKit
class Background: NSObject {
}
extension CAGradientLayer {
class func gradientLayerForBounds(_ bounds: CGRect, topColor:UIColor, bottomColor:UIColor) -> CAGradientLayer {
let layer = CAGradientLayer()
layer.frame = bounds
layer.colors = [topColor.cgColor, bottomColor.cgColor]
return layer
}
}
extension UINavigationBar {
override public func verticalGradientColor(_ topColor:UIColor, bottomColor:UIColor){
var updatedFrame = self.bounds
// take into account the status bar
updatedFrame.size.height += 20
let layer = CAGradientLayer.gradientLayerForBounds(updatedFrame, topColor: topColor, bottomColor: bottomColor)
UIGraphicsBeginImageContext(layer.bounds.size)
layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.barTintColor = UIColor.clear
self.setBackgroundImage(image, for: UIBarMetrics.default)
}
}
| mit | 412738f28cc32d65c9ac367ae1d1fba3 | 30.184211 | 118 | 0.703797 | 5.042553 | false | false | false | false |
mhdabdulhameed/IOSSW-01-Mohamed | IOSSW-01-Mohamed/LoginViewController.swift | 1 | 2583 | //
// ViewController.swift
// IOSSW-01-Mohamed
//
// Created by Mohamed Abdul-Hameed on 9/15/17.
// Copyright © 2017 Mohamed Abdul-Hameed. All rights reserved.
//
import UIKit
import TwitterKit
class LoginViewController: UIViewController {
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
// Hide navigation bar.
self.navigationController?.setNavigationBarHidden(true, animated: false)
// Create a login button and add it to the center of the view.
self.configureLoginButton()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Show navigation bar.
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
// MARK: - Utility Methods
/**
This methodinitializes a button of type `TWTRLogInButton`, the button will be added to the middle of the screen; tapping on the button will navigate to Twitter's authentication screen.
After entering the username and password, and if they were correct, the authentication screen will be dismissed, and an instance of `FollowersViewController` will be initialized and passed the ID of the logged-in user. In the end, the `FollowersViewController` instance will be pushed to the navigation stack.
*/
fileprivate func configureLoginButton() {
let logInButton = TWTRLogInButton(logInCompletion: { session, error in
if let session = session {
let followersViewController = Utility.initializeViewControllerFromStoryboard(storyboardIdentifier: "Main", viewControllerIdentifier: "followersViewController") as! FollowersViewController
// Pass the logged-in user's ID to `FollowersViewController` instance that's just been created.
followersViewController.userId = session.userID
self.navigationController?.pushViewController(followersViewController, animated: true)
} else {
// A problem occured while trying to log the user in.
Utility.showAlert(title: NSLocalizedString("Error", comment: ""),
message: error!.localizedDescription,
buttonTitle: NSLocalizedString("OK", comment: ""))
}
})
logInButton.center = self.view.center
self.view.addSubview(logInButton)
}
}
| mit | 4504e9ef3680d365415d2abca216c67b | 38.723077 | 314 | 0.642525 | 5.662281 | false | false | false | false |
couchbase/couchbase-lite-ios | Swift/Document.swift | 1 | 9359 | //
// Document.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Couchbase Lite document. The Document is immutable.
public class Document : DictionaryProtocol, Equatable, Hashable, Sequence {
/// The document's ID.
public var id: String {
return impl.id
}
/// The ID representing a document’s revision.
public var revisionID: String? {
return impl.revisionID
}
/// Sequence number of the document in the database.
/// This indicates how recently the document has been changed: every time any document is updated,
/// the database assigns it the next sequential sequence number. Thus, if a document's `sequence`
/// property changes that means it's been changed (on-disk); and if one document's `sequence`
/// is greater than another's, that means it was changed more recently.
public var sequence: UInt64 {
return impl.sequence
}
/// The collection that the document belongs to.
public let collection: Collection?
// MARK: Edit
/// Returns a mutable copy of the document.
///
/// - Returns: The MutableDocument object.
public func toMutable() -> MutableDocument {
return MutableDocument(impl.toMutable())
}
// MARK: DictionaryProtocol
/// The number of properties in the document.
public var count: Int {
return Int(impl.count)
}
/// An array containing all keys, or an empty array if the document has no properties.
public var keys: Array<String> {
return impl.keys
}
/// Gets a property's value. The value types are Blob, ArrayObject,
/// DictionaryObject, Number, or String based on the underlying data type; or nil
/// if the value is nil or the property doesn't exist.
///
/// - Parameter key: The key.
/// - Returns: The value or nil.
public func value(forKey key: String) -> Any? {
return DataConverter.convertGETValue(impl.value(forKey: key))
}
/// Gets a property's value as a string.
/// Returns nil if the property doesn't exist, or its value is not a string.
///
/// - Parameter key: The key.
/// - Returns: The String object or nil.
public func string(forKey key: String) -> String? {
return impl.string(forKey: key)
}
/// Get a property's value as an NSNumber object.
///
/// - Parameter key: The key.
/// - Returns: The NSNumber object.
public func number(forKey key: String) -> NSNumber? {
return impl.number(forKey: key)
}
/// Gets a property's value as an int value.
/// Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
/// Returns 0 if the property doesn't exist or does not have a numeric value.
///
/// - Parameter key: The key.
/// - Returns: The Int value.
public func int(forKey key: String) -> Int {
return impl.integer(forKey: key)
}
/// Gets a property's value as an int64 value.
/// Floating point values will be rounded. The value `true` is returned as 1, `false` as 0.
/// Returns 0 if the property doesn't exist or does not have a numeric value.
///
/// - Parameter key: The key.
/// - Returns: The Int64 value.
public func int64(forKey key: String) -> Int64 {
return impl.longLong(forKey: key)
}
/// Gets a property's value as a float value.
/// Integers will be converted to float. The value `true` is returned as 1.0, `false` as 0.0.
/// Returns 0.0 if the property doesn't exist or does not have a numeric value.
///
/// - Parameter key: The key.
/// - Returns: The Float value.
public func float(forKey key: String) -> Float {
return impl.float(forKey: key)
}
/// Gets a property's value as a double value.
/// Integers will be converted to double. The value `true` is returned as 1.0, `false` as 0.0.
/// Returns 0.0 if the property doesn't exist or does not have a numeric value.
///
/// - Parameter key: The key.
/// - Returns: The Double value.
public func double(forKey key: String) -> Double {
return impl.double(forKey: key)
}
// TODO: Review the behavior of getting boolean value
/// Gets a property's value as a boolean value.
/// Returns true if the value exists, and is either `true` or a nonzero number.
///
/// - Parameter key: The key.
/// - Returns: The Bool value.
public func boolean(forKey key: String) -> Bool {
return impl.boolean(forKey: key)
}
/// Get a property's value as a Blob object.
/// Returns nil if the property doesn't exist, or its value is not a blob.
///
/// - Parameter key: The key.
/// - Returns: The Blob object or nil.
public func blob(forKey key: String) -> Blob? {
return value(forKey: key) as? Blob
}
/// Gets a property's value as a Date value.
/// JSON does not directly support dates, so the actual property value must be a string, which is
/// then parsed according to the ISO-8601 date format (the default used in JSON.)
/// Returns nil if the value doesn't exist, is not a string, or is not parseable as a date.
/// NOTE: This is not a generic date parser! It only recognizes the ISO-8601 format, with or
/// without milliseconds.
///
/// - Parameter key: The key.
/// - Returns: The Date value or nil
public func date(forKey key: String) -> Date? {
return impl.date(forKey: key)
}
/// Get a property's value as a ArrayObject, which is a mapping object of an array value.
/// Returns nil if the property doesn't exists, or its value is not an array.
///
/// - Parameter key: The key.
/// - Returns: The ArrayObject object or nil.
public func array(forKey key: String) -> ArrayObject? {
return value(forKey: key) as? ArrayObject
}
/// Get a property's value as a DictionaryObject, which is a mapping object of
/// a dictionary value.
/// Returns nil if the property doesn't exists, or its value is not a dictionary.
///
/// - Parameter key: The key.
/// - Returns: THe DictionaryObject object or nil.
public func dictionary(forKey key: String) -> DictionaryObject? {
return value(forKey: key) as? DictionaryObject
}
/// Tests whether a property exists or not.
/// This can be less expensive than value(forKey:), because it does not have to allocate an
/// object for the property value.
///
/// - Parameter key: The key.
/// - Returns: True of the property exists, otherwise false.
public func contains(key: String) -> Bool {
return impl.containsValue(forKey: key)
}
// MARK: Data
/// Gets content of the current object as a Dictionary. The value types of
/// the values contained in the returned Dictionary object are Array, Blob,
/// Dictionary, Number types, NSNull, and String.
///
/// - Returns: The Dictionary representing the content of the current object.
public func toDictionary() -> Dictionary<String, Any> {
var dict: [String: Any] = [:]
for key in keys {
let value = self.value(forKey: key)
switch value {
case let v as DictionaryObject:
dict[key] = v.toDictionary()
case let v as ArrayObject:
dict[key] = v.toArray()
default:
dict[key] = value
}
}
return dict
}
// MARK: Sequence
/// Gets an iterator over the keys of the document's properties
///
/// - Returns: The key iterator.
public func makeIterator() -> IndexingIterator<[String]> {
return impl.keys.makeIterator();
}
// MARK: Subscript
/// Subscript access to a Fragment object by key.
///
/// - Parameter key: The key.
public subscript(key: String) -> Fragment {
return Fragment((impl as CBLDictionaryFragment)[key])
}
// MARK: Equality
/// Equal to operator for comparing two Document objects.
public static func == (doc1: Document, doc2: Document) -> Bool {
return doc1.impl == doc2.impl
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(impl.hash)
}
// MARK: toJSON
/// Return document data as JSON String
public func toJSON() -> String {
return impl.toJSON()
}
// MARK: Internal
init(_ impl: CBLDocument, collection: Collection?) {
self.impl = impl
self.collection = collection
}
// MARK: Private
let impl: CBLDocument
}
| apache-2.0 | b117748da06ce6e092c44645743221a1 | 34.044944 | 102 | 0.624773 | 4.368347 | false | false | false | false |
Wakup/Wakup-iOS-SDK | Wakup/CouponDescriptionViewController.swift | 1 | 1225 | //
// CouponDescriptionViewController.swift
// Wuakup
//
// Created by Guillermo Gutiérrez on 25/02/15.
// Copyright (c) 2015 Yellow Pineapple. All rights reserved.
//
import UIKit
class CouponDescriptionViewController: UIViewController {
@IBOutlet weak var descriptionLabel: UITextView!
var descriptionText: String?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
descriptionLabel?.text = descriptionText
view.backgroundColor = UIColor.clear
for view in view.subviews {
view.alpha = 0
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let subviews = view.subviews
let blurView = UIVisualEffectView()
blurView.frame = view.bounds
view.insertSubview(blurView, at: 0)
UIView.animate(withDuration: 0.3) {
for view in subviews {
view.alpha = 1
blurView.effect = UIBlurEffect(style: .dark)
}
}
}
@IBAction func actionButtonTapped(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
| mit | a5817c4ff7150d878a0d817e5cb0ddfe | 25.042553 | 61 | 0.60866 | 5.057851 | false | false | false | false |
marc-medley/004.45macOS_CotEditorSwiftScripting | scripts/02)Tidy/11)Tidy JSON Compact.swift | 1 | 1588 | #!/usr/bin/swift
// %%%{CotEditorXInput=AllText}%%%
// %%%{CotEditorXOutput=ReplaceAllText}%%%
/// Uses MacPorts install of http://www.html-tidy.org/
/// https://github.com/macports/macports-ports/blob/master/www/tidy/Portfile
/// `sudo port install tidy`
import Foundation
var jsonString: String = ""
var i = 0
while true {
let line = readLine(strippingNewline: true)
if line == nil { break }
if line == "" { continue } // `break` or `continue`
if let s = line {
jsonString.append(s)
// uncomment to view input
// print("line[\(i)] \(s)")
i = i + 1
}
}
let xmlData = jsonString.data(using: String.Encoding.utf8)!
if let data: Data = jsonString.data(using: .utf8) {
do {
let jsonInObject = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
let jsonOutData = try JSONSerialization.data(withJSONObject: jsonInObject, options: [])
let jsonOutString = String(data: jsonOutData, encoding: String.Encoding.utf8)!
print(jsonOutString)
}
catch {
print("ERROR: CONVERSION FAILED")
print(jsonString)
}
}
// NOTES:
//
// JSONSerialization.ReadingOptions:
// mutableContainers - arrays and dictionaries are created as mutable objects.
// mutableLeaves - graph leaf strings are created as NSMutableString
// allowFragments - allow top-level objects that are not an instance of NSArray or NSDictionary.
//
// JSONSerialization.ReadingOptions:
// prettyPrinted : add readable white space
// [default] : most compact possible
| mit | 1c3a9ef5a4f0df21a9058d4bc9490909 | 28.407407 | 99 | 0.661209 | 3.90172 | false | false | false | false |
zpz1237/NirTableHeaderView | TableHeaderViewAlbum/TableViewController.swift | 1 | 3211 | //
// TableViewController.swift
// TableHeaderViewAlbum
//
// Created by Nirvana on 10/28/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
//你想要展示的tableHeaderView
let imgView = UIImageView(frame: CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 64))
imgView.contentMode = .ScaleAspectFill
imgView.image = UIImage(named: "header")
//若含有navigationController
//一、取消ScrollViewInsets自动调整
self.automaticallyAdjustsScrollViewInsets = false
//二、隐藏NavBar
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
//类型零
//let headerView = NirTableHeaderView(subview: imgView, andType: 0)
//类型一
//let headerView = NirTableHeaderView(subview: imgView, andType: 1)
//类型二
//let headerView = NirTableHeaderView(subview: imgView, andType: 2)
//类型三
//let headerView = NirTableHeaderView(subview: imgView, andType: 3)
//headerView.tableView = self.tableView
//headerView.maximumOffsetY = -90
//类型四
let headerView = NirTableHeaderView(subview: imgView, andType: 4)
self.tableView.tableHeaderView = headerView
self.tableView.delegate = self
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
// MARK: - Table view delegate
override func scrollViewDidScroll(scrollView: UIScrollView) {
let headerView = self.tableView.tableHeaderView as! NirTableHeaderView
headerView.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 20
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nirCell", forIndexPath: indexPath)
cell.textLabel?.text = "Just Try"
return cell
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
extension UINavigationController {
override public func childViewControllerForStatusBarStyle() -> UIViewController? {
return self.topViewController
}
}
| mit | ba1548140446cf04b9f3e552e632b713 | 33.483516 | 118 | 0.678776 | 5.633752 | false | false | false | false |
SiarheiFedartsou/NSDecimalNumberSwiftExtension | BigNumber/NSDecimalNumberExtension.swift | 1 | 2854 | //
// NSDecimalNumberExtension.swift
// BigNumber
//
// Created by Sergey Fedortsov on 5.6.14.
// Copyright (c) 2014 Sergey Fedortsov. All rights reserved.
//
import Foundation
operator infix ^^ {
}
func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool
{
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
func <=(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool
{
return !(lhs > rhs) || lhs == rhs
}
func >=(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool
{
return lhs > rhs || lhs == rhs
}
func >(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool
{
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool
{
return !(lhs > rhs)
}
@infix func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberByAdding(rhs)
}
@infix func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberBySubtracting(rhs)
}
@infix func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberByMultiplyingBy(rhs)
}
@infix func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberByDividingBy(rhs)
}
@infix func ^^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber
{
return lhs.decimalNumberByRaisingToPower(rhs)
}
@assignment func +=(inout lhs: NSDecimalNumber, rhs: NSDecimalNumber)
{
lhs = lhs.decimalNumberByAdding(rhs)
}
@assignment func -=(inout lhs: NSDecimalNumber, rhs: NSDecimalNumber)
{
lhs = lhs.decimalNumberBySubtracting(rhs)
}
@assignment func *=(inout lhs: NSDecimalNumber, rhs: NSDecimalNumber)
{
lhs = lhs.decimalNumberByMultiplyingBy(rhs)
}
@assignment func /=(inout lhs: NSDecimalNumber, rhs: NSDecimalNumber)
{
lhs = lhs.decimalNumberByDividingBy(rhs)
}
@assignment @prefix func ++(inout lhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberByAdding(NSDecimalNumber.one())
}
@assignment @postfix func ++(inout lhs: NSDecimalNumber) -> NSDecimalNumber
{
let copy : NSDecimalNumber = lhs.copy() as NSDecimalNumber
lhs = lhs.decimalNumberByAdding(NSDecimalNumber.one())
return copy
}
@assignment @prefix func --(inout lhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs.decimalNumberBySubtracting(NSDecimalNumber.one())
}
@assignment @postfix func --(inout lhs: NSDecimalNumber) -> NSDecimalNumber
{
let copy : NSDecimalNumber = lhs.copy() as NSDecimalNumber
lhs = lhs.decimalNumberBySubtracting(NSDecimalNumber.one())
return copy
}
@prefix func -(lhs: NSDecimalNumber) -> NSDecimalNumber
{
let minusOne: NSDecimalNumber = NSDecimalNumber(string: "-1")
return lhs.decimalNumberByMultiplyingBy(minusOne)
}
@prefix func +(lhs: NSDecimalNumber) -> NSDecimalNumber
{
return lhs
}
| mit | b5b38462b85abf9d0061aad78a225f62 | 23.186441 | 76 | 0.7274 | 4.166423 | false | false | false | false |
xmartlabs/XLForm | Examples/Swift/SwiftExample/CustomRows/FloatLabeledTextField/FloatLabeledTextFieldCell.swift | 1 | 5707 | // FloatLabeledTextFieldCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
let XLFormRowDescriptorTypeFloatLabeledTextField = "XLFormRowDescriptorTypeFloatLabeledTextField"
class FloatLabeledTextFieldCell : XLFormBaseCell, UITextFieldDelegate {
static let kFontSize : CGFloat = 16.0
lazy var floatLabeledTextField: JVFloatLabeledTextField = {
let result = JVFloatLabeledTextField(frame: CGRect.zero)
result.translatesAutoresizingMaskIntoConstraints = false
result.font = UIFont.systemFont(ofSize: FloatLabeledTextFieldCell.kFontSize)
result.floatingLabel.font = .boldSystemFont(ofSize: FloatLabeledTextFieldCell.kFontSize)
result.clearButtonMode = .whileEditing
return result
}()
//Mark: - XLFormDescriptorCell
override func configure() {
super.configure()
selectionStyle = .none
contentView.addSubview(self.floatLabeledTextField)
floatLabeledTextField.delegate = self
contentView.addConstraints(layoutConstraints())
}
override func update() {
super.update()
if let rowDescriptor = rowDescriptor {
floatLabeledTextField.attributedPlaceholder = NSAttributedString(string: rowDescriptor.title ?? "" , attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])
if let value = rowDescriptor.value {
floatLabeledTextField.text = (value as AnyObject).displayText()
}
else {
floatLabeledTextField.text = rowDescriptor.noValueDisplayText
}
floatLabeledTextField.isEnabled = !rowDescriptor.isDisabled()
floatLabeledTextField.floatingLabelTextColor = .lightGray
floatLabeledTextField.alpha = rowDescriptor.isDisabled() ? 0.6 : 1.0
}
}
override func formDescriptorCellCanBecomeFirstResponder() -> Bool {
return rowDescriptor?.isDisabled() == false
}
override func formDescriptorCellBecomeFirstResponder() -> Bool {
return self.floatLabeledTextField.becomeFirstResponder()
}
override static func formDescriptorCellHeight(for rowDescriptor: XLFormRowDescriptor!) -> CGFloat {
return 55.0
}
//MARK: Helpers
func layoutConstraints() -> [NSLayoutConstraint]{
let views = ["floatLabeledTextField" : floatLabeledTextField]
let metrics = ["hMargin": 15.0, "vMargin": 8.0]
var result = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(hMargin)-[floatLabeledTextField]-(hMargin)-|", options:.alignAllCenterY, metrics:metrics, views:views)
result += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(vMargin)-[floatLabeledTextField]-(vMargin)-|", options:.alignAllCenterX, metrics:metrics, views:views)
return result
}
func textFieldDidChange(_ textField : UITextField) {
if floatLabeledTextField == textField {
if let rowDescriptor = rowDescriptor, let text = self.floatLabeledTextField.text {
if text.isEmpty == false {
rowDescriptor.value = self.floatLabeledTextField.text
} else {
rowDescriptor.value = nil
}
}
}
}
//Mark: UITextFieldDelegate
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldClear(textField)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldReturn(textField)
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldBeginEditing(textField)
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldEndEditing(textField)
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return self.formViewController().textField(textField, shouldChangeCharactersIn: range, replacementString: string)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.formViewController().textFieldDidBeginEditing(textField)
}
func textFieldDidEndEditing(_ textField: UITextField) {
self.textFieldDidChange(textField)
self.formViewController().textFieldDidEndEditing(textField)
}
}
| mit | e1df2eba6f78768b019eefe5f12cade7 | 39.764286 | 185 | 0.698791 | 5.747231 | false | false | false | false |
timsawtell/SwiftAppStarter | App/Utility/Extensions/UIColorHelper.swift | 1 | 2236 | //
// UIColorExtension.swift
// UIColor-Hex-Swift
//
// Created by R0CKSTAR on 6/13/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
switch (hex.characters.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
print("Scan hex error")
}
} else {
print("Invalid RGB string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
} | mit | fd5a6e5a204d713b17dcf234815d9c8a | 40.425926 | 109 | 0.464669 | 4.050725 | false | false | false | false |
scottrhoyt/Optimize | Optimize/Examples.playground/Contents.swift | 1 | 2577 | //: Playground - noun: a place where people can play
import Foundation
import XCPlayground
import Optimize
func f(x: Double) -> Double {
return 0.25 * pow(x, 4) - pow(x, 3) + pow(x, 2) - 1
//return exp(x)
}
func dfdx(x: Double) -> Double {
return 2*pow(x,3) - 15*pow(x,2) + 2*x - 4
}
let length = 300
let cosine = (0..<length).map({ f(Double($0)/Double(100)) })
for num in cosine {
XCPCaptureValue("cos", value: num)
}
var solver: Solver = NewtonSolver()
//solver.deriv = dfdx
do {
// let results = try solver.solve(10, f: finiteDifference(f, increment: 0.0000001)/*, gradient: dfdx*/)
let results = try solver.solve(10, f: f/*, gradient: dfdx*/)
let results2 = try solver.minMax(10, f: f)
results.result
results.value
results.iterations
}
catch SolverError.MaxIterationsReached(let results) {
print("Max Iter Reached")
results.result
results.value
results.iterations
}
catch SolverError.FunctionChangeBelowTolerance(let results) {
print("Function Change Below Tolerance")
results.result
results.value
results.iterations
}
//Solver.solve(solver)
//public struct NewtonSolver2: Solver {
// public var increment = 0.0000001
// public var maxIter = 100
// public var tolerance: Double
// public var limitTolerance: Double
//
// public init() {
// tolerance = increment
// limitTolerance = tolerance
// }
//
// public func genNextX(x: SolverVar, value: Double, gradient: SolverVar) -> SolverVar {
// return x * gradient
// }
//}
//
//let mySolver2 = NewtonSolver2()
//do {
// let results = try mySolver2.solve(10, f: f/*, gradient: dfdx*/)
// results.result
// results.value
// results.iterations
//}
//catch SolverError.MaxIterationsReached(let results) {
// print("Max Iter Reached")
// results.result
// results.value
// results.iterations
//}
//catch SolverError.FunctionChangeBelowTolerance(let results) {
// print("Function Change Below Tolerance")
// results.result
// results.value
// results.iterations
//}
//func minMax(guess: Double, f:((Double)->Double))-> Double {
// let newFunc = {
// (x: Double) -> Double in
// let increment = 0.00001
// let fx0 = f(x)
// let fx1 = f(x+increment)
// return (fx1 - fx0) / increment
// }
// return solve(guess, f: newFunc)
//}
//
//minMax(170, f: f)
//var a = [1, 2, 3]
//var b = a
//a[1] = 42
//a
//b
//
//var c = [1, 2, 3]
//var d = c
//c.append(42)
//c
//d
//
//var e = [1, 2, 3]
//var f = e
//e[0..<2] = [4, 5]
//e
//f
| mit | 59e6f2ec87ec1bd5bf3d945342648deb | 22.008929 | 110 | 0.614668 | 3.108565 | false | false | false | false |
comyarzaheri/Sol-Swift | Sol/Sol/Classes/Controllers/MainViewController.swift | 1 | 5897 | //
// MainViewController.swift
// Sol
//
// Created by Comyar Zaheri on 6/6/14.
// Copyright (c) 2014 Comyar Zaheri. All rights reserved.
//
import UIKit
import CoreLocation
class MainViewController: UIViewController, UIPageViewControllerDataSource, CLLocationManagerDelegate {
// Constants
let distanceFilter = 3000.0
// Properties
var geocoder: CLGeocoder?
var locationManager: CLLocationManager?
var viewControllers: UIViewController[]?
var settingsViewController: SettingsViewController?
var weatherPageViewController: UIPageViewController?
var addLocationViewController: AddLocationViewController?
init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
commonInit()
}
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nil, bundle: nil)
commonInit()
}
func commonInit() {
self.geocoder = CLGeocoder()
self.viewControllers = UIViewController[]()
self.locationManager = CLLocationManager()
self.locationManager!.activityType = CLActivityType.Other
self.locationManager!.distanceFilter = distanceFilter
self.locationManager!.delegate = self
println("common init")
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager!.requestWhenInUseAuthorization()
initNonlocalWeatherViewControllers()
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse {
println("authorized")
initLocalWeatherViewController()
}
self.weatherPageViewController!.setViewControllers(self.viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
println("location update")
if self.viewControllers!.count > 0 && locations.count > 0 {
let currentLocation = locations[locations.count - 1] as CLLocation
var localWeatherViewController = self.viewControllers![0] as WeatherViewController
self.geocoder!.reverseGeocodeLocation(currentLocation, completionHandler: {(placemarks: AnyObject[]!, error: NSError!) in
if placemarks.count > 0 {
let placemark = placemarks[0] as CLPlacemark
localWeatherViewController.placemark = placemark
localWeatherViewController.update(true)
}
})
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.Authorized || status == CLAuthorizationStatus.AuthorizedWhenInUse {
self.locationManager!.startUpdatingLocation()
initLocalWeatherViewController()
} else if status == CLAuthorizationStatus.Denied || status == CLAuthorizationStatus.Restricted {
let index = indexOfLocalWeatherViewController(self.viewControllers)
if index != NSNotFound {
var viewControllers = self.viewControllers!
viewControllers.removeAtIndex(index)
self.viewControllers = viewControllers
self.weatherPageViewController!.setViewControllers(self.viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
}
}
}
func initNonlocalWeatherViewControllers() {
// get cached state from file
// create weather view controllers
}
func initLocalWeatherViewController() {
let index = indexOfLocalWeatherViewController(self.viewControllers)
if index == NSNotFound {
var localWeatherViewController = WeatherViewController(nibName: nil, bundle: nil)
localWeatherViewController.local = true
var viewControllers: UIViewController[] = self.viewControllers!
viewControllers.insert(localWeatherViewController, atIndex: 0)
self.viewControllers = viewControllers
}
}
func indexOfLocalWeatherViewController(viewControllers: UIViewController[]!) -> Int {
if viewControllers {
for (index, value) in enumerate(self.viewControllers!) {
if value is WeatherViewController {
if (value as? WeatherViewController)!.local {
return index
}
}
}
}
return NSNotFound
}
func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {
return nil
}
func pageViewController(pageViewController: UIPageViewController!, viewControllerAfterViewController viewController: UIViewController!) -> UIViewController! {
return nil
}
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if segue?.identifier == "WeatherPageViewControllerEmbedSegue" {
self.weatherPageViewController = segue!.destinationViewController as? UIPageViewController
self.weatherPageViewController!.dataSource = self
} else if segue?.identifier == "AddLocationViewControllerSegue" {
self.addLocationViewController = segue!.destinationViewController as? AddLocationViewController
} else if segue?.identifier == "SettingsViewControllerSegue" {
self.settingsViewController = segue!.destinationViewController as? SettingsViewController
}
}
}
| mit | e206c6197271ef4f8a7cf65fd7d45ef0 | 41.731884 | 181 | 0.676106 | 6.648253 | false | false | false | false |
DoubleSha/BitcoinSwift | BitcoinSwift/Models/AlertMessage.swift | 1 | 2923 | //
// AlertMessage.swift
// BitcoinSwift
//
// Created by Kevin Greene on 10/10/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: AlertMessage, right: AlertMessage) -> Bool {
return left.alert == right.alert && left.signature == right.signature
}
/// An alert is sent between nodes to send a general notification message throughout the network.
/// If the alert can be confirmed with the signature as having come from the the core development
/// group of the Bitcoin software, the message is suggested to be displayed for end-users.
/// Attempts to perform transactions, particularly automated transactions through the client, are
/// suggested to be halted. The text in the Message string should be relayed to log files and any
/// user interfaces.
/// https://en.bitcoin.it/wiki/Protocol_specification#alert
public struct AlertMessage: Equatable {
public let alert: Alert
public let signature: NSData
private let coreDevPublicKeyBytes: [UInt8] = [
0x04, 0xfc, 0x97, 0x02, 0x84, 0x78, 0x40, 0xaa,
0xf1, 0x95, 0xde, 0x84, 0x42, 0xeb, 0xec, 0xed,
0xf5, 0xb0, 0x95, 0xcd, 0xbb, 0x9b, 0xc7, 0x16,
0xbd, 0xa9, 0x11, 0x09, 0x71, 0xb2, 0x8a, 0x49,
0xe0, 0xea, 0xd8, 0x56, 0x4f, 0xf0, 0xdb, 0x22,
0x20, 0x9e, 0x03, 0x74, 0x78, 0x2c, 0x09, 0x3b,
0xb8, 0x99, 0x69, 0x2d, 0x52, 0x4e, 0x9d, 0x6a,
0x69, 0x56, 0xe7, 0xc5, 0xec, 0xbc, 0xd6, 0x82,
0x84]
public init(alert: Alert, signature: NSData) {
self.alert = alert
self.signature = signature
}
public func isSignatureValid() -> Bool {
// TODO: Actually validate the signature.
return true
}
}
extension AlertMessage: MessagePayload {
public var command: Message.Command {
return Message.Command.Alert
}
public var bitcoinData: NSData {
let data = NSMutableData()
let alertData = alert.bitcoinData
data.appendVarInt(alertData.length)
data.appendData(alertData)
data.appendVarInt(signature.length)
data.appendData(signature)
return data
}
public static func fromBitcoinStream(stream: NSInputStream) -> AlertMessage? {
let alertDataLength = stream.readVarInt()
if alertDataLength == nil {
Logger.warn("Failed to parse alertDataLength from AlertMessage")
return nil
}
let alert = Alert.fromBitcoinStream(stream)
if alert == nil {
Logger.warn("Failed to parse alert from AlertMessage")
return nil
}
let signatureLength = stream.readVarInt()
if signatureLength == nil {
Logger.warn("Failed to parse signatureLength from AlertMessage")
return nil
}
let signature = stream.readData(Int(signatureLength!))
if signature == nil {
Logger.warn("Failed to parse signature from AlertMessage")
return nil
}
// TODO: Validate signature.
return AlertMessage(alert: alert!, signature: signature!)
}
}
| apache-2.0 | 412b44c4ab99369d728ad266e558c5bb | 31.842697 | 97 | 0.69415 | 3.586503 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blogging Reminders/BloggingRemindersTracker.swift | 1 | 4268 | import Foundation
/// Analytics tracker for blogging reminders.
///
class BloggingRemindersTracker {
enum BlogType: String {
case wpcom
case selfHosted = "self_hosted"
}
private enum SharedPropertyName: String {
case blogType = "blog_type"
}
enum Event: String {
// Flow events
case flowCompleted = "blogging_reminders_flow_completed"
case flowDismissed = "blogging_reminders_flow_dismissed"
case flowStart = "blogging_reminders_flow_start"
// Reminders scheduling events
case remindersScheduled = "blogging_reminders_scheduled"
case remindersCancelled = "blogging_reminders_cancelled"
// Misc UI events
case buttonPressed = "blogging_reminders_button_pressed"
case screenShown = "blogging_reminders_screen_shown"
}
enum FlowStartSource: String {
case publishFlow = "publish_flow"
case blogSettings = "blog_settings"
case notificationSettings = "notification_settings"
case statsInsights = "stats_insights"
case bloggingPromptsFeatureIntroduction = "blogging_prompts_onboarding"
}
enum FlowDismissSource: String {
case main
case dayPicker = "day_picker"
case enableNotifications = "enable_notifications"
case timePicker = "time_picker"
}
enum Screen: String {
case main
case dayPicker = "day_picker"
case allSet = "all_set"
case enableNotifications = "enable_notifications"
}
enum Button: String {
case `continue`
case dismiss
case notificationSettings
}
enum Property: String {
case button = "button"
case daysOfWeek = "days_of_week_count"
case source = "source"
case screen = "screen"
case selectedTime = "selected_time"
case state = "state"
}
/// The type of blog.
///
let blogType: BlogType
// MARK: - Initializers
init(blogType: BlogType) {
self.blogType = blogType
}
private func track(_ event: AnalyticsEvent) {
WPAnalytics.track(event)
}
// MARK: - Tracking
func buttonPressed(button: Button, screen: Screen) {
let properties = [
Property.button.rawValue: button.rawValue,
Property.screen.rawValue: screen.rawValue,
]
track(event(.buttonPressed, properties: properties))
}
func flowCompleted() {
track(event(.flowCompleted, properties: [:]))
}
func flowDismissed(source: FlowDismissSource) {
track(event(.flowDismissed, properties: [Property.source.rawValue: source.rawValue]))
}
func flowStarted(source: FlowStartSource) {
track(event(.flowStart, properties: [Property.source.rawValue: source.rawValue]))
}
func scheduled(_ schedule: BloggingRemindersScheduler.Schedule, time: Date) {
let event: AnalyticsEvent
switch schedule {
case .none:
event = self.event(.remindersCancelled, properties: [:])
case .weekdays(let days):
event = self.event(.remindersScheduled,
properties: [Property.daysOfWeek.rawValue: "\(days.count)",
Property.selectedTime.rawValue: time.toLocal24HTime()])
}
track(event)
}
func screenShown(_ screen: Screen) {
track(event(.screenShown, properties: [Property.screen.rawValue: screen.rawValue]))
}
/// Private tracking method, which takes care of composing the tracking payload by adding the shared properties.
///
private func event(_ event: Event, properties: [String: String]) -> AnalyticsEvent {
let finalProperties = sharedProperties().merging(
properties,
uniquingKeysWith: { (first, second) in
return first
})
return AnalyticsEvent(name: event.rawValue, properties: finalProperties)
}
// MARK: - Properties
/// Returns the parameters that should be present for all events tracked by this tracker.
///
private func sharedProperties() -> [String: String] {
[SharedPropertyName.blogType.rawValue: self.blogType.rawValue]
}
}
| gpl-2.0 | e4dc4f39da4690c7d46f9f947f93d56d | 28.846154 | 116 | 0.626757 | 4.784753 | false | false | false | false |
khoren93/SwiftHub | SwiftHub/Common/CollectionViewController.swift | 1 | 1473 | //
// CollectionViewController.swift
// SwiftHub
//
// Created by Khoren Markosyan on 1/4/17.
// Copyright © 2017 Khoren Markosyan. All rights reserved.
//
import UIKit
class CollectionViewController: ViewController {
lazy var collectionView: CollectionView = {
let view = CollectionView()
view.emptyDataSetSource = self
view.emptyDataSetDelegate = self
return view
}()
var clearsSelectionOnViewWillAppear = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if clearsSelectionOnViewWillAppear == true {
deselectSelectedItems()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func makeUI() {
super.makeUI()
stackView.spacing = 0
stackView.insertArrangedSubview(collectionView, at: 0)
}
override func updateUI() {
super.updateUI()
}
}
extension CollectionViewController {
func deselectSelectedItems() {
if let selectedIndexPaths = collectionView.indexPathsForSelectedItems {
selectedIndexPaths.forEach({ (indexPath) in
collectionView.deselectItem(at: indexPath, animated: false)
})
}
}
}
| mit | 973f4f7d3fbeee466bba4524c83f6aa4 | 22.365079 | 79 | 0.647418 | 5.391941 | false | false | false | false |
ciscospark/spark-ios-sdk-example | KitchenSink/UIKitExtension/UIKitExtension.swift | 1 | 4894 | // Copyright 2016-2017 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
extension UIFont {
static let fontFamilyDesc: [UIFontDescriptor.AttributeName:Any] = [UIFontDescriptor.AttributeName.family: "Arial"]
static func buttonLightFont(ofSize size:CGFloat) -> UIFont {
return withWeight(fromDescriptor: UIFontDescriptor(fontAttributes:fontFamilyDesc), weight: .light,size: size)
}
static func labelLightFont(ofSize size:CGFloat) -> UIFont {
return withWeight(fromDescriptor: UIFontDescriptor(fontAttributes:fontFamilyDesc), weight: .light,size: size)
}
static func textViewLightFont(ofSize size:CGFloat) -> UIFont {
return withWeight(fromDescriptor: UIFontDescriptor(fontAttributes:fontFamilyDesc), weight: .light,size: size)
}
static func navigationBoldFont(ofSize size:CGFloat) -> UIFont {
return withWeight(fromDescriptor: UIFontDescriptor(fontAttributes:fontFamilyDesc), weight: .bold,size: size)
}
static private func withWeight(fromDescriptor:UIFontDescriptor, weight: UIFont.Weight, size:CGFloat) -> UIFont {
var attributes = fromDescriptor.fontAttributes
var traits = (attributes[.traits] as? [UIFontDescriptor.TraitKey: Any]) ?? [:]
traits[.weight] = weight
attributes[.traits] = traits
let descriptor = UIFontDescriptor(fontAttributes: attributes)
return UIFont(descriptor: descriptor, size: size)
}
}
extension UIColor {
static func buttonBlueNormal() -> UIColor {
return UIColor.init(red: 7/255.0, green: 193/255.0, blue: 228/255.0, alpha: 1.0)
}
static func buttonBlueHightlight() -> UIColor {
return UIColor.init(red: 6/255.0, green: 177/255.0, blue: 210/255.0, alpha: 1.0)
}
static func labelGreyColor() -> UIColor {
return UIColor.init(red: 106/255.0, green: 107/255.0, blue: 108/255.0, alpha: 1.0)
}
static func labelGreyHightLightColor() -> UIColor {
return UIColor.init(red: 106/255.0, green: 107/255.0, blue: 108/255.0, alpha: 0.2)
}
static func titleGreyColor() -> UIColor {
return UIColor.init(fromRGB: 0x444444,withAlpha:1.0)
}
static func titleGreyLightColor() -> UIColor {
return UIColor.init(fromRGB: 0x444444,withAlpha:0.5)
}
static func buttonGreenNormal() ->UIColor {
return UIColor.init(fromRGB: 0x30D557,withAlpha:1.0)
}
static func buttonGreenHightlight() ->UIColor {
return UIColor.init(fromRGB: 0x30D557,withAlpha:0.5)
}
static func baseRedNormal() ->UIColor {
return UIColor.init(fromRGB: 0xFF513D,withAlpha:1.0)
}
static func baseRedHighlight() ->UIColor {
return UIColor.init(fromRGB: 0xEB4A38,withAlpha:1.0)
}
public convenience init(fromRGB rgbValue: UInt32, withAlpha alpha: CGFloat = 1) {
let r = CGFloat((rgbValue & 0xFF0000) >> 16) / 255
let g = CGFloat((rgbValue & 0x00FF00) >> 8) / 255
let b = CGFloat((rgbValue & 0x0000FF)) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)
}
}
extension UIImage {
static func imageWithColor(_ color:UIColor ,background:UIColor?) -> UIImage? {
let scaledUnti: CGFloat = 1.0/UIScreen.main.scale
let rect: CGRect = CGRect.init(x: 0, y: 0, width: scaledUnti, height: scaledUnti)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
if let backgroundColor = background {
backgroundColor.setFill()
UIRectFillUsingBlendMode(rect, .normal)
}
color.setFill()
UIRectFillUsingBlendMode(rect, .normal)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image?.resizableImage(withCapInsets: .zero)
}
}
| mit | 51c3b48d4783b19570e0f6e989d79785 | 42.309735 | 118 | 0.692072 | 4.28922 | false | false | false | false |
sudeepunnikrishnan/ios-sdk | Instamojo/CardFormView.swift | 1 | 12391 | //
// CardFormView.swift
// Instamojo
//
// Created by Sukanya Raj on 07/02/17.
// Copyright © 2017 Sukanya Raj. All rights reserved.
//
import UIKit
class CardFormView: UIViewController, UITextFieldDelegate, JuspayRequestCallBack {
@IBOutlet weak var payButton: UIButton!
@IBOutlet weak var cvvTextField: UITextField!
@IBOutlet weak var expiryDateTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var cardNumberTextField: UITextField!
@IBOutlet weak var cardImageView: UIImageView!
@IBOutlet var expiryPickerView: MonthYearPickerView!
@IBOutlet var cardNumberErrorLable: UILabel!
@IBOutlet var cardNumberDivider: UIView!
@IBOutlet var nameDivider: UIView!
@IBOutlet var nameErrorLable: UILabel!
@IBOutlet var expiryDateDivider: UIView!
@IBOutlet var expiryDateErrorLable: UILabel!
@IBOutlet var cvvDivider: UIView!
@IBOutlet var cvvErrorLable: UILabel!
var order: Order!
var cardType: Int = 0
var amountToBePayed: Float = 0
var spinner: Spinner!
var textField: UITextField!
var invalidEntries: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
amountToBePayed = Float(order.amount!)!
initUI()
let toolbarDone = UIToolbar.init()
toolbarDone.sizeToFit()
let barBtnDone = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.done,
target: self, action: #selector(CardFormView.doneButton_Clicked(sender:)))
toolbarDone.items = [barBtnDone]
cardNumberTextField.inputAccessoryView = toolbarDone
expiryDateTextField.inputAccessoryView = toolbarDone
expiryDateTextField.inputView = expiryPickerView
expiryPickerView.removeFromSuperview()
expiryPickerView.onDateSelected = { (month: Int, year: Int) in
let date = String(format: Constants.DateFormat, month, year)
self.expiryDateTextField.text = date
}
cvvTextField.inputAccessoryView = toolbarDone
spinner = Spinner(text: Constants.SpinnerText)
spinner.hide()
self.view.addSubview(spinner)
self.textField = cardNumberTextField
}
//Click listener on the Done button on top of the keyboard
@objc func doneButton_Clicked(sender: UIBarButtonItem) {
if cardNumberTextField.isEditing {
cardNumberTextField.resignFirstResponder()
self.textField = nameTextField
nameTextField.becomeFirstResponder()
} else if expiryDateTextField.isEditing {
expiryDateTextField.resignFirstResponder()
self.textField = cvvTextField
cvvTextField.becomeFirstResponder()
} else if cvvTextField.isEditing {
cvvTextField.resignFirstResponder()
}
validateEntries()
}
//Prepare the card object for a juspay request
func prepareCheckOut() {
let cardHolderName = nameTextField.text
let cardNumber = cardNumberTextField.text?.replacingOccurrences(of: " ", with: "")
let expiryDate = expiryDateTextField.text
let cvv = cvvTextField.text
let card = Card(cardHolderName: cardHolderName!, cardNumber: cardNumber!, date: expiryDate!, cvv: cvv!, savedCard: false)
self.checkOutCard(card: card)
}
//A juspay request using Card object
func checkOutCard(card: Card) {
self.textField.resignFirstResponder()
spinner.show()
Logger.logDebug(tag: "Juspay Request", message: "On Pay Clicked")
let request = Request(order: self.order, card: card, jusPayRequestCallBack: self)
request.execute()
}
//Valiated the data entered
func validateEntries() {
let cardNumber = cardNumberTextField?.text
let name = nameTextField?.text
var error: String = ""
if !cardNumberTextField.isEditing {
if (cardNumber?.isEmpty)! {
invalidEntries = true
error = Constants.EmptyCardNumer
cardNumberErrorLable.isHidden = false
cardNumberErrorLable.text = Constants.EmptyCardNumer
cardNumberDivider.backgroundColor = .red
} else {
let isValid = cardNumber?.isValidCardNumber()
if !isValid! {
error = Constants.InvalidCardNumber
cardNumberErrorLable.isHidden = false
cardNumberErrorLable.text = Constants.InvalidCardNumber
cardNumberDivider.backgroundColor = .red
cardNumberTextField.textColor = .red
} else {
cardNumberErrorLable.isHidden = true
cardNumberDivider.backgroundColor = .groupTableViewBackground
cardNumberTextField.textColor = .black
error += ""
}
}
} else {
cardNumberErrorLable.isHidden = true
cardNumberDivider.backgroundColor = .groupTableViewBackground
error += ""
}
if !nameTextField.isEditing {
if (name?.isEmpty)! {
error += Constants.EmptyCardHolderName
nameErrorLable.isHidden = false
nameErrorLable.text = Constants.EmptyCardHolderName
nameDivider.backgroundColor = .red
} else {
nameErrorLable.isHidden = true
nameDivider.backgroundColor = .groupTableViewBackground
error += ""
}
} else {
nameErrorLable.isHidden = true
nameDivider.backgroundColor = .groupTableViewBackground
error += ""
}
if !(name?.isEmpty)! && !(cardNumber?.isEmpty)! {
if !expiryDateTextField.isEditing {
let expiryDate = expiryDateTextField.text
if (expiryDate?.isEmpty)! {
error += Constants.EmptyExpiryDate
expiryDateErrorLable.isHidden = false
expiryDateErrorLable.text = Constants.EmptyExpiryDate
expiryDateDivider.backgroundColor = .red
} else {
expiryDateErrorLable.isHidden = true
expiryDateDivider.backgroundColor = .groupTableViewBackground
}
} else {
expiryDateErrorLable.isHidden = true
expiryDateDivider.backgroundColor = .groupTableViewBackground
error += ""
}
}
if !(name?.isEmpty)! && !(cardNumber?.isEmpty)! {
let cvv = cvvTextField.text
if (cvv?.isEmpty)! {
error += Constants.EmptyCVV
cvvErrorLable.isHidden = false
cvvErrorLable.text = Constants.EmptyCVV
cvvDivider.backgroundColor = .red
} else {
cvvErrorLable.isHidden = true
cvvDivider.backgroundColor = .groupTableViewBackground
error += ""
}
} else {
cvvErrorLable.isHidden = true
cvvDivider.backgroundColor = .groupTableViewBackground
error += ""
}
invalidEntries = !error.isEmpty
}
//To asssing next responder
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameTextField {
self.textField = expiryDateTextField
expiryDateTextField.becomeFirstResponder()
}
validateEntries()
return true
}
//Changed the screen title based on card type selected and updated the pay button title with the amount
func initUI() {
if cardType == Constants.DebitCard {
self.title = Constants.DebitCardTitle
} else if cardType == Constants.CreditCard {
//Default to Credit Card
self.title = Constants.CrediCardTitle
} else {
self.title = Constants.EmiCardTitle
}
payButton.setTitle("Pay " + Constants.Inr + String(amountToBePayed).amountFormatter, for: UIControlState.normal)
}
//validates a card number
func cardNumberDidChange(range: NSRange) -> Bool {
let cardNumber = cardNumberTextField.text?.formattedCardNumber()
do {
let cardType = try CardValidator.cardType(for: (cardNumber)!)
cardImageView.image = UIImage(named : cardType.stringValue(), in: Constants.frameworkBundle, compatibleWith: nil)
let validLength = cardNumber?.validLength()
if (cardNumber?.characters.count)! >= validLength! && range.length == 0 {
cardNumberTextField.resignFirstResponder()
nameTextField.becomeFirstResponder()
return false
} else {
return true
}
} catch {
if cardNumber?.characters.count == 0 {
cardImageView.image = UIImage(named: Constants.AcceptedCards, in: Constants.frameworkBundle, compatibleWith: nil)
return true
} else {
cardImageView.image = UIImage(named: Constants.UnknownCard, in: Constants.frameworkBundle, compatibleWith: nil)
return ((cardNumber?.characters.count)! >= 19 && range.length == 0) ? false : true
}
}
}
//texfield values are validated as and when a character changes
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let characterCount = textField.text?.characters.count
if textField == cardNumberTextField {
//card number validations
if (characterCount!) > 4 {
let numberEntered = cardNumberTextField.text?.formattedCardNumber()
let finalString = numberEntered?.pairs.joined(separator: " ")
cardNumberTextField.text = finalString
return cardNumberDidChange(range: range)
} else {
return true
}
} else if textField == cvvTextField {
//CVV number should not exceed 6 character limit
if characterCount! >= 6 && range.length == 0 {
cvvTextField.resignFirstResponder()
}
return (characterCount! >= 6 && range.length == 0) ? false : true
} else if textField == expiryDateTextField {
if characterCount! >= 5 && range.length == 0 {
expiryDateTextField.resignFirstResponder()
cvvTextField.becomeFirstResponder()
}
return (characterCount! >= 5 && range.length == 0) ? false : true
} else {
return true
}
}
//Call back recieved from juspay request to instamojo
func onFinish(params: BrowserParams, error: String ) {
Logger.logDebug(tag: "Juspay Request", message: "Juspay Request On Finish")
if error.isEmpty {
DispatchQueue.main.async {
let mainStoryboard = Constants.getStoryboardInstance()
if let viewController: PaymentViewController = mainStoryboard.instantiateViewController(withIdentifier: Constants.PaymentOptionsJuspayViewController) as? PaymentViewController {
viewController.params = params
self.navigationController?.pushViewController(viewController, animated: true)
self.spinner.hide()
}
}
} else {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Payment Status", message: "There seems to be some problem. Please choose a different payment options", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(_) in
_ = self.navigationController?.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
//When pay button is clicked
@IBAction func checkout(_ sender: Any) {
validateEntries()
if !(invalidEntries) {
prepareCheckOut()
}
}
}
| lgpl-3.0 | 78f0618933d09494a850d4eb73de056e | 41 | 202 | 0.60678 | 5.849858 | false | false | false | false |
zyanqing/BezierCurve | Bezier曲线/Bezier曲线/BezierView.swift | 1 | 9726 | //
// BezierView.swift
// Bezier曲线
//
// Created by anjubao on 2017/6/1.
// Copyright © 2017年 zhang_yan_qing. All rights reserved.
//
import UIKit
class BezierView: UIView {
/// 数据点
open var pointArray:[CGPoint]?{
didSet{
guard pointViewArray.count == 0 else {
return
}
// 重绘
setNeedsDisplay()
// 添加小圆圈
creatPoint()
creatPointView()
addSubview(tLB)
}
}
let tLB:UILabel = {
let LB = UILabel(frame: CGRect(x: ScreenWith - 70, y: ScreenHeight - 100, width: 60, height: 30))
LB.font = UIFont.systemFont(ofSize: 15.0)
LB.text = "t:0.00"
return LB
}()
/// 描绘进度(0.0 ~ 1.0)
var proportion:CGFloat = 0.0
/// 描绘速率
open var rate:CGFloat = 0.5
/// 定时器
var timer:Timer?
/// 保存控制点
var controlPoints:[CGPoint] = []
/// 判断是否开始绘制贝塞尔曲线
var isDrawBezier = false
/// 判断是否重置数据线
var isResetDataLine = false
/// 判断是否停止画线
var isStop = false
/// 小圆圈数组,删除点的时候使用
var dotArray:[UIView] = []
/// 颜色数组
let colorArray:[CGColor] = [UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor, UIColor.orange.cgColor, UIColor.green.cgColor,UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor, UIColor.orange.cgColor, UIColor.green.cgColor,UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor, UIColor.orange.cgColor, UIColor.green.cgColor,UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor, UIColor.orange.cgColor, UIColor.green.cgColor]
fileprivate var pointViewArray:[UIView] = []
override func draw(_ rect: CGRect) {
guard pointArray != nil else {
return
}
// 绘制初始曲线
let ctx = UIGraphicsGetCurrentContext()
ctx?.addLines(between: pointArray!)
ctx?.strokePath()
if isDrawBezier {
drawLines(ctx: ctx!)
}
// 画完曲线后由于颜色不对需要重绘
if isResetDataLine {
isResetDataLine = false
ctx?.addLines(between: controlPoints) // 重绘曲线
ctx?.setStrokeColor(UIColor.red.cgColor)
ctx?.strokePath()
controlPoints.removeAll() // 清空控制点
}
}
}
// MARK: - 画线相关
extension BezierView {
// MARK: - 批量画线
fileprivate func drawLines(ctx:CGContext) {
if pointArray?.count == 1 {
return
}
var pointArr:[CGPoint] = pointArray!
repeat {
pointArr = calculateCoordinates(pointArray: pointArr)
ctx.addLines(between: pointArr)
ctx.setStrokeColor(colorArray[pointArr.count])
ctx.strokePath()
// 遍历,画小圆
for center in pointArr {
ctx.addArc(center: center, radius: 3, startAngle: 0, endAngle: CGFloat(M_2_PI), clockwise: true)
ctx.setFillColor(colorArray[pointArr.count])
ctx.fillPath()
}
} while pointArr.count != 1
controlPoints.append(pointArr.first!)
ctx.addLines(between: controlPoints)
ctx.setStrokeColor(UIColor.red.cgColor)
ctx.strokePath()
}
}
// MARK: - 计算控制点
extension BezierView {
// MARK: - 计算新的数据点
fileprivate func calculateCoordinates(pointArray:[CGPoint]) -> [CGPoint] {
var newPointArray:[CGPoint] = []
for i in 0..<(pointArray.count - 1) {
let newPoint = calculateBetweenPoint(pointOne: pointArray[i], pointTwo: pointArray[i+1])
newPointArray.append(newPoint)
}
return newPointArray
}
// MARK: 计算一阶贝塞尔曲线(向量方向为:pointOne -> pointTwo)
fileprivate func calculateBetweenPoint(pointOne:CGPoint, pointTwo:CGPoint) -> CGPoint{
let x = pointOne.x * (1 - proportion) + pointTwo.x * proportion
let y = pointOne.y * (1 - proportion) + pointTwo.y * proportion
return CGPoint(x:x, y:y)
}
// MARK: - 添加数据点
open func addPoint(point:CGPoint){
pointArray?.append(point)
for subview in subviews {
subview.removeFromSuperview()
}
setNeedsDisplay()
// 添加小圆圈
creatPoint()
creatPointView()
}
// MARK: - 删除数据点
open func delPoint(){
if pointArray?.count == 0 {
return
}
pointViewArray.last?.removeFromSuperview()
dotArray.last?.removeFromSuperview()
pointArray?.removeLast()
pointViewArray.removeLast()
dotArray.removeLast()
setNeedsDisplay()
}
}
// MARK: - 计时相关
extension BezierView {
/// 开启定时器
open func startTimer() {
if isStop == false {
proportion = 0.0
isDrawBezier = true
}
timer = Timer(timeInterval: 0.001, target: self, selector:#selector(reduced) , userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode:RunLoopMode.commonModes)
}
/// 停止画线
open func stopDrawBezier(){
isStop = true
timer?.invalidate()
}
/// 移除定时器
fileprivate func removeTimer() {
isDrawBezier = false
isStop = false
isResetDataLine = true
setNeedsDisplay()
timer?.invalidate()
}
@objc fileprivate func reduced() {
guard Int(proportion) != 1 else {
removeTimer()
return
}
proportion = proportion + 0.01 - (1 - rate) * 0.01
tLB.text = "t:" + String(format:"%.2f",proportion)
setNeedsDisplay()
}
}
// MARK: - 小圆圈相关
extension BezierView {
// MARK: - 创建小圆圈
fileprivate func creatPoint(){
for i in 0..<(pointArray?.count)! {
let center = (pointArray?[i])!
// 用于移动初始数据点
let rectangleVeiw = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
rectangleVeiw.isUserInteractionEnabled = true
rectangleVeiw.tag = i
// 定义小圆圈 (仅显示)
let dot = UIView(frame: CGRect(x: 10, y: 10, width: 10, height: 10))
dot.layer.cornerRadius = 5
dot.layer.borderWidth = 1
dot.layer.borderColor = UIColor.lightGray.cgColor
dot.isUserInteractionEnabled = true
// 添加圆圈标记 (仅显示)
let textLB = UILabel(frame: CGRect(x: 10, y: 0, width: 20, height: 10))
textLB.text = "P" + String(i)
textLB.font = UIFont.systemFont(ofSize: 10.0)
dot.addSubview(textLB)
rectangleVeiw.addSubview(dot)
addSubview(rectangleVeiw)
rectangleVeiw.center = center
dotArray.append(rectangleVeiw)
// 添加手势
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(movePoint(gesture:)))
longPressGesture.minimumPressDuration = 0.1
rectangleVeiw.addGestureRecognizer(longPressGesture)
}
}
// MARK: - 监听手势改变小圆圈坐标
@objc fileprivate func movePoint(gesture:UIGestureRecognizer) {
guard isDrawBezier == false else {
return
}
switch gesture.state {
case .changed:
// 改变center
gesture.view?.center = gesture.location(in: self)
pointArray?.remove(at: (gesture.view?.tag)!)
pointArray?.insert(gesture.location(in: self), at:(gesture.view?.tag)!)
refreshPointView() // 刷新坐标
setNeedsDisplay() // 重绘视图
default:
return
}
}
// MARK: - 刷新坐标视图
fileprivate func refreshPointView(){
for i in 0..<(pointArray?.count)! {
let point = (pointArray?[i])!
let pointLB = pointViewArray[i] as! UILabel
pointLB.text = "P" + String(i) + "(\(point.x),\(point.y))"
pointLB.font = UIFont.systemFont(ofSize: 13.0)
}
}
// MARK: - 创建坐标视图
fileprivate func creatPointView(){
let height = 30
pointViewArray.removeAll()
for i in 0..<(pointArray?.count)! {
let point = (pointArray?[i])!
// 添加圆圈标记
let pointLB = UILabel(frame: CGRect(x: 10, y: Int(ScreenHeight - CGFloat(110 + i*height)), width: 120, height: height))
pointLB.text = "P" + String(i) + "(\(point.x),\(point.y))"
pointLB.font = UIFont.systemFont(ofSize: 13.0)
pointViewArray.append(pointLB)
addSubview(pointLB)
}
}
}
| apache-2.0 | 9e22fc2e559beab0f911679c370986e6 | 24.575 | 484 | 0.523949 | 4.673604 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/subView/view/FoodCourseCommentCell.swift | 1 | 1327 | //
// FoodCourseCommentCell.swift
// zhangchu
//
// Created by 苏宁 on 2016/11/4.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class FoodCourseCommentCell: UITableViewCell {
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBAction func btnClick(sender: UIButton) {
}
var model:FoodCourseCommentDataData? {
didSet{
if model != nil
{
//
imgView.kf_setImageWithURL(NSURL(string: (model?.head_img)!), placeholderImage: UIImage(named: "sdefaultImage"))
//
nameLabel.text = model?.nick
//
commentLabel.text = model?.content
//
timeLabel.text = model?.create_time
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
imgView.layer.cornerRadius = 30
imgView.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | c3fe6ce7ec6025b62c3093b199d62d89 | 23.444444 | 128 | 0.569697 | 5 | false | false | false | false |
FreddyZeng/Charts | ChartsDemo-iOS/Swift/Demos/LineChartTimeViewController.swift | 1 | 5646 | //
// LineChartTimeViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class LineChartTimeViewController: DemoBaseViewController {
@IBOutlet var chartView: LineChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderTextX: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Line Chart 2"
self.options = [.toggleValues,
.toggleFilled,
.toggleCircles,
.toggleCubic,
.toggleHorizontalCubic,
.toggleStepped,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.pinchZoomEnabled = false
chartView.highlightPerDragEnabled = true
chartView.backgroundColor = .white
chartView.legend.enabled = false
let xAxis = chartView.xAxis
xAxis.labelPosition = .topInside
xAxis.labelFont = .systemFont(ofSize: 10, weight: .light)
xAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1)
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = true
xAxis.centerAxisLabelsEnabled = true
xAxis.granularity = 3600
xAxis.valueFormatter = DateValueFormatter()
let leftAxis = chartView.leftAxis
leftAxis.labelPosition = .insideChart
leftAxis.labelFont = .systemFont(ofSize: 12, weight: .light)
leftAxis.drawGridLinesEnabled = true
leftAxis.granularityEnabled = true
leftAxis.axisMinimum = 0
leftAxis.axisMaximum = 170
leftAxis.yOffset = -9
leftAxis.labelTextColor = UIColor(red: 255/255, green: 192/255, blue: 56/255, alpha: 1)
chartView.rightAxis.enabled = false
chartView.legend.form = .line
sliderX.value = 100
slidersValueChanged(nil)
chartView.animate(xAxisDuration: 2.5)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value), range: 30)
}
func setDataCount(_ count: Int, range: UInt32) {
let now = Date().timeIntervalSince1970
let hourSeconds: TimeInterval = 3600
let from = now - (Double(count) / 2) * hourSeconds
let to = now + (Double(count) / 2) * hourSeconds
let values = stride(from: from, to: to, by: hourSeconds).map { (x) -> ChartDataEntry in
let y = arc4random_uniform(range) + 50
return ChartDataEntry(x: x, y: Double(y))
}
let set1 = LineChartDataSet(values: values, label: "DataSet 1")
set1.axisDependency = .left
set1.setColor(UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1))
set1.lineWidth = 1.5
set1.drawCirclesEnabled = false
set1.drawValuesEnabled = false
set1.fillAlpha = 0.26
set1.fillColor = UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)
set1.highlightColor = UIColor(red: 244/255, green: 117/255, blue: 117/255, alpha: 1)
set1.drawCircleHoleEnabled = false
let data = LineChartData(dataSet: set1)
data.setValueTextColor(.white)
data.setValueFont(.systemFont(ofSize: 9, weight: .light))
chartView.data = data
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleFilled:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawFilledEnabled = !set.drawFilledEnabled
}
chartView.setNeedsDisplay()
case .toggleCircles:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.drawCirclesEnabled = !set.drawCirclesEnabled
}
chartView.setNeedsDisplay()
case .toggleCubic:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier
}
chartView.setNeedsDisplay()
case .toggleStepped:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .stepped) ? .linear : .stepped
}
chartView.setNeedsDisplay()
case .toggleHorizontalCubic:
for set in chartView.data!.dataSets as! [LineChartDataSet] {
set.mode = (set.mode == .cubicBezier) ? .horizontalBezier : .cubicBezier
}
chartView.setNeedsDisplay()
default:
super.handleOption(option, forChartView: chartView)
}
}
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
self.updateChartData()
}
}
| apache-2.0 | acd0cacff6ad34e2cc1eaa760e9a1241 | 34.062112 | 95 | 0.568645 | 5.040179 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | Pods/ImageViewer/ImageViewer/Source/GallerySwipeToDismissTransition.swift | 1 | 2429 | //
// GallerySwipeToDismissTransition.swift
// ImageViewer
//
// Created by Kristian Angyal on 03/03/2016.
// Copyright © 2016 MailOnline. All rights reserved.
//
import UIKit
enum SwipeToDismiss {
case horizontal
case vertical
}
final class GallerySwipeToDismissTransition {
fileprivate weak var scrollView : UIScrollView?
init(scrollView: UIScrollView?) {
self.scrollView = scrollView
}
func updateInteractiveTransition(horizontalOffset hOffset: CGFloat = 0, verticalOffset vOffset: CGFloat = 0) {
scrollView?.setContentOffset(CGPoint(x: hOffset, y: vOffset), animated: false)
}
func finishInteractiveTransition(_ swipeDirection: SwipeToDismiss, touchPoint: CGFloat, targetOffset: CGFloat, escapeVelocity: CGFloat, completion: (() -> Void)?) {
/// In units of "vertical velocity". for example if we have a vertical velocity of 50 units (which are points really) per second
/// and the distance to travel is 175 units, then our spring velocity is 3.5. I.e. we will travel 3.5 units in 1 second.
let springVelocity = fabs(escapeVelocity / (targetOffset - touchPoint))
/// How much time it will take to travel the remaining distance given the above speed.
let expectedDuration = TimeInterval( fabs(targetOffset - touchPoint) / fabs(escapeVelocity))
UIView.animate(withDuration: expectedDuration * 0.65, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: springVelocity, options: UIViewAnimationOptions.curveLinear, animations: { [weak self] () -> Void in
switch swipeDirection {
case .horizontal: self?.scrollView?.setContentOffset(CGPoint(x: targetOffset, y: 0), animated: false)
case .vertical: self?.scrollView?.setContentOffset(CGPoint(x: 0, y: targetOffset), animated: false)
}
}, completion: { (finished) -> Void in
completion?()
})
}
func cancelTransition(_ completion: (() -> Void)? = {}) {
UIView.animate(withDuration: 0.2, delay: 0, options: .curveLinear, animations: { [weak self] () -> Void in
self?.scrollView?.setContentOffset(CGPoint.zero, animated: false)
}) { finished in
completion?()
}
}
}
| mit | 95f0aa9afbc063488421964abca4b477 | 36.9375 | 224 | 0.633855 | 5.10084 | false | false | false | false |
brightify/Bond | Bond/iOS/Bond+UIImageView.swift | 1 | 1930 | //
// Bond+UIImageView.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
var imageDynamicHandleUIImageView: UInt8 = 0;
extension UIImageView: Bondable {
public var dynImage: Dynamic<UIImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageDynamicHandleUIImageView) {
return (d as? Dynamic<UIImage?>)!
} else {
let d = InternalDynamic<UIImage?>(self.image)
let bond = Bond<UIImage?>() { [weak self] v in if let s = self { s.image = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageDynamicHandleUIImageView, d, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var designatedBond: Bond<UIImage?> {
return self.dynImage.valueBond
}
}
| mit | 35ff3db7f8538e897a51f3a7aba806c6 | 38.387755 | 107 | 0.718135 | 4.123932 | false | false | false | false |
marty-suzuki/QiitaApiClient | QiitaApiClient/Model/QiitaExpandedTemplate.swift | 1 | 884 | //
// QiitaExpandedTemplate.swift
// QiitaApiClient
//
// Created by Taiki Suzuki on 2016/08/21.
//
//
import Foundation
public class QiitaExpandedTemplate: QiitaModel {
public let expandedBody: String
public let expandedTags: [QiitaTagging]
public let expandedTitle: String
public required init?(dictionary: [String : NSObject]) {
guard
let expandedBody = dictionary["expanded_body"] as? String,
let rawExpandedTags = dictionary["expanded_tags"] as? [[String : NSObject]],
let expandedTitle = dictionary["expanded_title"] as? String
else {
return nil
}
self.expandedBody = expandedBody
let expandedTags: [QiitaTagging] = rawExpandedTags.flatMap { QiitaTagging(dictionary: $0) }
self.expandedTags = expandedTags
self.expandedTitle = expandedTitle
}
} | mit | c6a6508d3d4bdffadc0a4ea7b1500aed | 29.517241 | 99 | 0.658371 | 4.48731 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.