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
nahive/SnapKit-Keyboard
KeyboardConstraints.swift
1
4518
// // KeyboardConstraints.swift // snapkitkeyboard // // Created by Szymon Maślanka on 03/01/2017. // Copyright © 2017 Szymon Maślanka. All rights reserved. // import UIKit import SnapKit extension ConstraintMakerEditable { @discardableResult func keyboard(_ shown: Bool, in view: UIView) -> ConstraintMakerEditable { switch view.traitCollection.verticalSizeClass { case .regular: if shown { view.shownRegularConstraints.append(constraint) } else { view.hiddenRegularConstraints.append(constraint) } case .compact: if shown { view.shownCompactConstraints.append(constraint) } else { view.hiddenCompactConstraints.append(constraint) } case .unspecified: break } return self } } private var ckmShownRegular: UInt8 = 0 private var ckmShownCompact: UInt8 = 1 private var ckmHiddenRegular: UInt8 = 2 private var ckmHiddenCompact: UInt8 = 3 extension UIView { fileprivate var shownRegularConstraints: [Constraint]! { get { return objc_getAssociatedObject(self, &ckmShownRegular) as? [Constraint] ?? [Constraint]() } set(newValue) { objc_setAssociatedObject(self, &ckmShownRegular, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } fileprivate var shownCompactConstraints: [Constraint]! { get { return objc_getAssociatedObject(self, &ckmShownCompact) as? [Constraint] ?? [Constraint]() } set(newValue) { objc_setAssociatedObject(self, &ckmShownCompact, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } fileprivate var hiddenRegularConstraints: [Constraint]! { get { return objc_getAssociatedObject(self, &ckmHiddenRegular) as? [Constraint] ?? [Constraint]() } set(newValue) { objc_setAssociatedObject(self, &ckmHiddenRegular, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } fileprivate var hiddenCompactConstraints: [Constraint]! { get { return objc_getAssociatedObject(self, &ckmHiddenCompact) as? [Constraint] ?? [Constraint]() } set(newValue) { objc_setAssociatedObject(self, &ckmHiddenCompact, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } @objc private dynamic func keyboardWillShow(notification: Notification) { let duration = (notification as NSNotification).userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval let option = (notification as NSNotification).userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber switch traitCollection.verticalSizeClass { case .regular: hiddenRegularConstraints.forEach { $0.deactivate() } shownRegularConstraints.forEach { $0.activate() } case .compact: hiddenCompactConstraints.forEach { $0.deactivate() } shownCompactConstraints.forEach { $0.activate() } case .unspecified: break } UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: option.uintValue), animations: { self.layoutIfNeeded() }, completion: nil) } @objc private dynamic func keyboardWillHide(notification: Notification) { let duration = (notification as NSNotification).userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval let option = (notification as NSNotification).userInfo![UIResponder.keyboardAnimationCurveUserInfoKey] as! NSNumber switch traitCollection.verticalSizeClass { case .regular: shownRegularConstraints.forEach { $0.deactivate() } hiddenRegularConstraints.forEach { $0.activate() } case .compact: shownCompactConstraints.forEach { $0.deactivate() } hiddenCompactConstraints.forEach { $0.activate() } case .unspecified: break } UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions(rawValue: option.uintValue), animations: { self.layoutIfNeeded() }, completion: nil) } func registerAutomaticKeyboardConstraints() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) } }
unlicense
86c2ea94b142eddc038bb985fa4960b3
45.546392
167
0.702547
4.977949
false
false
false
false
ReactiveKit/Bond
Tests/BondTests/UICollectionViewTests.swift
3
4081
// // UITableViewTests.swift // Bond // // Created by Srdan Rasic on 22/09/2016. // Copyright © 2016 Swift Bond. All rights reserved. // #if os(iOS) || os(tvOS) import XCTest import ReactiveKit @testable import Bond class TestCollectionView: UICollectionView { var observedEvents: [OrderedCollectionDiff<IndexPath>] = [] override func reloadData() { super.reloadData() observedEvents.append(OrderedCollectionDiff()) } open override func insertSections(_ sections: IndexSet) { super.insertSections(sections) observedEvents.append(OrderedCollectionDiff(inserts: sections.map { [$0] })) } open override func deleteSections(_ sections: IndexSet) { super.deleteSections(sections) observedEvents.append(OrderedCollectionDiff(deletes: sections.map { [$0] })) } open override func reloadSections(_ sections: IndexSet) { super.reloadSections(sections) observedEvents.append(OrderedCollectionDiff(updates: sections.map { [$0] })) } open override func moveSection(_ section: Int, toSection newSection: Int) { super.moveSection(section, toSection: newSection) observedEvents.append(OrderedCollectionDiff(moves: [(from: [section], to: [newSection])])) } open override func insertItems(at indexPaths: [IndexPath]) { super.insertItems(at: indexPaths) observedEvents.append(OrderedCollectionDiff(inserts: indexPaths)) } open override func deleteItems(at indexPaths: [IndexPath]) { super.deleteItems(at: indexPaths) observedEvents.append(OrderedCollectionDiff(deletes: indexPaths)) } open override func reloadItems(at indexPaths: [IndexPath]) { super.reloadItems(at: indexPaths) observedEvents.append(OrderedCollectionDiff(updates: indexPaths)) } open override func moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) { super.moveItem(at: indexPath, to: newIndexPath) observedEvents.append(OrderedCollectionDiff(moves: [(from: indexPath, to: newIndexPath)])) } } class UICollectionViewTests: XCTestCase { var array: MutableObservableArray<Int>! var collectionView: TestCollectionView! override func setUp() { array = MutableObservableArray([1, 2, 3]) collectionView = TestCollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 1000), collectionViewLayout: UICollectionViewFlowLayout()) array.bind(to: collectionView, cellType: UICollectionViewCell.self) { _, _ in } } func testInsertItems() { array.insert(4, at: 1) XCTAssert(collectionView.observedEvents == [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(inserts: [IndexPath(row: 1, section: 0)])]) } func testDeleteItems() { let _ = array.remove(at: 2) XCTAssert(collectionView.observedEvents == [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(deletes: [IndexPath(row: 2, section: 0)])]) } func testReloadItems() { array[2] = 5 XCTAssert(collectionView.observedEvents == [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(updates: [IndexPath(row: 2, section: 0)])]) } func testMoveRow() { array.move(from: 1, to: 2) XCTAssert(collectionView.observedEvents == [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(moves: [(from: IndexPath(row: 1, section: 0), to: IndexPath(row: 2, section: 0))])]) } func testBatchUpdates() { array.batchUpdate { (array) in array.insert(0, at: 0) array.insert(1, at: 0) } let possibleResultA = [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(inserts: [IndexPath(row: 1, section: 0), IndexPath(row: 0, section: 0)])] let possibleResultB = [OrderedCollectionDiff(), OrderedCollectionDiff<IndexPath>(inserts: [IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0)])] XCTAssert(collectionView.observedEvents == possibleResultA || collectionView.observedEvents == possibleResultB) } } #endif
mit
1431bd81d615abda8b09543441fec680
36.777778
194
0.689461
4.429967
false
true
false
false
google/android-auto-companion-ios
Sources/AndroidAutoConnectedDeviceTransport/TransportSession.swift
1
3336
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import AndroidAutoLogger /// Delegate for processing session events. public protocol TransportSessionDelegate: AnyObject { func session( _: AnyTransportSession, didDiscover: AnyTransportPeripheral, mode: PeripheralScanMode) func session( _: AnyTransportSession, peripheral: AnyTransportPeripheral, didChangeStateTo: PeripheralStatus ) } /// Encapsulates for a single transport, the lifecycle of peripherals including discovery, /// association and connection. public class TransportSession<Provider: TransportPeripheralProvider> { public typealias Peripheral = Provider.Peripheral private let log = Logger(for: TransportSession.self) /// Monitor for peripheral discovery. private var peripheralDiscoveryMonitor: PeripheralActivityMonitor? /// Delegate for handling session events. private var delegate: TransportSessionDelegate? = nil /// Provider of the transport layer. public let provider: Provider /// All peripherals. @Locked var peripherals: Set<Peripheral> = [] public var discoveredPeripherals: [Peripheral] { peripherals.filter { if case .discovered = $0.status { return true } else { return false } } } public init(provider: Provider, delegate: TransportSessionDelegate? = nil) { self.provider = provider self.delegate = delegate } /// Begin scanning for peripherals. /// /// - Parameter mode: Scan mode (association or reconnection) for which to scan peripherals. public func scanForPeripherals( mode: PeripheralScanMode, discoveryHandler: @escaping (Peripheral, Peripheral.DiscoveryContext?) -> Void ) { stopScanningForPeripherals() clearDiscoveredPeripherals() peripheralDiscoveryMonitor = provider.scanForPeripherals(mode: mode) { [weak self] (peripheral, context) in guard let self = self else { return } self.peripherals.insert(peripheral) peripheral.onStatusChange = { state in self.onPeripheralStatusChange(peripheral, state: state) } discoveryHandler(peripheral, context) self.delegate?.session(self, didDiscover: peripheral, mode: mode) } } /// Stop scanning for peripherals. public func stopScanningForPeripherals() { peripheralDiscoveryMonitor?.cancel() } private func clearDiscoveredPeripherals() { peripherals.subtract(Set(discoveredPeripherals)) } private func onPeripheralStatusChange(_ peripheral: Peripheral, state: PeripheralStatus) { delegate?.session(self, peripheral: peripheral, didChangeStateTo: state) } } /// Conformance for any transport session. public protocol AnyTransportSession {} /// Specify transport session conformance. extension TransportSession: AnyTransportSession {}
apache-2.0
4da1ef0f4a456a64949f7585329e7d49
31.076923
94
0.738609
4.8418
false
false
false
false
peferron/algo
EPI/Hash Tables/Find the smallest subarray covering all values/swift/main.swift
1
1450
public func digest(article: [String], search: Set<String>) -> Range<Int>? { var bestRange: Range<Int>? var currentRangeStart = 0 var currentRangeEnd = 0 var currentSearchCounts = [String: Int]() while true { if currentSearchCounts.count < search.count { // The current range is missing some search words. Increment the end index to try to // include all search words. if currentRangeEnd == article.count { break } let incomingWord = article[currentRangeEnd] currentRangeEnd += 1 if search.contains(incomingWord) { currentSearchCounts[incomingWord] = (currentSearchCounts[incomingWord] ?? 0) + 1 } } else { // The current range contains all search words. Increment the start index to try to // reduce the range count. if bestRange == nil || currentRangeEnd - currentRangeStart < bestRange!.count { bestRange = currentRangeStart..<currentRangeEnd } let outgoingWord = article[currentRangeStart] currentRangeStart += 1 if let count = currentSearchCounts[outgoingWord], count > 1 { currentSearchCounts[outgoingWord] = count - 1 } else { currentSearchCounts.removeValue(forKey: outgoingWord) } } } return bestRange }
mit
2b447bc0b7259ba25c98c4f0ccd6edab
39.277778
96
0.588276
5.197133
false
false
false
false
rusty1s/RSScene
Example/Example/GameController.swift
1
617
// // GameController.swift // Example // // Created by Matthias Fey on 28.07.15. // Copyright © 2015 Matthias Fey. All rights reserved. // import UIKit import SpriteKit class GameController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let skView = self.view as! SKView let scene = GameScene(size: view.bounds.size) skView.showsFPS = true scene.showsTPS = true scene.scaleMode = .AspectFill skView.presentScene(scene) } override func prefersStatusBarHidden() -> Bool { return true } }
mit
f7f6ae3bcf481aba241b5f6796568596
19.533333
55
0.625
4.431655
false
false
false
false
sharath-cliqz/browser-ios
Extensions/ShareTo/ShareViewController.swift
2
11209
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import Storage struct ShareDestination { let code: String let name: String let image: String } // TODO: See if we can do this with an Enum instead. Previous attempts failed because for example NSSet does not take (string) enum values. let ShareDestinationBookmarks: String = "Bookmarks" let ShareDestinationReadingList: String = "ReadingList" let ShareDestinations = [ ShareDestination(code: ShareDestinationReadingList, name: NSLocalizedString("Add to Reading List", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your reading list"), image: "AddToReadingList"), ShareDestination(code: ShareDestinationBookmarks, name: NSLocalizedString("Add to Bookmarks", tableName: "ShareTo", comment: "On/off toggle to select adding this url to your bookmarks"), image: "AddToBookmarks") ] protocol ShareControllerDelegate { func shareControllerDidCancel(_ shareController: ShareDialogController) -> Void func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) -> Void } private struct ShareDialogControllerUX { static let CornerRadius: CGFloat = 4 // Corner radius of the dialog static let NavigationBarTintColor = UIColor(rgb: 0xf37c00) // Tint color changes the text color in the navigation bar static let NavigationBarCancelButtonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize) // System default static let NavigationBarAddButtonFont = UIFont.boldSystemFont(ofSize: UIFont.buttonFontSize) // System default static let NavigationBarIconSize = 38 // Width and height of the icon static let NavigationBarBottomPadding = 12 @available(iOSApplicationExtension 8.2, *) static let ItemTitleFontMedium = UIFont.systemFont(ofSize: 15, weight: UIFontWeightMedium) static let ItemTitleFont = UIFont.systemFont(ofSize: 15) static let ItemTitleMaxNumberOfLines = 2 static let ItemTitleLeftPadding = 44 static let ItemTitleRightPadding = 44 static let ItemTitleBottomPadding = 12 static let ItemLinkFont = UIFont.systemFont(ofSize: 12) static let ItemLinkMaxNumberOfLines = 3 static let ItemLinkLeftPadding = 44 static let ItemLinkRightPadding = 44 static let ItemLinkBottomPadding = 14 static let DividerColor = UIColor.lightGray // Divider between the item and the table with destinations static let DividerHeight = 0.5 static let TableRowHeight: CGFloat = 44 // System default static let TableRowFont = UIFont.systemFont(ofSize: 14) static let TableRowFontMinScale: CGFloat = 0.8 static let TableRowTintColor = UIColor(red:0.427, green:0.800, blue:0.102, alpha:1.0) // Green tint for the checkmark static let TableRowTextColor = UIColor(rgb: 0x555555) static let TableHeight = 88 // Height of 2 standard 44px cells } class ShareDialogController: UIViewController, UITableViewDataSource, UITableViewDelegate { var delegate: ShareControllerDelegate! var item: ShareItem! var initialShareDestinations: NSSet = NSSet(object: ShareDestinationBookmarks) var selectedShareDestinations: NSMutableSet = NSMutableSet() var navBar: UINavigationBar! var navItem: UINavigationItem! override func viewDidLoad() { super.viewDidLoad() selectedShareDestinations = NSMutableSet(set: initialShareDestinations) self.view.backgroundColor = UIColor.white self.view.layer.cornerRadius = ShareDialogControllerUX.CornerRadius self.view.clipsToBounds = true // Setup the NavigationBar navBar = UINavigationBar() navBar.translatesAutoresizingMaskIntoConstraints = false navBar.tintColor = ShareDialogControllerUX.NavigationBarTintColor navBar.isTranslucent = false self.view.addSubview(navBar) // Setup the NavigationItem navItem = UINavigationItem() navItem.leftBarButtonItem = UIBarButtonItem( title: Strings.ShareToCancelButton, style: .Plain, target: self, action: #selector(ShareDialogController.cancel) ) navItem.leftBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarCancelButtonFont], for: UIControlState()) navItem.leftBarButtonItem?.accessibilityIdentifier = "ShareDialogController.navigationItem.leftBarButtonItem" navItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Add", tableName: "ShareTo", comment: "Add button in the share dialog"), style: UIBarButtonItemStyle.done, target: self, action: #selector(ShareDialogController.add)) navItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName: ShareDialogControllerUX.NavigationBarAddButtonFont], for: UIControlState()) let logo = UIImageView(frame: CGRect(x: 0, y: 0, width: ShareDialogControllerUX.NavigationBarIconSize, height: ShareDialogControllerUX.NavigationBarIconSize)) logo.image = UIImage(named: "Icon-Small") logo.contentMode = UIViewContentMode.scaleAspectFit // TODO Can go away if icon is provided in correct size navItem.titleView = logo navBar.pushItem(navItem, animated: false) // Setup the title view let titleView = UILabel() titleView.translatesAutoresizingMaskIntoConstraints = false titleView.numberOfLines = ShareDialogControllerUX.ItemTitleMaxNumberOfLines titleView.lineBreakMode = NSLineBreakMode.byTruncatingTail titleView.text = item.title titleView.font = ShareDialogControllerUX.ItemTitleFontMedium view.addSubview(titleView) // Setup the link view let linkView = UILabel() linkView.translatesAutoresizingMaskIntoConstraints = false linkView.numberOfLines = ShareDialogControllerUX.ItemLinkMaxNumberOfLines linkView.lineBreakMode = NSLineBreakMode.byTruncatingTail linkView.text = item.url linkView.font = ShareDialogControllerUX.ItemLinkFont view.addSubview(linkView) // Setup the icon let iconView = UIImageView() iconView.translatesAutoresizingMaskIntoConstraints = false iconView.image = UIImage(named: "defaultFavicon") view.addSubview(iconView) // Setup the divider let dividerView = UIView() dividerView.translatesAutoresizingMaskIntoConstraints = false dividerView.backgroundColor = ShareDialogControllerUX.DividerColor view.addSubview(dividerView) // Setup the table with destinations let tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.separatorInset = UIEdgeInsets.zero tableView.layoutMargins = UIEdgeInsets.zero tableView.isUserInteractionEnabled = true tableView.delegate = self tableView.allowsSelection = true tableView.dataSource = self tableView.isScrollEnabled = false view.addSubview(tableView) // Setup constraints let views = [ "nav": navBar, "title": titleView, "link": linkView, "icon": iconView, "divider": dividerView, "table": tableView ] // TODO See Bug 1102516 - Use Snappy to define share extension layout constraints let constraints = [ "H:|[nav]|", "V:|[nav]", "H:|-\(ShareDialogControllerUX.ItemTitleLeftPadding)-[title]-\(ShareDialogControllerUX.ItemTitleRightPadding)-|", "V:[nav]-\(ShareDialogControllerUX.NavigationBarBottomPadding)-[title]", "H:|-\(ShareDialogControllerUX.ItemLinkLeftPadding)-[link]-\(ShareDialogControllerUX.ItemLinkLeftPadding)-|", "V:[title]-\(ShareDialogControllerUX.ItemTitleBottomPadding)-[link]", "H:|[divider]|", "V:[divider(\(ShareDialogControllerUX.DividerHeight))]", "V:[link]-\(ShareDialogControllerUX.ItemLinkBottomPadding)-[divider]", "H:|[table]|", "V:[divider][table]", "V:[table(\(ShareDialogControllerUX.TableHeight))]|" ] for constraint in constraints { view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: constraint, options: NSLayoutFormatOptions(), metrics: nil, views: views)) } } // UITabBarItem Actions that map to our delegate methods func cancel() { delegate?.shareControllerDidCancel(self) } func add() { delegate?.shareController(self, didShareItem: item, toDestinations: NSSet(set: selectedShareDestinations)) } // UITableView Delegate and DataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ShareDestinations.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return ShareDialogControllerUX.TableRowHeight } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.darkGray : ShareDialogControllerUX.TableRowTextColor cell.textLabel?.font = ShareDialogControllerUX.TableRowFont cell.accessoryType = selectedShareDestinations.contains(ShareDestinations[indexPath.row].code) ? UITableViewCellAccessoryType.checkmark : UITableViewCellAccessoryType.none cell.tintColor = ShareDialogControllerUX.TableRowTintColor cell.layoutMargins = UIEdgeInsets.zero cell.textLabel?.text = ShareDestinations[indexPath.row].name cell.textLabel?.adjustsFontSizeToFitWidth = true cell.textLabel?.minimumScaleFactor = ShareDialogControllerUX.TableRowFontMinScale cell.imageView?.image = UIImage(named: ShareDestinations[indexPath.row].image) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let code = ShareDestinations[indexPath.row].code if selectedShareDestinations.contains(code) { selectedShareDestinations.remove(code) } else { selectedShareDestinations.add(code) } tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.automatic) navItem.rightBarButtonItem?.isEnabled = (selectedShareDestinations.count != 0) } }
mpl-2.0
db944e0bcdafdde7b3715c71bb5f556a
44.380567
244
0.697832
5.918163
false
false
false
false
zixun/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/ZXURLNavigator/ZXNavigationController.swift
1
3148
// // ZXNavigationController.swift // CocoaChinaPlus // // Created by zixun on 17/1/23. // Copyright © 2017年 zixun. All rights reserved. // import Foundation import AppBaseKit open class ZXNavigationController: UINavigationController { open var enable = true override open func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black // 获取系统自带滑动手势的target对象 let target = self.interactivePopGestureRecognizer!.delegate; // 创建全屏滑动手势,调用系统自带滑动手势的target的action方法 let pan = UIPanGestureRecognizer(target: target, action: Selector("handleNavigationTransition:")) // 设置手势代理,拦截手势触发 pan.delegate = self; // 给导航控制器的view添加全屏滑动手势 self.view.addGestureRecognizer(pan); // 禁止使用系统自带的滑动手势 self.interactivePopGestureRecognizer!.isEnabled = false; let width = UIScreen.main.bounds.size.width let image = UIImage.image(color: UIColor(hex: 0x272626), size: CGSize(width: width, height: 0.5)) let imageView = UIImageView(image: image) self.navigationBar.addSubview(imageView) var rect = self.navigationBar.bounds rect.origin.y = rect.origin.y + rect.size.height - 0.5 rect.size.height = 0.5 imageView.frame = rect } override open func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } } // MARK: UIGestureRecognizerDelegate extension ZXNavigationController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let translation: CGPoint = (gestureRecognizer as! UIPanGestureRecognizer).translation(in: self.view.superview) guard self.enable == true else { return false } if (translation.x < 0) { return false //往右滑返回,往左滑不做操作 } if (self.viewControllers.count <= 1) { return false } return true } } extension UIViewController { public func presentViewController(_ viewControllerToPresent: UIViewController) { self.present(viewControllerToPresent, animated: true, completion: nil) } public func presentViewController(_ viewControllerToPresent: UIViewController,withNavigation:Bool, animated flag: Bool, completion: (() -> Void)?) { if withNavigation == false { self.present(viewControllerToPresent, animated: flag, completion: completion) }else { let nav = ZXNavigationController(rootViewController: viewControllerToPresent) self.present(nav, animated: flag, completion: completion) } } }
mit
f814a7665895dd4b2ec67fa1a9e7bd49
31.944444
152
0.652277
5.033956
false
false
false
false
gcharita/XMLMapper
XMLMapper/Classes/XMLMappable.swift
1
3687
// // XMLMappable.swift // XMLMapper // // Created by Giorgos Charitakis on 14/09/2017. // // /// XMLBaseMappable should not be implemented directly. XMLMappable or XMLStaticMappable should be used instead public protocol XMLBaseMappable { /// This property is where the name of the XML node is being mapped var nodeName: String! { get set } /// This function is where all variable mappings should occur. It is executed by XMLMapper during the mapping (serialization and deserialization) process. mutating func mapping(map: XMLMap) } extension XMLBaseMappable { /// Start mapping by map the XML nodeName first mutating func mapping(with map: XMLMap) { nodeName <- map[XMLParserConstant.Key.nodeName] mapping(map: map) } } public protocol XMLMappable: XMLBaseMappable { /// This function can be used to validate XML prior to mapping. Return nil to cancel mapping at this point init?(map: XMLMap) } public protocol XMLStaticMappable: XMLBaseMappable { /// This is function that can be used to: /// 1) provide an existing cached object to be used for mapping /// 2) return an object of another class (which conforms to XMLBaseMappable) to be used for mapping. For instance, you may inspect the XML to infer the type of object that should be used for any given mapping static func objectForMapping(map: XMLMap) -> XMLBaseMappable? } public extension XMLBaseMappable { /// Initializes object from a XML String init?(XMLString: String) { if let obj: Self = XMLMapper().map(XMLString: XMLString) { self = obj } else { return nil } } /// Initializes object from a XML Dictionary init?(XML: [String: Any]) { if let obj: Self = XMLMapper().map(XML: XML) { self = obj } else { return nil } } /// Returns the XML Dictionary for the object func toXML() -> [String: Any] { return XMLMapper().toXML(self) } /// Returns the XML String for the object func toXMLString() -> String? { return XMLMapper().toXMLString(self) } } public extension Array where Element: XMLBaseMappable { /// Initialize Array from a XML String init?(XMLString: String) { if let obj: [Element] = XMLMapper().mapArray(XMLString: XMLString) { self = obj } else { return nil } } /// Initialize Array from a XML Array init(XMLArray: [[String: Any]]) { let obj: [Element] = XMLMapper().mapArray(XMLArray: XMLArray) self = obj } /// Returns the XML Array func toXML() -> [[String: Any]] { return XMLMapper().toXMLArray(self) } /// Returns the XML String for the object func toXMLString() -> String? { return XMLMapper().toXMLString(self) } } public extension Set where Element: XMLBaseMappable { /// Initializes a set from a XML String init?(XMLString: String) { if let obj: Set<Element> = XMLMapper().mapSet(XMLString: XMLString) { self = obj } else { return nil } } /// Initializes a set from XML init?(XMLArray: [[String: Any]]) { guard let obj = XMLMapper().mapSet(XMLArray: XMLArray) as Set<Element>? else { return nil } self = obj } /// Returns the XML Set func toXML() -> [[String: Any]] { return XMLMapper().toXMLSet(self) } /// Returns the XML String for the object func toXMLString() -> String? { return XMLMapper().toXMLString(self) } }
mit
1bf48702028fd9c3469d6c83e1e39aee
28.733871
219
0.615134
4.307243
false
false
false
false
wjk930726/weibo
weiBo/weiBo/iPhone/Modules/ViewModel/WBStatusViewModel.swift
1
2733
// // WBStatusViewModel.swift // weiBo // // Created by 王靖凯 on 2016/11/29. // Copyright © 2016年 王靖凯. All rights reserved. // import UIKit class WBStatusViewModel: NSObject { var status: WBStatusModel var verifiedType: UIImage? var verifiedLevel: UIImage? var sourceString: String? var timeString: String? var retweetedString: String? var rowHeight: CGFloat = 0 var firstImageSize: CGSize = CGSize.zero var pic_urls: [WBPicUrlsModel]? init(status: WBStatusModel) { self.status = status super.init() getType() getLevel() dealWithSource() dealWithTime() dealWithRetweetedText() calculateRowHeight() } } extension WBStatusViewModel { fileprivate func calculateRowHeight() { if let pics = status.pic_urls { pic_urls = pics } if let pics = status.retweeted_status?.pic_urls { pic_urls = pics } if var height = pic_urls?.count, height != 0 { height = (height - 1) / 3 + 1 let heightf = CGFloat(height) rowHeight = widthHeight * heightf + margin * (heightf - 1.0) } } fileprivate func dealWithRetweetedText() { if let text = status.retweeted_status?.text, text.count > 0, let userName = status.retweeted_status?.user?.screen_name { retweetedString = "@\(userName):\(text)" } } fileprivate func dealWithTime() { guard let sinaTime = status.created_at else { return } let date = Date.dateFromSinaFormat(sinaDateString: sinaTime) timeString = date.requiredTimeString() } fileprivate func getType() { if let type = status.user?.verified_type { switch type { case 0: verifiedType = #imageLiteral(resourceName: "avatar_vip") case 2, 3, 5: verifiedType = #imageLiteral(resourceName: "avatar_enterprise_vip") case 220: verifiedType = #imageLiteral(resourceName: "avatar_grassroot") default: verifiedType = nil } } } fileprivate func getLevel() { if let level = status.user?.verified_level, level <= 7 && level > 0 { verifiedLevel = UIImage(named: "common_icon_membership_level\(level)") } } fileprivate func dealWithSource() { if let count = (status.source?.count), count > 0, let start = status.source?.range(of: "\">")?.upperBound, let end = status.source?.range(of: "</a>")?.lowerBound, let str = status.source { sourceString = String(describing: str[start ..< end]) } } }
mit
14bf368a42510263f505d814ae4d64bb
29.2
196
0.582781
4.362761
false
false
false
false
exponent/exponent
packages/expo-updates/ios/EXUpdates/AppLoader/EXUpdatesSignatureHeaderInfo.swift
2
1770
// Copyright 2015-present 650 Industries. All rights reserved. import Foundation import EXStructuredHeaders @objc public enum EXUpdatesSignatureHeaderInfoError: Int, Error { case MissingSignatureHeader case StructuredFieldParseError case SigMissing } struct EXUpdatesSignatureHeaderFields { static let SignatureFieldKey = "sig" static let KeyIdFieldKey = "keyid" static let AlgorithmFieldKey = "alg" } @objc public class EXUpdatesSignatureHeaderInfo : NSObject { static let DefaultKeyId = "root" var signature: String var keyId: String var algorithm: EXUpdatesCodeSigningAlgorithm @objc public required init(signatureHeader: String?) throws { guard let signatureHeader = signatureHeader else { throw EXUpdatesSignatureHeaderInfoError.MissingSignatureHeader } let parser = EXStructuredHeadersParser.init(rawInput: signatureHeader, fieldType: EXStructuredHeadersParserFieldType.dictionary, ignoringParameters: true) let parserOutput = try parser.parseStructuredFields() guard let parserOutputDictionary = parserOutput as? Dictionary<String, String> else { throw EXUpdatesSignatureHeaderInfoError.StructuredFieldParseError } guard let signatureFieldValue = parserOutputDictionary[EXUpdatesSignatureHeaderFields.SignatureFieldKey] else { throw EXUpdatesSignatureHeaderInfoError.SigMissing } signature = signatureFieldValue keyId = parserOutputDictionary[EXUpdatesSignatureHeaderFields.KeyIdFieldKey] ?? EXUpdatesSignatureHeaderInfo.DefaultKeyId algorithm = try parseCodeSigningAlgorithm(parserOutputDictionary[EXUpdatesSignatureHeaderFields.AlgorithmFieldKey]) } }
bsd-3-clause
ab44ef35c1603616bc4fe3f6837cfe0f
35.875
125
0.758192
5.331325
false
false
false
false
fanyinan/ImagePickerProject
ImagePicker/Tool/Extension.swift
1
1762
// // MuColor.swift // ImagePickerProject // // Created by 范祎楠 on 15/4/9. // Copyright (c) 2015年 范祎楠. All rights reserved. // import UIKit extension UIColor { class var jx_main: UIColor { return UIColor(hex: 0x333333) } class var separatorColor: UIColor { return UIColor(hex: 0xe5e5e5) } convenience init(hex: Int, alpha: CGFloat = 1) { let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green = CGFloat((hex & 0x00FF00) >> 8) / 255.0 let blue = CGFloat((hex & 0x0000FF)) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } /** 随机颜色 - returns: 颜色 */ class func randomColor() -> UIColor{ let hue = CGFloat(arc4random() % 256) / 256.0 let saturation = CGFloat(arc4random() % 128) / 256.0 + 0.5 let brightness : CGFloat = CGFloat(arc4random() % 128) / 256.0 + 0.5 return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1) } } extension UIImage { //旋转rect func transformOrientationRect(_ rect: CGRect) -> CGRect { var rectTransform: CGAffineTransform = CGAffineTransform.identity switch imageOrientation { case .left: rectTransform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)).translatedBy(x: 0, y: -size.height) case .right: rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: 0) case .down: rectTransform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi / 2)).translatedBy(x: -size.width, y: -size.height) default: break } let orientationRect = rect.applying(rectTransform.scaledBy(x: scale, y: scale)) return orientationRect } }
bsd-2-clause
df54ea0719e9fc2b609a5751e955fd18
26.0625
125
0.646651
3.571134
false
false
false
false
lynxerzhang/SwiftUtil
StringExt.swift
1
4543
// // StringExt.swift // TODO import Foundation //@see //https://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial //http://andybargh.com/swift-strings/ //http://chrismontrois.net/2014/08/02/swift-techniques-strings/ extension String { /** 截取字符串 - Parameter startIndex: 起始索引点 - Parameter endIndex: 结束索引点(最终字符串中不会包含该字符) - Returns: 返回指定截取的字符串 */ func slice(startIndex: Int = 0, endIndex: Int = Int.max) -> String { var str = "" var start = startIndex, end = endIndex let count = self.length if start < 0 { if start < -count { start = -count } start += count } if end < 0 { end += count } else if end > count { end = count } if end >= start { let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) str = self[index] } return str } /** 截取字符串 - Parameter startIndex: 起始索引点 - Parameter len: 截取的字符串长度 - Returns: 返回指定截取的字符串 */ func substr(startIndex: Int = 0, len: Int = Int.max) -> String { var str = "" var start = startIndex, end = len let count = self.length if end > count { end = count } if start < 0 { if start < -count { start = -count } start += count } end += start if end > count { end = count } if start < count { let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) str = self[index] } return str } /** 截取字符串 - Parameter startIndex: 起始索引点 - Parameter endIndex: 结束索引点(最终字符串中不会包含该字符) - Returns: 返回指定截取的字符串 */ func substring(startIndex: Int = 0, endIndex: Int = Int.max) -> String { var str = "" var start = startIndex, end = endIndex let count = self.length if start < 0 { start = 0 } if end < 0 { end = 0 } if start > end { let tmp = end end = start start = tmp } if end > count { end = count } if start < count { let index = self.startIndex.advancedBy(start)..<self.startIndex.advancedBy(end) str = self[index] } return str } /** 检查指定索引处的字符 - Parameter index: 字符串中指定的索引值 - Returns: 返回指定位置字符,默认为空字符 */ func charAt(index: Int) -> String { let count = self.length var str = "" //if str is a character, it is Illegal if index >= 0 && index <= count - 1{ let index = self.startIndex.advancedBy(index)..<self.startIndex.advancedBy(index + 1) str = self[index] } return str } /** 是否匹配指定字符串 - Parameter pattern: 正则表达式 */ func isMatch(pattern: String) -> Bool { var isMatch:Bool = false do { let regex = try NSRegularExpression(pattern: pattern, options: [.CaseInsensitive]) let result = regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) if (result != nil){ isMatch = true } } catch { isMatch = false } return isMatch } /** 检索指定字符串 - Parameter val: 待搜索字符串 - Parameter startIndex: 起始搜索索引 - Returns: 返回搜索到的字符串最初索引位置,如没有搜索到返回-1 */ func indexOf(val: String, startIndex: Int = 0) -> Int { var findIndex: Int = -1 let count = self.length var index = startIndex if index < 0 { index = 0 } else if index > count { index = count } do { let regex = try NSRegularExpression(pattern: val, options: [.CaseInsensitive]) let result = regex.rangeOfFirstMatchInString(self, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(index, count - index)) if result.location != NSNotFound { findIndex = result.location } } catch { } return findIndex } /** 前后翻转指定字符串 */ func reverse() -> String { return String(self.characters.reverse()) } /** 获取字符串长度 */ var length: Int { return self.characters.count } }
mit
36a5602450b1e2299d9555756fab66fb
21.701657
99
0.568265
3.82945
false
false
false
false
RobinChao/Hacking-with-Swift
HackingWithSwift-03/HackingWithSwift-03/MasterViewController.swift
1
2416
// // MasterViewController.swift // HackingWithSwift-03 // // Created by Robin on 2/19/16. // Copyright © 2016 Robin. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Load files let fileManager = NSFileManager.defaultManager() let path = NSBundle.mainBundle().resourcePath! let items = try! fileManager.contentsOfDirectoryAtPath(path) for item in items { if item.hasPrefix("nssl") { objects.append(item) } } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] cell.textLabel!.text = object return cell } }
mit
54047cc747ba191e4afb0c2a91d40542
30.363636
136
0.660455
5.763723
false
false
false
false
spreedly/spreedly-ios
Spreedly/Spreedly.swift
1
858
// // Spreedly.swift // Spreedly // // Created by David Santoso on 8/13/19. // Copyright © 2019 Spreedly Inc. All rights reserved. // import Foundation import SwiftyJSON public class Spreedly { public static let instance = Spreedly() var lifecycle: TransactionLifecycle? public init() {} public func threeDsInit(rawThreeDsContext: String) -> TransactionLifecycle { let decodedData = Data(base64Encoded: rawThreeDsContext)! let decodedString = String(data: decodedData, encoding: .utf8)! let threeDsContext = JSON(parseJSON: decodedString) if threeDsContext["gateway_type"] == "adyen" { self.lifecycle = AdyenLifecycle(threeDsContext) } else { self.lifecycle = TransactionLifecycle(threeDsContext) } return lifecycle! } }
mit
329ac3e1a934ac06597b5e7cd30407e2
24.969697
80
0.649942
4.394872
false
false
false
false
frosty/iOSDevUK-StackViews
StackReview/PancakeHouseTableViewCell.swift
6
1812
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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 class PancakeHouseTableViewCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var pancakeImage : UIImageView! @IBOutlet weak var ratingImage: UIImageView! @IBOutlet weak var cityLabel: UILabel! @IBOutlet weak var priceGuideLabel: UILabel! var pancakeHouse : PancakeHouse? { didSet { if let pancakeHouse = pancakeHouse { nameLabel?.text = pancakeHouse.name pancakeImage?.image = pancakeHouse.thumbnail ?? UIImage(named: "placeholder_thumb") ratingImage?.image = pancakeHouse.rating.smallRatingImage cityLabel?.text = pancakeHouse.city priceGuideLabel?.text = "\(pancakeHouse.priceGuide)" } } } }
mit
e042147efa57a31ad0f90ba04d5d8a2b
40.181818
91
0.749448
4.452088
false
false
false
false
drscotthawley/add-menu-popover-demo
PopUpMenuTest/ChooseGearTableViewController.swift
1
1860
// // ChooseGearTableViewController.swift // PopUpMenuTest // // Created by Scott Hawley on 8/31/15. // Copyright © 2015 Scott Hawley. All rights reserved. // import UIKit class ChooseGearTableViewController: UITableViewController { // throw in some dummy data let cellStrings = ["Desktop", "LA-2A", "Avalon", "VoxBox", "Massive Passive", "Distressor", "AwesomeRack"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations //self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return cellStrings.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("LabelCell", forIndexPath: indexPath) cell.textLabel?.text = "\(cellStrings[indexPath.row])" return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectionString = cellStrings[indexPath.row] print(" ChooseGearTableViewController: Hey you just selected \(selectionString)") let rootVC = self.presentingViewController as! ViewController rootVC.menuSelections.append(selectionString) } }
gpl-2.0
09f30094bbfeb769a4e6724539e27f7c
31.614035
118
0.686928
5.28125
false
false
false
false
ryanbooker/Swiftz
Sources/ArrayExt.swift
1
14652
// // ArrayExt.swift // Swiftz // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // #if !XCODE_BUILD import Operadics import Swiftx #endif /// MARK: Array extensions public enum ArrayMatcher<A> { case Nil case Cons(A, [A]) } extension Array /*: Functor*/ { public typealias A = Element public typealias B = Any public typealias FB = [B] public func fmap<B>(_ f : (A) -> B) -> [B] { return self.map(f) } } extension Array /*: Pointed*/ { public static func pure(_ x : A) -> [Element] { return [x] } } extension Array /*: Applicative*/ { public typealias FAB = [(A) -> B] public func ap<B>(_ f : [(A) -> B]) -> [B] { return f <*> self } } extension Array /*: Cartesian*/ { public typealias FTOP = Array<()> public typealias FTAB = Array<(A, B)> public typealias FTABC = Array<(A, B, C)> public typealias FTABCD = Array<(A, B, C, D)> public static var unit : Array<()> { return [()] } public func product<B>(_ r : Array<B>) -> Array<(A, B)> { return self.mzip(r) } public func product<B, C>(_ r : Array<B>, _ s : Array<C>) -> Array<(A, B, C)> { return { x in { y in { z in (x, y, z) } } } <^> self <*> r <*> s } public func product<B, C, D>(_ r : Array<B>, _ s : Array<C>, _ t : Array<D>) -> Array<(A, B, C, D)> { return { x in { y in { z in { w in (x, y, z, w) } } } } <^> self <*> r <*> s <*> t } } extension Array /*: ApplicativeOps*/ { public typealias C = Any public typealias FC = [C] public typealias D = Any public typealias FD = [D] public static func liftA<B>(_ f : @escaping (A) -> B) -> ([A]) -> [B] { typealias FAB = (A) -> B return { (a : [A]) -> [B] in [FAB].pure(f) <*> a } } public static func liftA2<B, C>(_ f : @escaping (A) -> (B) -> C) -> ([A]) -> ([B]) -> [C] { return { (a : [A]) -> ([B]) -> [C] in { (b : [B]) -> [C] in f <^> a <*> b } } } public static func liftA3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> ([A]) -> ([B]) -> ([C]) -> [D] { return { (a : [A]) -> ([B]) -> ([C]) -> [D] in { (b : [B]) -> ([C]) -> [D] in { (c : [C]) -> [D] in f <^> a <*> b <*> c } } } } } extension Array /*: Monad*/ { public func bind<B>(_ f : (A) -> [B]) -> [B] { return self.flatMap(f) } } extension Array /*: MonadOps*/ { public static func liftM<B>(_ f : @escaping (A) -> B) -> ([A]) -> [B] { return { (m1 : [A]) -> [B] in m1 >>- { (x1 : A) in [B].pure(f(x1)) } } } public static func liftM2<B, C>(_ f : @escaping (A) -> (B) -> C) -> ([A]) -> ([B]) -> [C] { return { (m1 : [A]) -> ([B]) -> [C] in { (m2 : [B]) -> [C] in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in [C].pure(f(x1)(x2)) } } } } } public static func liftM3<B, C, D>(_ f : @escaping (A) -> (B) -> (C) -> D) -> ([A]) -> ([B]) -> ([C]) -> [D] { return { (m1 : [A]) -> ([B]) -> ([C]) -> [D] in { (m2 : [B]) -> ([C]) -> [D] in { (m3 : [C]) -> [D] in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in [D].pure(f(x1)(x2)(x3)) } } } } } } } } public func >>->> <A, B, C>(_ f : @escaping (A) -> [B], g : @escaping (B) -> [C]) -> ((A) -> [C]) { return { x in f(x) >>- g } } public func <<-<< <A, B, C>(g : @escaping (B) -> [C], f : @escaping (A) -> [B]) -> ((A) -> [C]) { return f >>->> g } extension Array /*: MonadPlus*/ { public static var mzero : [Element] { return [] } public func mplus(_ other : [Element]) -> [Element] { return self + other } } extension Array /*: MonadZip*/ { public typealias FTABL = [(A, B)] public func mzip<B>(_ ma : [B]) -> [(A, B)] { return [(A, B)](zip(self, ma)) } public func mzipWith<B, C>(_ other : [B], _ f : @escaping (A) -> (B) -> C) -> [C] { return self.mzip(other).map(uncurry(f)) } public static func munzip<B>(ftab : [(A, B)]) -> ([A], [B]) { return (ftab.map(fst), ftab.map(snd)) } } extension Array /*: Foldable*/ { public func foldr<B>(_ k : @escaping (Element) -> (B) -> B, _ i : B) -> B { switch self.match { case .Nil: return i case let .Cons(x, xs): return k(x)(xs.foldr(k, i)) } } public func foldl<B>(_ com : @escaping (B) -> (Element) -> B, _ i : B) -> B { return self.reduce(i, uncurry(com)) } public func foldMap<M : Monoid>(_ f : @escaping (A) -> M) -> M { return self.foldr(curry(<>) • f, M.mempty) } } extension Array { /// Destructures a list into its constituent parts. /// /// If the given list is empty, this function returns .Nil. If the list is non-empty, this /// function returns .Cons(head, tail) public var match : ArrayMatcher<Element> { if self.count == 0 { return .Nil } else if self.count == 1 { return .Cons(self[0], []) } let hd = self[0] let tl = Array(self[1..<self.count]) return .Cons(hd, tl) } /// Returns the tail of the list, or None if the list is empty. public var tail : Optional<[Element]> { switch self.match { case .Nil: return .none case .Cons(_, let xs): return .some(xs) } } /// Returns an array of all initial segments of the receiver, shortest first public var inits : [[Element]] { return self.reduce([[Element]]()) { xss, x in return xss.map { $0.cons(x) }.cons([]) } } /// Returns an array of all final segments of the receiver, longest first public var tails : [[Element]] { return self.reduce([[Element]]()) { x, y in return [x.first!.cons(y)] + x } } /// Returns an array consisting of the receiver with a given element appended to the front. public func cons(_ lhs : Element) -> [Element] { return [lhs] + self } /// Decomposes the receiver into its head and tail. If the receiver is empty the result is /// `.none`, else the result is `.Just(head, tail)`. public var uncons : Optional<(Element, [Element])> { switch self.match { case .Nil: return .none case let .Cons(x, xs): return .some(x, xs) } } /// Safely indexes into an array by converting out of bounds errors to nils. public func safeIndex(_ i : Int) -> Element? { if i < self.count && i >= 0 { return self[i] } else { return nil } } /// Maps a function over an array that takes pairs of (index, element) to a different element. public func mapWithIndex<U>(_ f : (Int, Element) -> U) -> [U] { return zip((self.startIndex ..< self.endIndex), self).map(f) } public func mapMaybe<U>(_ f : (Element) -> Optional<U>) -> [U] { var res = [U]() res.reserveCapacity(self.count) self.forEach { x in if let v = f(x) { res.append(v) } } return res } /// Folds a reducing function over an array from right to left. public func foldRight<U>(_ z : U, _ f : (Element, U) -> U) -> U { var res = z for x in self { res = f(x, res) } return res } /// Takes a binary function, an initial value, and a list and scans the function across each /// element from left to right. After each pass of the scanning function the output is added to /// an accumulator and used in the succeeding scan until the receiver is consumed. /// /// [x1, x2, ...].scanl(z, f) == [z, f(z, x1), f(f(z, x1), x2), ...] public func scanl<B>(_ start : B, _ r : (B, Element) -> B) -> [B] { if self.isEmpty { return [start] } var arr = [B]() arr.append(start) var reduced = start for x in self { reduced = r(reduced, x) arr.append(reduced) } return arr } /// Takes a separator and a list and intersperses that element throughout the list. /// /// ["a","b","c","d","e"].intersperse(",") == ["a",",","b",",","c",",","d",",","e"] public func intersperse(_ item : Element) -> [Element] { func prependAll(item : Element, array : [Element]) -> [Element] { var arr = Array([item]) for i in array.startIndex..<array.endIndex.advanced(by: -1) { arr.append(array[i]) arr.append(item) } arr.append(array[array.endIndex.advanced(by: -1)]) return arr } if self.isEmpty { return self } else if self.count == 1 { return self } else { var array = Array([self[0]]) array += prependAll(item: item, array: self.tail!) return Array(array) } } /// Returns a tuple where the first element is the longest prefix of elements that satisfy a /// given predicate and the second element is the remainder of the list: /// /// [1, 2, 3, 4, 1, 2, 3, 4].span(<3) == ([1, 2],[3, 4, 1, 2, 3, 4]) /// [1, 2, 3].span(<9) == ([1, 2, 3],[]) /// [1, 2, 3].span(<0) == ([],[1, 2, 3]) /// /// span(list, p) == (takeWhile(list, p), dropWhile(list, p)) public func span(_ p : (Element) -> Bool) -> ([Element], [Element]) { switch self.match { case .Nil: return ([], []) case .Cons(let x, let xs): if p(x) { let (ys, zs) = xs.span(p) return (ys.cons(x), zs) } return ([], self) } } /// Returns a tuple where the first element is the longest prefix of elements that do not /// satisfy a given predicate and the second element is the remainder of the list: /// /// `extreme(_:)` is the dual to span(_:)` and satisfies the law /// /// self.extreme(p) == self.span((!) • p) public func extreme(_ p : @escaping (Element) -> Bool) -> ([Element], [Element]) { return self.span { ((!) • p)($0) } } /// Takes a list and groups its arguments into sublists of duplicate elements found next to each /// other according to an equality predicate. public func groupBy(_ p : (Element) -> (Element) -> Bool) -> [[Element]] { switch self.match { case .Nil: return [] case .Cons(let x, let xs): let (ys, zs) = xs.span(p(x)) let l = ys.cons(x) return zs.groupBy(p).cons(l) } } /// Takes a list and groups its arguments into sublists of duplicate elements found next to each /// other according to an equality predicate. public func groupBy(_ p : @escaping (Element, Element) -> Bool) -> [[Element]] { return self.groupBy(curry(p)) } /// Returns an array of the first elements that do not satisfy a predicate until that predicate /// returns false. /// /// [1, 2, 3, 4, 5, 1, 2, 3].dropWhile(<3) == [3,4,5,1,2,3] /// [1, 2, 3].dropWhile(<9) == [] /// [1, 2, 3].dropWhile(<0) == [1,2,3] public func dropWhile(_ p : (Element) -> Bool) -> [Element] { switch self.match { case .Nil: return [] case .Cons(let x, let xs): if p(x) { return xs.dropWhile(p) } return self } } /// Returns an array of of the remaining elements after dropping the largest suffix of the /// receiver over which the predicate holds. /// /// [1, 2, 3, 4, 5].dropWhileEnd(>3) == [1, 2, 3] /// [1, 2, 3, 4, 5, 2].dropWhileEnd(>3) == [1, 2, 3, 4, 5, 2] public func dropWhileEnd(_ p : (Element) -> Bool) -> [Element] { return self.reduce([Element](), { xs, x in p(x) && xs.isEmpty ? [] : xs.cons(x) }) } /// Returns an array of the first elements that satisfy a predicate until that predicate returns /// false. /// /// [1, 2, 3, 4, 1, 2, 3, 4].takeWhile(<3) == [1, 2] /// [1,2,3].takeWhile(<9) == [1, 2, 3] /// [1,2,3].takeWhile(<0) == [] public func takeWhile(_ p : (Element) -> Bool) -> [Element] { switch self.match { case .Nil: return [] case .Cons(let x, let xs): if p(x) { return xs.takeWhile(p).cons(x) } return [] } } } extension Array where Element : Equatable { /// Takes two lists and returns true if the first string is a prefix of the second string. public func isPrefixOf(_ r : [Element]) -> Bool { switch (self.match, r.match) { case (.Cons(let x, let xs), .Cons(let y, let ys)) where (x == y): return xs.isPrefixOf(ys) case (.Nil, _): return true default: return false } } /// Takes two lists and returns true if the first string is a suffix of the second string. public func isSuffixOf(_ r : [Element]) -> Bool { return self.reversed().isPrefixOf(r.reversed()) } /// Takes two lists and returns true if the first string is contained entirely anywhere in the /// second string. public func isInfixOf(_ r : [Element]) -> Bool { if let _ = r.tails.first(where: self.isPrefixOf) { return true } return false } /// Takes two strings and drops items in the first from the second. If the first string is not a /// prefix of the second string this function returns Nothing. public func stripPrefix(_ r : [Element]) -> Optional<[Element]> { switch (self.match, r.match) { case (.Nil, _): return .some(r) case (.Cons(let x, let xs), .Cons(let y, _)) where x == y: return xs.stripPrefix(xs) default: return .none } } /// Takes two strings and drops items in the first from the end of the second. If the first /// string is not a suffix of the second string this function returns nothing. public func stripSuffix(_ r : [Element]) -> Optional<[Element]> { return self.reversed().stripPrefix(r.reversed()).map({ $0.reversed() }) } /// Takes a list and groups its arguments into sublists of duplicate elements found next to each /// other. /// /// group([0, 1, 1, 2, 3, 3, 4, 5, 6, 7, 7]) == [[0], [1, 1], [2], [3, 3], [4], [5], [6], [7, 7]] public var group : [[Element]] { return self.groupBy { a in { b in a == b } } } } /// MARK: Sequence and SequenceType extensions extension Sequence { /// Maps the array of to a dictionary given a transformer function that returns /// a (Key, Value) pair for the dictionary, if nil is returned then the value is /// not added to the dictionary. public func mapAssociate<Key : Hashable, Value>(_ f : (Iterator.Element) -> (Key, Value)?) -> [Key : Value] { return Dictionary(flatMap(f)) } /// Creates a dictionary of Key-Value pairs generated from the transformer function returning the key (the label) /// and pairing it with that element. public func mapAssociateLabel<Key : Hashable>(_ f : (Iterator.Element) -> Key) -> [Key : Iterator.Element] { return Dictionary(map { (f($0), $0) }) } } /// Maps a function over a list of Optionals, applying the function of the optional is Some, /// discarding the value if it is None and returning a list of non Optional values public func mapFlatten<A>(_ xs : [A?]) -> [A] { return xs.mapMaybe(identity) } /// Inserts a list in between the elements of a 2-dimensional array and concatenates the result. public func intercalate<A>(_ list : [A], nested : [[A]]) -> [A] { return concat(nested.intersperse(list)) } /// Concatenate a list of lists. public func concat<T>(_ list : [[T]]) -> [T] { return list.reduce([], +) } public func sequence<A>(_ ms: [Array<A>]) -> Array<[A]> { if ms.isEmpty { return [] } return ms.reduce(Array<[A]>.pure([]), { (n : [[A]], m : [A]) in return n.bind { (xs : [A]) in return m.bind { (x : A) in return Array<[A]>.pure(xs + [x]) } } }) }
bsd-3-clause
eba53488974d8a0522c4d94b2539926c
29.197938
203
0.57217
2.858314
false
false
false
false
Rendel27/RDExtensionsSwift
RDExtensionsSwift/RDExtensionsSwift/Source/String/String+Conversion.swift
1
4166
// // String+Conversion.swift // // Created by Giorgi Iashvili on 19.09.16. // Copyright (c) 2016 Giorgi Iashvili // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public extension String { /// RDExtensionsSwift: Convert String to Bool var toBool : Bool? { get { switch self { case "TRUE", "True", "true", "YES", "Yes", "yes", "1": return true case "FALSE", "False", "false", "NO", "No", "no", "0": return false default: return nil } } } /// RDExtensionsSwift: Convert String to Int var toInt : Int { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.intValue } } /// RDExtensionsSwift: Convert String to Int8 var toInt8 : Int8 { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.int8Value } } /// RDExtensionsSwift: Convert String to Int16 var toInt16 : Int16 { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.int16Value } } /// RDExtensionsSwift: Convert String to Int32 var toInt32 : Int32 { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.int32Value } } /// RDExtensionsSwift: Convert String to Int64 var toInt64 : Int64 { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.int64Value } } /// RDExtensionsSwift: Convert String to Float var toFloat : Float { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.floatValue } } /// RDExtensionsSwift: Convert String to CGFloat var toCGFloat : CGFloat { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : CGFloat(number.floatValue) } } /// RDExtensionsSwift: Convert String to Double var toDouble : Double { get { let number = NSDecimalNumber(string: self); return number == NSDecimalNumber.notANumber ? 0 : number.doubleValue } } /// RDExtensionsSwift: Convert String to NSTimeInterval var toTimeInterval : TimeInterval { get { return self.toDouble } } /// RDExtensionsSwift: Convert String to NSDecimalNumber var toNSDecimalNumber : NSDecimalNumber? { get { let number = NSDecimalNumber(string: self); return number == .notANumber ? nil : number } } /// RDExtensionsSwift: Convert String to NSDecimalNumber. Returns zero if covert was unsuccessful. var toNSDecimalNumberValue: NSDecimalNumber { get { return self.toNSDecimalNumber ?? .zero } } /// RDExtensionsSwift: Convert String to NSURL var toHttpURL : URL? { get { return URL(string: self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? self) } } /// RDExtensionsSwift: Convert String to NSURL var toFileURL : URL? { get { return URL(fileURLWithPath: self) } } }
mit
ca678f3db124778f4b1b2eb5fa767cd5
48.595238
160
0.683149
4.744875
false
false
false
false
biohazardlover/ByTrain
ByTrain/Station/TopStationsViewController.swift
1
1330
import UIKit class TopStationsViewController: TableViewController { var topStations: [Station]? var selectedStation: Station? override func refresh() { retrieveTopStations { (response) in self.refreshControl?.endRefreshing() if response.result.error == nil { self.topStations = response.result.value self.tableView.reloadData() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "UnwindSegueFromTopStationsViewController" { if let indexPath = tableView.indexPathForSelectedRow { selectedStation = topStations?[indexPath.row] } else { selectedStation = nil } } } // MARK: - Table View Data Source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topStations?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "StationTableCell", for: indexPath) cell.textLabel?.text = topStations?[indexPath.row].stationName return cell } }
mit
acb65b3bc9347487117ae14e2f1d1af2
31.439024
109
0.621805
5.495868
false
false
false
false
fireflyexperience/BSImagePicker
Pod/Classes/Controller/BSImagePickerViewController.swift
1
11475
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos /** BSImagePickerViewController. Use settings or buttons to customize it to your needs. */ public final class BSImagePickerViewController : UINavigationController, BSImagePickerSettings { fileprivate let settings = Settings() fileprivate var doneBarButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) fileprivate var cancelBarButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil) fileprivate let albumTitleView: AlbumTitleView = bundle.loadNibNamed("AlbumTitleView", owner: nil, options: nil)!.first as! AlbumTitleView fileprivate var dataSource: SelectableDataSource? fileprivate let selections: [PHAsset] static let bundle: Bundle = Bundle(for: PhotosViewController.self) lazy var photosViewController: PhotosViewController = { let dataSource: SelectableDataSource if self.dataSource != nil { dataSource = self.dataSource! } else { dataSource = BSImagePickerViewController.defaultDataSource() } let vc = PhotosViewController(dataSource: dataSource, settings: self.settings, selections: self.selections) vc.doneBarButton = self.doneBarButton vc.cancelBarButton = self.cancelBarButton vc.albumTitleView = self.albumTitleView return vc }() class func authorize(_ status: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus(), fromViewController: UIViewController, completion: @escaping () -> Void) { switch status { case .authorized: // We are authorized. Run block completion() case .notDetermined: // Ask user for permission PHPhotoLibrary.requestAuthorization({ (status) -> Void in DispatchQueue.main.async(execute: { () -> Void in self.authorize(status, fromViewController: fromViewController, completion: completion) }) }) default: () DispatchQueue.main.async(execute: { () -> Void in // Set up alert controller with some default strings. These should probably be overriden in application localizeable strings. // If you don't enjoy my Swenglish that is ^^ let alertController = UIAlertController(title: NSLocalizedString("imagePickerNoCameraAccessTitle", value: "Can't access Photos", comment: "Alert view title"), message: NSLocalizedString("imagePickerNoCameraAccessMessage", value: "You need to enable Photos access in application settings.", comment: "Alert view message"), preferredStyle: .alert) let cancelAction = UIAlertAction(title: NSLocalizedString("imagePickerNoCameraAccessCancelButton", value: "Cancel", comment: "Cancel button title"), style: .cancel, handler:nil) let settingsAction = UIAlertAction(title: NSLocalizedString("imagePickerNoCameraAccessSettingsButton", value: "Settings", comment: "Settings button title"), style: .default, handler: { (action) -> Void in let url = URL(string: UIApplicationOpenSettingsURLString) if let url = url , UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } }) alertController.addAction(cancelAction) alertController.addAction(settingsAction) fromViewController.present(alertController, animated: true, completion: nil) }) } } /** Want it to show your own custom fetch results? Make sure the fetch results are of PHAssetCollections - parameter fetchResults: PHFetchResult of PHAssetCollections */ public convenience init(fetchResults: [PHFetchResult<PHObject>]) { self.init(dataSource: FetchResultsDataSource(fetchResults: fetchResults)) } /** Do you have an asset collection you want to select from? Use this initializer! - parameter assetCollection: The PHAssetCollection you want to select from - parameter selections: Selected assets */ public convenience init(assetCollection: PHAssetCollection, selections: [PHAsset] = []) { self.init(dataSource: AssetCollectionDataSource(assetCollection: assetCollection), selections: selections) } /** Sets up an classic image picker with results from camera roll and albums */ public convenience init() { self.init(dataSource: nil) } /** You should probably use one of the convenience inits - parameter dataSource: The data source for the albums - parameter selections: Any PHAsset you want to seed the picker with as selected */ public required init(dataSource: SelectableDataSource?, selections: [PHAsset] = []) { if let dataSource = dataSource { self.dataSource = dataSource } self.selections = selections super.init(nibName: nil, bundle: nil) } /** https://www.youtube.com/watch?v=dQw4w9WgXcQ */ required public init?(coder aDecoder: NSCoder) { dataSource = BSImagePickerViewController.defaultDataSource() selections = [] super.init(coder: aDecoder) } /** Load view. See apple documentation */ public override func loadView() { super.loadView() // TODO: Settings view.backgroundColor = UIColor.white // Make sure we really are authorized if PHPhotoLibrary.authorizationStatus() == .authorized { setViewControllers([photosViewController], animated: false) } } fileprivate static func defaultDataSource() -> SelectableDataSource { let fetchOptions = PHFetchOptions() // Camera roll fetch result let cameraRollResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: fetchOptions) // Albums fetch result let albumResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions) return FetchResultsDataSource(fetchResults: [cameraRollResult as! PHFetchResult<PHObject>, albumResult as! PHFetchResult<PHObject>]) } // MARK: ImagePickerSettings proxy /** See BSImagePicketSettings for documentation */ public var maxNumberOfSelections: Int { get { return settings.maxNumberOfSelections } set { settings.maxNumberOfSelections = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionCharacter: Character? { get { return settings.selectionCharacter } set { settings.selectionCharacter = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionFillColor: UIColor { get { return settings.selectionFillColor } set { settings.selectionFillColor = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionStrokeColor: UIColor { get { return settings.selectionStrokeColor } set { settings.selectionStrokeColor = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionShadowColor: UIColor { get { return settings.selectionShadowColor } set { settings.selectionShadowColor = newValue } } /** See BSImagePicketSettings for documentation */ public var selectionTextAttributes: [String: AnyObject] { get { return settings.selectionTextAttributes } set { settings.selectionTextAttributes = newValue } } /** See BSImagePicketSettings for documentation */ public var cellsPerRow: (_ verticalSize: UIUserInterfaceSizeClass, _ horizontalSize: UIUserInterfaceSizeClass) -> Int { get { return settings.cellsPerRow } set { settings.cellsPerRow = newValue } } // MARK: Buttons /** Cancel button */ public var cancelButton: UIBarButtonItem { get { return self.cancelBarButton } } /** Done button */ public var doneButton: UIBarButtonItem { get { return self.doneBarButton } } /** Album button */ public var albumButton: UIButton { get { return self.albumTitleView.albumButton } } // MARK: Closures var selectionClosure: ((_ asset: PHAsset) -> Void)? { get { return photosViewController.selectionClosure } set { photosViewController.selectionClosure = newValue } } var deselectionClosure: ((_ asset: PHAsset) -> Void)? { get { return photosViewController.deselectionClosure } set { photosViewController.deselectionClosure = newValue } } var cancelClosure: ((_ assets: [PHAsset]) -> Void)? { get { return photosViewController.cancelClosure } set { photosViewController.cancelClosure = newValue } } var finishClosure: ((_ assets: [PHAsset]) -> Void)? { get { return photosViewController.finishClosure } set { photosViewController.finishClosure = newValue } } }
mit
ff4fc5be1a49f589a362e7d8163417a6
29.435616
220
0.613038
5.578026
false
false
false
false
Swiftodon/Leviathan
Leviathan/Sources/Views/ToolViews/Updating.swift
1
1780
// // Updating.swift // Leviathan // // Created by Thomas Bonk on 17.11.22. // Copyright 2022 The Swiftodon Team // // 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 SwiftUI struct Updating<Content: View>: View { // MARK: - Public Properties var body: some View { content() .onAppear { guard updateTimer == nil else { return } updateTimer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { _ in onUpdate() }) updateTimer?.fire() } .onDisappear { updateTimer?.invalidate() updateTimer = nil } } // MARK: - Private Properties private let interval: TimeInterval private let content: () -> Content private let onUpdate: () -> () @State private var updateTimer: Timer? = nil // MARK: - Initialization init( _ interval: TimeInterval = 60, content: @escaping () -> Content, onUpdate: @escaping () -> ()) { self.interval = interval self.onUpdate = onUpdate self.content = content } }
apache-2.0
2ff6f0ca078aff06b1cd3b84bc6232f9
24.797101
101
0.571348
4.721485
false
false
false
false
Limon-O-O/Lady
Lady/HighPassFilter.swift
1
1533
// // HighPassFilter.swift // Example // // Created by Limon on 8/3/16. // Copyright © 2016 Lady. All rights reserved. // import CoreImage class HighPassFilter { var inputImage: CIImage? /// A number value that controls the radius (in pixel) of the filter. The default value of this parameter is 1.0. var inputRadius: Float = 1.0 private static let kernel: CIColorKernel = { let shaderPath = Bundle(for: HighPassFilter.self).path(forResource: "\(HighPassFilter.self)", ofType: "cikernel") guard let path = shaderPath, let kernelString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8), let kernel = CIColorKernel(source: kernelString) else { fatalError("Unable to build HighPassFilter Kernel") } return kernel }() var outputImage: CIImage? { guard let unwrappedInputImage = inputImage, let blurFilter = blurFilter else { return nil } blurFilter.setValue(unwrappedInputImage.clampedToExtent(), forKey: kCIInputImageKey) blurFilter.setValue(inputRadius, forKey: kCIInputRadiusKey) guard let outputImage = blurFilter.outputImage else { return nil } return HighPassFilter.kernel.apply(extent: unwrappedInputImage.extent, arguments: [unwrappedInputImage, outputImage]) } private lazy var blurFilter: CIFilter? = { let filter = CIFilter(name: "CIGaussianBlur") return filter }() func setDefaults() { inputImage = nil inputRadius = 1.0 } }
mit
91fd77fe0444bd380f8e0540ea8acd32
28.461538
178
0.682115
4.479532
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/00646-llvm-raw-fd-ostream-write-impl.swift
11
728
// 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 // RUN: not %target-swift-frontend %s -parse protocol C { deinit { struct e == { x in a { return [unowned self.e { class A { func compose<U : e where A? = B<C> { override init(b.init() -> { var f: B) { } } } let t: C { typealias R = { c: String = { } } } } } protocol P { } } static let i: NSObject { } } e : U : H) -> { } typealias e = compose<T! { } let a { } } typealias e : e,
apache-2.0
dd0edd1fcd89905f5c06c47b014f593b
17.2
78
0.649725
2.95935
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/DiscoveryV1/Models/Environment.swift
1
3482
/** * (C) Copyright IBM Corp. 2016, 2020. * * 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 /** Details about an environment. */ public struct Environment: Codable, Equatable { /** Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. */ public enum Status: String { case active = "active" case pending = "pending" case maintenance = "maintenance" case resizing = "resizing" } /** Current size of the environment. */ public enum Size: String { case lt = "LT" case xs = "XS" case s = "S" case ms = "MS" case m = "M" case ml = "ML" case l = "L" case xl = "XL" case xxl = "XXL" case xxxl = "XXXL" } /** Unique identifier for the environment. */ public var environmentID: String? /** Name that identifies the environment. */ public var name: String? /** Description of the environment. */ public var description: String? /** Creation date of the environment, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. */ public var created: Date? /** Date of most recent environment update, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. */ public var updated: Date? /** Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. */ public var status: String? /** If `true`, the environment contains read-only collections that are maintained by IBM. */ public var readOnly: Bool? /** Current size of the environment. */ public var size: String? /** The new size requested for this environment. Only returned when the environment *status* is `resizing`. *Note:* Querying and indexing can still be performed during an environment upsize. */ public var requestedSize: String? /** Details about the resource usage and capacity of the environment. */ public var indexCapacity: IndexCapacity? /** Information about the Continuous Relevancy Training for this environment. */ public var searchStatus: SearchStatus? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case environmentID = "environment_id" case name = "name" case description = "description" case created = "created" case updated = "updated" case status = "status" case readOnly = "read_only" case size = "size" case requestedSize = "requested_size" case indexCapacity = "index_capacity" case searchStatus = "search_status" } }
apache-2.0
62b15e5ab446c3486ecf634414ef806e
27.308943
120
0.634406
4.368883
false
false
false
false
teacurran/alwaysawake-ios
Pods/p2.OAuth2/Sources/Base/OAuth2AuthRequest.swift
2
7804
// // OAuth2AuthRequest.swift // OAuth2 // // Created by Pascal Pfiffner on 18/03/16. // Copyright © 2016 Pascal Pfiffner. 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 /** HTTP methods for auth requests. */ public enum OAuth2HTTPMethod: String { case GET = "GET" case POST = "POST" } /** Content types that will be specified in the request header under "Content-type". */ public enum OAuth2HTTPContentType: String { /// JSON content: `application/json` case JSON = "application/json" /// Form encoded content, using UTF-8: `application/x-www-form-urlencoded; charset=utf-8` case WWWForm = "application/x-www-form-urlencoded; charset=utf-8" } /** Class representing an OAuth2 authorization request that can be used to create NSURLRequest instances. */ public class OAuth2AuthRequest { /// The url of the receiver. Queries may by added by parameters specified on `params`. public let url: NSURL /// The HTTP method. public let method: OAuth2HTTPMethod /// The content type that will be specified. Defaults to `WWWForm`. public var contentType = OAuth2HTTPContentType.WWWForm /// If set will take preference over any "Authorize" header that would otherwise be set. public var headerAuthorize: String? public var params = OAuth2AuthRequestParams() /** Designated initializer. Neither URL nor method can later be changed. */ public init(url: NSURL, method: OAuth2HTTPMethod = .POST) { self.url = url self.method = method } // MARK: - Parameter /** Add the given parameter to the receiver's parameter list, overwriting existing parameters. This method can take nil for convenience. - parameter params: The parameters to add to the receiver */ public func addParams(params inParams: OAuth2StringDict?) { if let prms = inParams { for (key, val) in prms { params[key] = val } } } // MARK: - Request Creation /** Returns URL components created from the receiver. Only if its method is GET will it add the parameters as percent encoded query. - returns: NSURLComponents representing the receiver */ func asURLComponents() throws -> NSURLComponents { let comp = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) guard let components = comp where "https" == components.scheme else { throw OAuth2Error.NotUsingTLS } if .GET == method && params.count > 0 { components.percentEncodedQuery = params.percentEncodedQueryString() } return components } /** Creates an NSURL from the receiver's components; calls `asURLComponents()`, so its caveats apply. - returns: An NSURL representing the receiver */ public func asURL() throws -> NSURL { let comp = try asURLComponents() if let finalURL = comp.URL { return finalURL } throw OAuth2Error.InvalidURLComponents(comp) } /** Creates a mutable URL request from the receiver, taking into account settings from the provided OAuth2 instance. - parameter oauth2: The OAuth2 instance from which to take client and auth settings - returns: A mutable NSURLRequest */ public func asURLRequestFor(oauth2: OAuth2) throws -> NSMutableURLRequest { var finalParams = params var finalAuthHeader = headerAuthorize // base request let finalURL = try asURL() let req = NSMutableURLRequest(URL: finalURL) req.HTTPMethod = method.rawValue req.setValue(contentType.rawValue, forHTTPHeaderField: "Content-Type") req.setValue("application/json", forHTTPHeaderField: "Accept") // add custom headers if let headerParams = oauth2.authHeaders where !headerParams.isEmpty { for (key, value) in headerParams { req.setValue(value, forHTTPHeaderField: key) } } // handle client secret if there is one if let clientId = oauth2.clientConfig.clientId where !clientId.isEmpty, let secret = oauth2.clientConfig.clientSecret { // add to request body if oauth2.authConfig.secretInBody { oauth2.logger?.debug("OAuth2", msg: "Adding “client_id” and “client_secret” to request body") finalParams["client_id"] = clientId finalParams["client_secret"] = secret } // add Authorization header (if not in body) else if nil == finalAuthHeader { oauth2.logger?.debug("OAuth2", msg: "Adding “Authorization” header as “Basic client-key:client-secret”") let pw = "\(clientId.wwwFormURLEncodedString):\(secret.wwwFormURLEncodedString)" if let utf8 = pw.dataUsingEncoding(NSUTF8StringEncoding) { finalAuthHeader = "Basic \(utf8.base64EncodedStringWithOptions([]))" } else { throw OAuth2Error.UTF8EncodeError } finalParams.removeValueForKey("client_id") finalParams.removeValueForKey("client_secret") } } // add custom Authorize header if let authHeader = finalAuthHeader { req.setValue(authHeader, forHTTPHeaderField: "Authorization") } // add a body to POST requests if .POST == method && finalParams.count > 0 { req.HTTPBody = try finalParams.utf8EncodedData() } return req } } /** Struct to hold on to request parameters. Provides utility functions so the parameters can be correctly encoded for use in URLs and request bodies. */ public struct OAuth2AuthRequestParams { /// The parameters to be used. private var params: OAuth2StringDict? = nil public init() { } public subscript(key: String) -> String? { get { return params?[key] } set(newValue) { params = params ?? OAuth2StringDict() params![key] = newValue } } /** Removes the given value from the receiver, if it is defined. - parameter key: The key for the value to be removed - returns: The value that was removed, if any */ public mutating func removeValueForKey(key: String) -> String? { return params?.removeValueForKey(key) } /// The number of items in the receiver. public var count: Int { return params?.count ?? 0 } // MARK: - Conversion /** Creates a form encoded query string, then encodes it using UTF-8 to NSData. - returns: NSData representing the receiver form-encoded */ public func utf8EncodedData() throws -> NSData? { guard nil != params else { return nil } let body = percentEncodedQueryString() if let encoded = body.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) { return encoded } else { throw OAuth2Error.UTF8EncodeError } } /** Creates a parameter string in the form of `key1=value1&key2=value2`, using form URL encoding. - returns: A form encoded string */ public func percentEncodedQueryString() -> String { guard let params = params else { return "" } return self.dynamicType.formEncodedQueryStringFor(params) } /** Create a query string from a dictionary of string: string pairs. This method does **form encode** the value part. If you're using NSURLComponents you want to assign the return value to `percentEncodedQuery`, NOT `query` as this would double-encode the value. - parameter params: The parameters you want to have encoded - returns: An URL-ready query string */ public static func formEncodedQueryStringFor(params: OAuth2StringDict) -> String { var arr: [String] = [] for (key, val) in params { arr.append("\(key)=\(val.wwwFormURLEncodedString)") } return arr.joinWithSeparator("&") } }
apache-2.0
de6b07f77d52801a2f5bc1b2766fc1fe
27.734317
138
0.717863
3.862599
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/02068-swift-parser-parsedeclfunc.swift
1
572
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck deinit { return { typealias R = B, range: Array<f = g: d { let c { func a(n: d : A>() { struct A? = """ } func c({ return " } } } struct d<d where l.E == b.<T>()) } d func d
apache-2.0
7c029b2672e782453404b4572197d435
22.833333
79
0.681818
3.231638
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/Home/QRCode/QRCodeCardViewController.swift
1
3754
// // QRCodeCardViewController.swift // CCWeibo // // Created by 徐才超 on 16/2/5. // Copyright © 2016年 徐才超. All rights reserved. // import UIKit class QRCodeCardViewController: UIViewController { @IBOutlet weak var cardImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "我的名片" cardImageView.image = creatQRCodeImageBy("猥琐皮特") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func creatQRCodeImageBy(info: String) -> UIImage{ // 1.创建滤镜 let filter = CIFilter(name: "CIQRCodeGenerator") // 2.还原滤镜的默认属性 filter?.setDefaults() // 3.设置需要生成二维码的数据 filter?.setValue(info.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage") // 4.从滤镜中取出生成好的图片 let ciImage = filter?.outputImage // return UIImage(CIImage: ciImage!) let bgImage = createNonInterpolatedUIImageFormCIImage(ciImage!, size: 300) // 5.创建一个头像 let icon = UIImage(named: "\(info)") // 6.合成图片(将二维码和头像进行合并) let newImage = creteImage(bgImage, iconImage: icon!) // 7.返回生成好的二维码 return newImage } /** 合成图片 :param: bgImage 背景图片 :param: iconImage 头像 */ private func creteImage(bgImage: UIImage, iconImage: UIImage) -> UIImage { // 1.开启图片上下文 UIGraphicsBeginImageContext(bgImage.size) // 2.绘制背景图片 bgImage.drawInRect(CGRect(origin: CGPointZero, size: bgImage.size)) // 3.绘制头像 let width:CGFloat = 50 let height:CGFloat = width let x = (bgImage.size.width - width) * 0.5 let y = (bgImage.size.height - height) * 0.5 iconImage.drawInRect(CGRect(x: x, y: y, width: width, height: height)) // 4.取出绘制号的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 5.关闭上下文 UIGraphicsEndImageContext() // 6.返回合成号的图片 return newImage } /** 根据CIImage生成指定大小的高清UIImage :param: image 指定CIImage :param: size 指定大小 :returns: 生成好的图片 */ private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage { let extent: CGRect = CGRectIntegral(image.extent) let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent)) // 1.创建bitmap; let width = CGRectGetWidth(extent) * scale let height = CGRectGetHeight(extent) * scale let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()! let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)! let context = CIContext(options: nil) let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent) CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None) CGContextScaleCTM(bitmapRef, scale, scale); CGContextDrawImage(bitmapRef, extent, bitmapImage); // 2.保存bitmap到图片 let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)! return UIImage(CGImage: scaledImage) } }
mit
8f5dbd2bc7e73258b341d75bc4353f9c
29.651786
100
0.616662
4.614247
false
false
false
false
oursky/Redux
Pod/Classes/StoreConnector.swift
1
2462
// // StoreConnector.swift // Pods // // Created by Steven Chan on 30/12/15. // // import UIKit public protocol StoreDelegate { func storeDidUpdateState(_ lastState: ReduxAppState) } open class StoreConnector { typealias Disconnect = () -> Void var connections: [Int: Disconnect] = [Int: Disconnect]() func connect(_ store: ReduxStore, keys: [String], delegate: StoreDelegate) { let address: Int = unsafeBitCast(store, to: Int.self) var lastState: ReduxAppState? if let storeState = store.getState() as? ReduxAppState { lastState = storeState } connections[address] = store.subscribe { if let storeState = store.getState() as? ReduxAppState { let k: [String] = keys.filter { if let storeValue = storeState.get($0), let lastValue = lastState?.get($0) { return !storeValue.equals(lastValue) } return false } if k.count > 0 && lastState != nil { delegate.storeDidUpdateState(lastState!) } lastState = storeState } } } func disconnect(_ store: ReduxStore) { let address: Int = unsafeBitCast(store, to: Int.self) connections[address]!() connections.removeValue(forKey: address) } } public extension UIViewController { fileprivate struct AssociatedKeys { static var connector: StoreConnector? } var storeConnector: StoreConnector? { get { return objc_getAssociatedObject( self, &AssociatedKeys.connector ) as? StoreConnector } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.connector, newValue as AnyObject, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } func connect(_ store: ReduxStore, keys: [String], delegate: StoreDelegate) { if storeConnector == nil { storeConnector = StoreConnector() } storeConnector?.connect(store, keys: keys, delegate: delegate) } func disconnect(_ store: ReduxStore) { storeConnector?.disconnect(store) } }
mit
40812d66d7a24c17ee9a6e47b06ad77e
25.76087
80
0.547522
5.065844
false
false
false
false
MR-Zong/ZGResource
Project/cellAnimation/cellAnimation/ViewController2.swift
1
2650
// // ViewController2.swift // cellAnimation // // Created by XQ on 16/7/15. // Copyright © 2016年 XQ. All rights reserved. // import UIKit class ViewController2: UIViewController, UITableViewDelegate, UITableViewDataSource{ var tableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView = UITableView.init(frame: self.view.frame) tableView.delegate = self tableView.dataSource = self tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") //tableView.separatorStyle = UITableViewCellSeparatorStyle.None self.view.addSubview(tableView) // Do any additional setup after loading the view. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.backgroundColor = UIColor.greenColor() cell.textLabel?.text = "aaaaaaaaa \(indexPath.row) aaaaaaaa" cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = ViewController() self.navigationController?.popViewControllerAnimated(true) } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let trans = CATransform3DMakeScale(0.1, 0.1, 0.1) cell.layer.transform = CATransform3DRotate(trans, CGFloat(M_PI_2), 0, 0, 1) UIView.animateWithDuration(1) { () -> Void in cell.layer.transform = CATransform3DIdentity } cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
90d86895a87e90e66e2541c7f0f445f6
38.507463
125
0.698149
5.100193
false
false
false
false
chanhx/Octogit
iGithub/ViewControllers/Detail/PullRequestViewController.swift
2
1927
// // PullRequestViewController.swift // iGithub // // Created by Chan Hocheung on 10/09/2017. // Copyright © 2017 Hocheung. All rights reserved. // import UIKit import WebKit import RxSwift import RxCocoa class PullRequestViewController: UIViewController { let indicator = LoadingIndicator() let webView = WKWebView() let disposeBag = DisposeBag() var viewModel: PullRequestViewModel! override func viewDidLoad() { super.viewDidLoad() webView.frame = view.bounds webView.autoresizingMask = [.flexibleWidth, .flexibleHeight] webView.navigationDelegate = self webView.isOpaque = false webView.backgroundColor = UIColor(netHex: 0xefeff4) self.view.addSubview(webView) self.show(indicator: indicator, onView: webView) navigationItem.title = "#\(viewModel.number)" viewModel.html.asDriver() .flatMap { Driver.from(optional: $0) } .drive(onNext: { [unowned self] in self.webView.loadHTMLString($0, baseURL: Bundle.main.resourceURL) self.indicator.removeFromSuperview() }) .disposed(by: disposeBag) viewModel.fetchData() } } extension PullRequestViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { guard let url = navigationAction.request.url else { decisionHandler(.cancel) return } if url.isFileURL { decisionHandler(.allow) return } decisionHandler(.cancel) let vc = URLRouter.viewController(forURL: url) self.navigationController?.pushViewController(vc, animated: true) } }
gpl-3.0
00329828d186c87ef816236b618be4d8
27.323529
157
0.624091
5.364903
false
false
false
false
kalupa/WriterTest
WriterTest/WriterTest/AppDelegate.swift
1
5876
// // AppDelegate.swift // WriterTest // // Created by Paul Kalupnieks on 2015-06-20. // Copyright (c) 2015 Paul Kalupnieks. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.Kalupnieks.Paul.WriterTest" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("WriterTest", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("WriterTest.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
d77272a87f8f278c6e61aa4a5e9b181d
51.936937
287
0.74966
5.269955
false
false
false
false
heshamMassoud/RouteMe
RouteMe/SearchResultsController.swift
1
2226
// // SearchResultsController.swift // PlacesLookup // // Created by Malek T. on 9/30/15. // Copyright © 2015 Medigarage Studios LTD. All rights reserved. // import UIKit protocol InsertAddressOnTextfield{ func insertAddress(address: String, isStart: Bool) } class SearchResultsController: UITableViewController { var autocompleteResults: [String]! var isEditingStartPoint: Bool! var delegate: InsertAddressOnTextfield! override func viewDidLoad() { super.viewDidLoad() self.autocompleteResults = Array() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier") self.view.backgroundColor = UIColor(hexString: Style.ColorPallete.GREY) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.autocompleteResults.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) styleCell(cell, index: indexPath.row) return cell } func styleCell(cell: UITableViewCell, index: Int) { cell.backgroundColor = UIColor(hexString: Style.ColorPallete.GREY) cell.textLabel?.text = self.autocompleteResults[index] cell.textLabel?.textColor = UIColor(hexString: Style.ColorPallete.Blue) cell.textLabel?.font = Style.Font.AutocompleteResults } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ self.dismissViewControllerAnimated(true, completion: nil) let address: String = self.autocompleteResults[indexPath.row] self.delegate.insertAddress(address, isStart: isEditingStartPoint) } func reloadDataWithArray(array:[String], isStart: Bool){ self.autocompleteResults = array self.tableView.reloadData() self.isEditingStartPoint = isStart } }
apache-2.0
a174c0b1d160ffb758818819c21752da
34.887097
118
0.713708
5.138568
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/MigrationHubConfig/MigrationHubConfig_API.swift
1
5336
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS MigrationHubConfig service. The AWS Migration Hub home region APIs are available specifically for working with your Migration Hub home region. You can use these APIs to determine a home region, as well as to create and work with controls that describe the home region. You must make API calls for write actions (create, notify, associate, disassociate, import, or put) while in your home region, or a HomeRegionNotSetException error is returned. API calls for read actions (list, describe, stop, and delete) are permitted outside of your home region. If you call a write API outside the home region, an InvalidInputException is returned. You can call GetHomeRegion action to obtain the account's Migration Hub home region. For specific API usage, see the sections that follow in this AWS Migration Hub Home Region API reference. */ public struct MigrationHubConfig: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the MigrationHubConfig client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "AWSMigrationHubMultiAccountService", service: "migrationhub-config", signingName: "mgh", serviceProtocol: .json(version: "1.1"), apiVersion: "2019-06-30", endpoint: endpoint, errorType: MigrationHubConfigErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// This API sets up the home region for the calling account only. public func createHomeRegionControl(_ input: CreateHomeRegionControlRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateHomeRegionControlResult> { return self.client.execute(operation: "CreateHomeRegionControl", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// This API permits filtering on the ControlId and HomeRegion fields. public func describeHomeRegionControls(_ input: DescribeHomeRegionControlsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeHomeRegionControlsResult> { return self.client.execute(operation: "DescribeHomeRegionControls", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Returns the calling account’s home region, if configured. This API is used by other AWS services to determine the regional endpoint for calling AWS Application Discovery Service and Migration Hub. You must call GetHomeRegion at least once before you call any other AWS Application Discovery Service and AWS Migration Hub APIs, to obtain the account's Migration Hub home region. public func getHomeRegion(_ input: GetHomeRegionRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetHomeRegionResult> { return self.client.execute(operation: "GetHomeRegion", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension MigrationHubConfig { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: MigrationHubConfig, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
34068197f06d49f36fef1529d5adbcff
58.266667
811
0.700975
4.980392
false
true
false
false
DrabWeb/Sudachi
Sudachi/Sudachi/SCMusicBrowserController.swift
1
32495
// // SCMusicBrowserController.swift // Sudachi // // Created by Seth on 2016-04-07. // import Cocoa class SCMusicBrowserController: NSObject { /// The main view controller for the main window(The on this is in) @IBOutlet weak var mainViewController: ViewController! /// The array controller for the collection view @IBOutlet weak var arrayController : NSArrayController!; /// The items in arrayController as an NSMutableArray var browserItems : NSMutableArray = NSMutableArray(); /// The scroll view for musicBrowserCollectionView @IBOutlet weak var musicBrowserCollectionViewScrollView: NSScrollView! /// The collection view for displaying the music browser visually @IBOutlet weak var musicBrowserCollectionView: NSCollectionView! /// The view for letting users drop files into the music browser and import them @IBOutlet weak var musicBrowserDropView: SCMusicBrowserDropView! /// The SCMusicBrowserItems that are kept in the background and pulled from for displaying var musicBrowserItems : [SCMusicBrowserItem] = []; /// The text field for searching for items in the music browser @IBOutlet weak var searchField: SCSearchTextField! /// When searchField has text entered... @IBAction func searchFieldInteracted(sender: AnyObject) { // Search for the entered text searchFor(searchField.stringValue); } /// The container view for anything to show when a search is being processed @IBOutlet weak var searchingContainer: NSView! /// The label in searchingContainer that says "Searching..." @IBOutlet weak var searchingLabel: NSTextField! /// The container view for anything to show when there are no results @IBOutlet weak var noSearchResultsContainer: NSView! /// The label in noSearchResultsContainer that says "No Results" @IBOutlet weak var noSearchResultsLabel: NSTextField! /// Calls the same event as a double click on all the selected items in the music browser func openSelectedItems() { // Disable updating on the playlist(For speed improvements so it doesnt update on every possible song add) mainViewController.playlistController.canUpdate = false; // For every selected item... for(_, currentSelectionIndex) in musicBrowserCollectionView.selectionIndexes.enumerate() { /// The collection item at the current selection index let currentSelectedItem : SCMusicBrowserCollectionViewItem = musicBrowserCollectionView.itemAtIndex(currentSelectionIndex) as! SCMusicBrowserCollectionViewItem; // Call the open function for the current item currentSelectedItem.open(); } // Enable updating on the playlist mainViewController.playlistController.canUpdate = true; // Update the playlist mainViewController.playlistController.update(); } /// The current path the music browser is at var currentFolder : String = ""; /// Called when an item in the Music Browser is opened func browserItemOpened(browserItem : SCMusicBrowserItem) { // If the openSearch if browserItem is nil... if(browserItem.openSearch == nil) { // If the item is a folder... if(SCFileUtilities().isFolder((NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + browserItem.representedObjectPath)) { /// Display the items folder contents(First removes the MPD folder path from the represented path) displayItemsFromRelativePath(browserItem.representedObjectPath); } // If the item is a song... else { // Add the song to the playlist /// The temporary song to pass to the SCMPD.addSongToPlaylist let itemSong : SCSong = SCSong(); // Set the path itemSong.filePath = (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + browserItem.representedObjectPath; // Add the song to the playlist (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.addSongToPlaylist(itemSong, insert: false); } } // If the openSearch if browserItem is not nil... else { // Perform the search searchFor(browserItem.openSearch!); searchField.stringValue = lastSearch; } } /// Displays the items in the given path(Relative to the MPD folder) func displayItemsFromRelativePath(path : String) { // Clear the current browser items clearGrid(true); // Set the current folder currentFolder = path; // If the current folder isn't blank... if(currentFolder != "") { // Add the back item /// The item for letting the user go back to the previous folder let backBrowserItem : SCMusicBrowserItem = SCMusicBrowserItem(); // Set the path to the folder containing the current folder backBrowserItem.representedObjectPath = NSString(string: currentFolder).stringByDeletingLastPathComponent; // Set the display image to the back icon backBrowserItem.displayImage = SCThemingEngine().defaultEngine().folderBackIcon; // Set the title to "Bacl" backBrowserItem.displayTitle = "Back" // Add the back item to the grid addBrowserItem(backBrowserItem); // Show musicBrowserItems in the grid(I call this here and at the end so this item comes up before the loading is finished, it looks nicer) setGridToBrowserItems(); } // For every item in the given path... for(_, currentItemPath) in (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.runMpcCommand(["ls", path], waitUntilExit: true, log: true).componentsSeparatedByString("\n").enumerate() { /// The SCMusicBrowserItem for the current item in the path let currentBrowserItem : SCMusicBrowserItem = SCMusicBrowserItem(); // Set the current item's path currentBrowserItem.representedObjectPath = currentItemPath; // Load the item's display image currentBrowserItem.grabAndSetDisplayImage(); // If this item isnt a folder... if(!currentBrowserItem.isFolder) { // Set the display title to the file's name without the extension currentBrowserItem.displayTitle = NSString(string: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentBrowserItem.representedObjectPath).lastPathComponent.stringByReplacingOccurrencesOfString("." + NSString(string: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentBrowserItem.representedObjectPath).pathExtension, withString: ""); } // If this item is a folder... else { // Set the title to the folder's name currentBrowserItem.displayTitle = NSString(string: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentBrowserItem.representedObjectPath).lastPathComponent; } // Add the browser item addBrowserItem(currentBrowserItem); } // Remove the last item from the grid(Its for some reason a random item called "Music") removeBrowserItem(musicBrowserItems.last!, alsoMusicBrowserItems: true); // Show musicBrowserItems in the grid setGridToBrowserItems(); // If we arent in the root directory... if(currentFolder != "") { // Set the back item's target and action /// The SCMusicBrowserCollectionViewItem for the back item let backBrowserItemCollectionViewItem : SCMusicBrowserCollectionViewItem = (musicBrowserCollectionView.itemAtIndex(0)) as! SCMusicBrowserCollectionViewItem; // Set the target and action backBrowserItemCollectionViewItem.openTarget = self; backBrowserItemCollectionViewItem.openAction = Selector("openParentFolder"); // If the browser items length is greater than 1... if(musicBrowserItems.count > 1) { // For every SCMusicBrowserCollectionViewItem in the music browser collection view(Except the first one)... for currentIndex in 1...(musicBrowserItems.count - 1) { /// The SCMusicBrowserCollectionViewItem for the current index let currentBrowserItemCollectionViewItem : SCMusicBrowserCollectionViewItem = (musicBrowserCollectionView.itemAtIndex(currentIndex)) as! SCMusicBrowserCollectionViewItem; // Set the target and action currentBrowserItemCollectionViewItem.openTarget = self; currentBrowserItemCollectionViewItem.openAction = Selector("browserItemOpened:"); // Load the item's display image currentBrowserItemCollectionViewItem.imageView?.image = (currentBrowserItemCollectionViewItem.representedObject as! SCMusicBrowserItem).displayImage; } } else { // Display the message saying theres an error print("SCMusicBrowserController: No items in directory \"\(currentFolder)\", this usually means the server crashed"); } } // If we are in the root directory... else { // For every SCMusicBrowserCollectionViewItem in the music browser collection view... for currentIndex in 0...(musicBrowserItems.count - 1) { /// The SCMusicBrowserCollectionViewItem for the current index let currentBrowserItemCollectionViewItem : SCMusicBrowserCollectionViewItem = (musicBrowserCollectionView.itemAtIndex(currentIndex)) as! SCMusicBrowserCollectionViewItem; // Set the target and action currentBrowserItemCollectionViewItem.openTarget = self; currentBrowserItemCollectionViewItem.openAction = Selector("browserItemOpened:"); } } // Select the first item in the music browser collection view musicBrowserCollectionView.selectionIndexes = NSIndexSet(index: 0); } /// Called when the user drops files into the music browser. Moves the dropped files into the current directory, updates the database, and reloads the folder contents func filesDroppedIntoMusicBrowser(files : [String]) { // For every droppped file... for(_, currentFile) in files.enumerate() { do { // Move the current file to the current folder try NSFileManager.defaultManager().moveItemAtPath(currentFile, toPath: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentFolder + "/" + NSString(string: currentFile).lastPathComponent); } catch let error as NSError { // Print the error description print("SCMusicBrowserController: Failed to move files to current folder, \(error.description)"); } } // Update the database (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.updateDatabase(); // Sleep for a second so the database can update sleep(1); // Reload the current folder displayItemsFromRelativePath(currentFolder); } /// Adds the current songs in the music browser collection view to the playlist func openListedSongs() { // Disable updating on the playlist(For speed improvements so it doesnt update on every possible song add) mainViewController.playlistController.canUpdate = false; /// The amount of songs we added to the playlist var addedSongCount : Int = 0; // For every item in the music browser... for currentIndex in 0...((arrayController.arrangedObjects as! [AnyObject]).count - 1) { /// The collection item at the current index let currentItem : SCMusicBrowserCollectionViewItem = musicBrowserCollectionView.itemAtIndex(currentIndex) as! SCMusicBrowserCollectionViewItem; // If the current item is not a folder... if(!(currentItem.representedObject as! SCMusicBrowserItem).isFolder) { // Call the open function for the current item currentItem.open(); // Add one to the added song count addedSongCount++; } } // Enable updating on the playlist mainViewController.playlistController.canUpdate = true; // If we added any songs... if(addedSongCount > 0) { // Update the playlist mainViewController.playlistController.update(); } } /// Updates the music database and once finished reloads the current directory and shows a notification saying the update is done func updateDatabse() { // Update the database (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.updateDatabase(); /// The notification to say the database update finished let finishedNotification : NSUserNotification = NSUserNotification(); // Set the informative text finishedNotification.informativeText = "Database update finished"; // Deliver the notification NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(finishedNotification); // Reload the current directory displayItemsFromRelativePath(currentFolder); } /// The last entered search var lastSearch : String = ""; /// All the items from the search results var searchResultItems : [SCMusicBrowserItem] = []; /// Searches for the given string and displays the results func searchFor(searchString : String) { // Print to the log what we are searching for print("SCMusicBrowserController: Searching for \"\(searchString)\" in music browser"); // Set last search lastSearch = searchString; // Clear the results searchResultItems.removeAll(); // Make sure the no results container is hidden noSearchResultsContainer.hidden = true; // If the search string is blank... if(searchString == "") { // Go back to the directory the user was in displayItemsFromRelativePath(currentFolder); // Select the first item in the music browser collection view musicBrowserCollectionView.selectionIndexes = NSIndexSet(index: 0); } // If the search string has content... else { // Show the searching container searchingContainer.hidden = false; /// The arguments for "mpc search" var searchCommandArguments : [String] = ["search"]; // For every string in the search string split at every ", " for(_, currentSearch) in searchString.componentsSeparatedByString(", ").enumerate() { // If there was a ":" in the current search... if(currentSearch.rangeOfString(":") != nil) { /// The type to search for let searchType = currentSearch.substringToIndex(currentSearch.rangeOfString(":")!.startIndex); /// The query to search for var searchQuery = currentSearch.substringFromIndex(currentSearch.rangeOfString(":")!.startIndex.successor()); // If searchQuery isnt blank... if(searchQuery != "") { // If the first character in searchQuery is a " "... if(searchQuery.substringToIndex(searchQuery.startIndex.successor()) == " ") { // Remove the first character searchQuery = searchQuery.substringFromIndex(searchQuery.startIndex.successor()); } } // Add the search type and query to the search arguments searchCommandArguments.append(searchType); searchCommandArguments.append(searchQuery); } // If there wasnt a ":" in the current search... else { // Add the any type and set the query to the whole string searchCommandArguments.append("any"); searchCommandArguments.append(currentSearch); } } // For every search result... for(_, currentSearchResult) in (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.runMpcCommand(searchCommandArguments, waitUntilExit: true, log: true).componentsSeparatedByString("\n").enumerate() { // If the search result isnt blank(For some reason it puts an extra blank one on the end)... if(currentSearchResult != "") { // Clear the display grid clearGrid(false); // Add the current item to the grid /// The SCMusicBrowserItem for the current search result let currentResultBrowserItem : SCMusicBrowserItem = SCMusicBrowserItem(); // Set the current item's path currentResultBrowserItem.representedObjectPath = currentSearchResult; // Load the item's display image currentResultBrowserItem.grabAndSetDisplayImage(); // Set the display title to the file's name without the extension currentResultBrowserItem.displayTitle = NSString(string: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentResultBrowserItem.representedObjectPath).lastPathComponent.stringByReplacingOccurrencesOfString("." + NSString(string: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + currentResultBrowserItem.representedObjectPath).pathExtension, withString: ""); // Add the browser item to the results searchResultItems.append(currentResultBrowserItem); } } // Show the items setGridToBrowserItems(searchResultItems); // Set the open actions // If there is at least one search result... if(((arrayController.arrangedObjects as! [AnyObject]).count > 0)) { // For every SCMusicBrowserCollectionViewItem in the music browser collection view... for currentIndex in 0...((arrayController.arrangedObjects as! [AnyObject]).count - 1) { /// The SCMusicBrowserCollectionViewItem for the current index let currentBrowserItemCollectionViewItem : SCMusicBrowserCollectionViewItem = (musicBrowserCollectionView.itemAtIndex(currentIndex)) as! SCMusicBrowserCollectionViewItem; // Set the target and action currentBrowserItemCollectionViewItem.openTarget = self; currentBrowserItemCollectionViewItem.openAction = Selector("browserItemOpened:"); } } // Hide the searching container searchingContainer.hidden = true; // If searchResultItems is blank... if(searchResultItems.isEmpty) { // Show the no results container noSearchResultsContainer.hidden = false; } } } /// Removes the item at the given index from the grid, and also musicBrowserItems if alsoMusicBrowserItems is true func removeBrowserItemAtIndex(index : Int, alsoMusicBrowserItems : Bool) { // Remove the item from the arrayController arrayController.removeObject(musicBrowserItems[index]); // If we said to also remove it from musicBrowserItems... if(alsoMusicBrowserItems) { // Remove the object from musicBrowserItems musicBrowserItems.removeAtIndex(index); } } /// Removes the given item from the grid, and also musicBrowserItems if alsoMusicBrowserItems is true func removeBrowserItem(item : SCMusicBrowserItem, alsoMusicBrowserItems : Bool) { // Remove the given item from the array controller arrayController.removeObject(item); // If we said to also remove it from musicBrowserItems... if(alsoMusicBrowserItems) { // Cast musicBrowserItems into an NSMutableArray, remove the object, and turn it back into an [SCMusicBrowserItem] and store it back in musicBrowserItems let musicBrowserItemsMutable : NSMutableArray = NSMutableArray(array: musicBrowserItems); musicBrowserItemsMutable.removeObject(item); musicBrowserItems = (Array(musicBrowserItemsMutable) as! [SCMusicBrowserItem]); } } /// Adds the given SCMusicBrowserItem to musicBrowserItems func addBrowserItem(item : SCMusicBrowserItem) { // Add the item to musicBrowserItems musicBrowserItems.append(item); } /// Adds the given SCMusicBrowserItem to the grid func addBrowserItemToGrid(item : SCMusicBrowserItem) { // Add the item to arrayController arrayController.addObject(item); } /// Sets the grid to the given array of SCMusicBrowserItems func setGridToBrowserItems(browserItems : [SCMusicBrowserItem]) { // Clear the current items clearGrid(false); // Add all the objects in browserItems to arrayController arrayController.addObjects(browserItems); // If there is at least one item in the array controller... if((arrayController.arrangedObjects as! [AnyObject]).count > 0) { // For every grid item... for currentIndex in 0...((arrayController.arrangedObjects as! [AnyObject]).count - 1) { // Set if this item's image view wants a shadow (musicBrowserCollectionView.itemAtIndex(currentIndex)!.imageView as! SCMusicBrowserCollectionViewItemImageView).wantsShadow = SCThemingEngine().defaultEngine().musicBrowserItemShadowEnabled; } } } /// Sets the grid to match musicBrowserItems func setGridToBrowserItems() { // Add all the items in musicBrowserItems to the grid setGridToBrowserItems(musicBrowserItems); } /// Clears arrayController, also clears musicBrowserItems if you set alsoMusicBrowserItems to true func clearGrid(alsoMusicBrowserItems : Bool) { // Remove all the objects from the grid array controller arrayController.removeObjects(arrayController.arrangedObjects as! [AnyObject]); // if we also want to clear musicBrowserItems... if(alsoMusicBrowserItems) { // Clear musicBrowserItems musicBrowserItems.removeAll(); } } /// Opens the root of the user's music folder func openRootFolder() { // Open the root folder displayItemsFromRelativePath(""); } /// Opens the parent folder of the current folder(Does nothing if we are in the root of the music directory) func openParentFolder() { // If currentFolder isnt blank... if(currentFolder != "") { // Open the enclosing folder displayItemsFromRelativePath(NSString(string: currentFolder).stringByDeletingLastPathComponent); } } /// Makes searchField the first responder func selectSearchField() { (NSApplication.sharedApplication().delegate as! AppDelegate).mainWindow?.makeFirstResponder(searchField); } /// Makes musicBrowserCollectionView the first responder func selectMusicBrowser() { (NSApplication.sharedApplication().delegate as! AppDelegate).mainWindow?.makeFirstResponder(musicBrowserCollectionView); } /// Sets up the menu items for this controller func setupMenuItems() { // Setup the menu items // Set the targets (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemOpenSelectedItem.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemOpenSelectedItemsEnter.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemSelectSearchField.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemSelectMusicBrowser.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemEnclosingFolder.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemUpdateMpdDatabase.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemAddListedSongs.target = self; (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemHome.target = self; // Set the actions (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemOpenSelectedItem.action = Selector("openSelectedItems"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemOpenSelectedItemsEnter.action = Selector("openSelectedItems"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemSelectSearchField.action = Selector("selectSearchField"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemSelectMusicBrowser.action = Selector("selectMusicBrowser"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemEnclosingFolder.action = Selector("openParentFolder"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemUpdateMpdDatabase.action = Selector("updateDatabse"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemAddListedSongs.action = Selector("openListedSongs"); (NSApplication.sharedApplication().delegate as! AppDelegate).menuItemHome.action = Selector("openRootFolder"); } /// Loads in the theme variables from SCThemingEngine func loadTheme() { // Set the minimum and maximum item sizes musicBrowserCollectionView.minItemSize = SCThemingEngine().defaultEngine().musicBrowserMinimumItemSize; musicBrowserCollectionView.maxItemSize = SCThemingEngine().defaultEngine().musicBrowserMaximumItemSize; // Set the searching labek color searchingLabel.textColor = SCThemingEngine().defaultEngine().musicBrowserSearchingTextColor; // Set the no results label color noSearchResultsLabel.textColor = SCThemingEngine().defaultEngine().musicBrowserNoResultsTextColor; } func initialize() { // Load the theme loadTheme(); // Setup the menu items setupMenuItems(); // Set the collection view's prototype item musicBrowserCollectionView.itemPrototype = NSStoryboard(name: "Main", bundle: NSBundle.mainBundle()).instantiateControllerWithIdentifier("musicBrowserCollectionViewItem") as! SCMusicBrowserCollectionViewItem; // Set the drop view's target and action musicBrowserDropView.dropTarget = self; musicBrowserDropView.dropAction = Selector("filesDroppedIntoMusicBrowser:"); // Display the root of the music folder openRootFolder(); } } class SCMusicBrowserItem: NSObject { /// The image to show for the item var displayImage : NSImage = NSImage(); /// The title to show for the item var displayTitle : String = "Error: Failed to load title"; /// The path of the file/folder this item represents var representedObjectPath : String = ""; /// The search to perform when this item is opened(Only performs if it is not nil) var openSearch : String? = nil; /// Is this item a folder? var isFolder : Bool { // Return if the item at representedObjectPath is a folder return SCFileUtilities().isFolder((NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + representedObjectPath); } /// Sets the display image to the proper image func grabAndSetDisplayImage() { // If the represented path is set... if(representedObjectPath != "") { // If this item is a folder... if(isFolder) { /// The NSURL of representedObjectPath let folderUrl : NSURL = NSURL(fileURLWithPath: (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + representedObjectPath); // For every item in this folders contents... for(_, currentFile) in NSFileManager.defaultManager().enumeratorAtURL(folderUrl, includingPropertiesForKeys: nil, options: [NSDirectoryEnumerationOptions.SkipsHiddenFiles, NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants], errorHandler: nil)!.enumerate() { /// The path of the current file let currentFilePath : String = currentFile.absoluteString.stringByReplacingOccurrencesOfString("file://", withString: "").stringByRemovingPercentEncoding!; // If the current file is an image... if(SCConstants().realisticImageFileTypes.contains(NSString(string: currentFilePath).pathExtension)) { // Set the display image to this image displayImage = NSImage(contentsOfFile: currentFilePath)!; // Mask the display image to the folder icon displayImage = displayImage.maskWith(SCThemingEngine().defaultEngine().folderIcon); } } // If the display image wasnt set... if(displayImage.size == NSSize.zero) { // Set the display image to the folder icon displayImage = SCThemingEngine().defaultEngine().folderIcon; } } // If this item is a file... else { // Set the display image to the cover of this file /// The temporary song to grab the cover image of this item let song : SCSong = SCSong(); // Set the song's path song.filePath = (NSApplication.sharedApplication().delegate as! AppDelegate).SudachiMPD.mpdFolderPath + representedObjectPath; // Set the display image to the song's cover image displayImage = song.getCoverImage(); // Mask the art displayImage = displayImage.maskWith(SCThemingEngine().defaultEngine().musicBrowserArtMask); } } } // Init with a title and image init(displayImage : NSImage, displayTitle : String) { self.displayImage = displayImage; self.displayTitle = displayTitle; } // Blank init override init() { super.init(); self.displayImage = NSImage(); self.displayTitle = "Error: Failed to load title"; self.representedObjectPath = ""; } }
gpl-3.0
5e2593062b8640a1f3ab7b99a89cdfdb
49.146605
458
0.638006
5.783057
false
false
false
false
cuappdev/podcast-ios
old/Podcast/UserPreferences.swift
1
4133
// // UserPreferences.swift // Podcast // // Created by Natasha Armbrust on 3/20/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import Foundation class SeriesPreferences: NSObject, NSCoding { var playerRate: PlayerRate var trimSilences: Bool //TODO struct Keys { static let rate = "rate" static let trimSilence = "trim_silence" } convenience init?(data: Data) { if let prefs = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? SeriesPreferences { self.init(playerRate: prefs.playerRate, trimSilences: prefs.trimSilences) } return nil } override convenience init() { self.init(playerRate: .one, trimSilences: false) } init(playerRate: PlayerRate, trimSilences: Bool) { self.playerRate = playerRate self.trimSilences = trimSilences } required convenience init(coder decoder: NSCoder) { self.init() self.playerRate = PlayerRate(rawValue: decoder.decodeFloat(forKey: Keys.rate)) ?? .one self.trimSilences = decoder.decodeBool(forKey: Keys.trimSilence) } func encode(with aCoder: NSCoder) { aCoder.encode(playerRate.rawValue, forKey: Keys.rate) aCoder.encode(trimSilences, forKey: Keys.trimSilence) } } class UserPreferences { static let key: String = "user-prefs" static let defaultPlayerRateKey: String = "default-player-rate" // userId: [seriesId: prefs] -> may have more than one user due to logging out ability static var userPreferences: [String: [String: SeriesPreferences]] { get { if let savedData = UserDefaults.standard.value(forKey: UserPreferences.key) as? Data, let savedPrefs = NSKeyedUnarchiver.unarchiveObject(with: savedData) { return (savedPrefs as? [String: [String: SeriesPreferences]]) ?? [:] } else { // nothing saved yet let prefs: [String: [String: SeriesPreferences]] = [:] let prefsData = NSKeyedArchiver.archivedData(withRootObject: prefs) UserDefaults.standard.set(prefsData, forKey: UserPreferences.key) return prefs } } } static func userToSeriesPreference(for user: User, seriesId: String) -> SeriesPreferences? { guard let usersPrefs = UserPreferences.userPreferences[user.id], let seriesPrefs = usersPrefs[seriesId] else { return nil } return seriesPrefs } static func savePreference(preference: SeriesPreferences, for user: User, and seriesId: String) { var currentPreferences = self.userPreferences if var userPrefs = currentPreferences[user.id] { // this user exists in preferences saved userPrefs[seriesId] = preference currentPreferences[user.id] = userPrefs } else { currentPreferences[user.id] = [seriesId: preference] } let prefsData = NSKeyedArchiver.archivedData(withRootObject: currentPreferences) UserDefaults.standard.set(prefsData, forKey: UserPreferences.key) } static func removePreference(for user: User, and seriesId: String) { var currentPreferences = self.userPreferences if var userPrefs = currentPreferences[user.id] { // this user exists in preferences saved userPrefs.removeValue(forKey: seriesId) currentPreferences[user.id] = userPrefs } let prefsData = NSKeyedArchiver.archivedData(withRootObject: currentPreferences) UserDefaults.standard.set(prefsData, forKey: UserPreferences.key) } static var defaultPlayerRate: PlayerRate { get { if let rate = PlayerRate(rawValue: UserDefaults.standard.float(forKey: UserPreferences.defaultPlayerRateKey)) { return rate } else { // nothing saved yet saveDefaultPlayerRate(rate: .one) return .one } } } static func saveDefaultPlayerRate(rate: PlayerRate) { UserDefaults.standard.set(rate.rawValue, forKey: UserPreferences.defaultPlayerRateKey) } }
mit
9a34a96ca2871ab8225c1e14fec6ceb7
37.259259
167
0.662633
4.491304
false
false
false
false
suifengqjn/swiftDemo
Swift基本语法-黑马笔记/字符和字符串/main.swift
1
1569
// // main.swift // 字符和字符串 // // Created by 李南江 on 15/2/28. // Copyright (c) 2015年 itcast. All rights reserved. // import Foundation /* 字符: OC: char charValue = 'a'; */ var charValue1:Character = "a" /* Swift和OC字符不一样 1.Swift是用双引号 2.Swift中的字符类型和OC中的也不一样, OC中的字符占一个字节,因为它只包含ASCII表中的字符, 而Swift中的字符除了可以存储ASCII表中的字符还可以存储unicode字符, 例如中文: OC:char charValue = '李'; // 错误 Swift: var charValue2:Character = "李" // 正确 OC的字符是遵守ASCII标准的,Swift的字符是遵守unicode标准的, 所以可以存放时间上所有国家语言的字符(大部分) */ var charValue2:Character = "李" //正确 /* 注意: 双引号中只能放一个字符, 如下是错误写法 var charValue3:Character = "ab" */ /* 字符串: 字符是单个字符的集合, 字符串是多个字符的集合, 想要存放多个字符需要使用字符串 C: char *stringValue = "ab"; char stringArr = "ab"; OC: NSString *stringValue = "ab"; */ var stringValue1 = "ab" /* C语言中的字符串是以\0结尾的, 例如: char *stringValue = "abc\0bcd"; printf("%s", stringValue); 打印结果为abc OC语言中的字符串也是以\0结尾的, 例如: NSString *stringValue = @"abc\0bcd"; NSLog(@"%@", stringValue); 打印结果为abc */ var stringValue2 = "abc\0bcd" print(stringValue2) // 打印结果为abcbcd // 从此可以看出Swift中的字符串和C语言/OC语言中的字符串是不一样的
apache-2.0
395f72823569de0a8c8585aa267aa449
15.138462
96
0.71306
2.428241
false
false
false
false
sbooth/SFBAudioEngine
Metadata/SFBAudioMetadata.swift
1
2459
// // Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]> // Part of https://github.com/sbooth/SFBAudioEngine // MIT license // import Foundation extension AudioMetadata { /// The compilation flag public var isCompilation: Bool? { get { __compilation?.boolValue } set { __compilation = newValue != nil ? newValue! as NSNumber : nil } } /// The track number public var trackNumber: Int? { get { __trackNumber?.intValue } set { __trackNumber = newValue != nil ? newValue! as NSNumber : nil } } /// The track total public var trackTotal: Int? { get { __trackTotal?.intValue } set { __trackTotal = newValue != nil ? newValue! as NSNumber : nil } } /// The disc number public var discNumber: Int? { get { __discNumber?.intValue } set { __discNumber = newValue != nil ? newValue! as NSNumber : nil } } /// The disc total public var discTotal: Int? { get { __discTotal?.intValue } set { __discTotal = newValue != nil ? newValue! as NSNumber : nil } } /// The beats per minute (BPM) public var bpm: Int? { get { __bpm?.intValue } set { __bpm = newValue != nil ? newValue! as NSNumber : nil } } /// The rating public var rating: Int? { get { __rating?.intValue } set { __rating = newValue != nil ? newValue! as NSNumber : nil } } /// The replay gain reference loudness public var replayGainReferenceLoudness: Double? { get { __replayGainReferenceLoudness?.doubleValue } set { __replayGainReferenceLoudness = newValue != nil ? newValue! as NSNumber : nil } } /// The replay gain track gain public var replayGainTrackGain: Double? { get { __replayGainTrackGain?.doubleValue } set { __replayGainTrackGain = newValue != nil ? newValue! as NSNumber : nil } } /// The replay gain track peak public var replayGainTrackPeak: Double? { get { __replayGainTrackPeak?.doubleValue } set { __replayGainTrackPeak = newValue != nil ? newValue! as NSNumber : nil } } /// The replay gain album gain public var replayGainAlbumGain: Double? { get { __replayGainAlbumGain?.doubleValue } set { __replayGainAlbumGain = newValue != nil ? newValue! as NSNumber : nil } } /// The replay gain album peak public var replayGainAlbumPeak: Double? { get { __replayGainAlbumPeak?.doubleValue } set { __replayGainAlbumPeak = newValue != nil ? newValue! as NSNumber : nil } } }
mit
cb8cc74b97fc241af157a361cbb497d5
18.062016
80
0.636844
3.201823
false
false
false
false
jspahrsummers/RxSwift
RxSwift/EnumerableBuffer.swift
1
1986
// // EnumerableBuffer.swift // RxSwift // // Created by Justin Spahr-Summers on 2014-06-26. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation /// A controllable Enumerable that functions as a combination push- and /// pull-driven stream. @final class EnumerableBuffer<T>: Enumerable<T>, Sink { typealias Element = Event<T> let _capacity: Int? let _queue = dispatch_queue_create("com.github.ReactiveCocoa.EnumerableBuffer", DISPATCH_QUEUE_SERIAL) var _enumerators: Enumerator<T>[] = [] var _eventBuffer: Event<T>[] = [] var _terminated = false /// Creates a buffer for events up to the given maximum capacity. /// /// If more than `capacity` values are received, the earliest values will be /// dropped and won't be enumerated over in the future. init(capacity: Int? = nil) { assert(capacity == nil || capacity! > 0) _capacity = capacity super.init(enumerate: { enumerator in dispatch_barrier_sync(self._queue) { self._enumerators.append(enumerator) for event in self._eventBuffer { enumerator.put(event) } } enumerator.disposable.addDisposable { dispatch_barrier_async(self._queue) { self._enumerators = removeObjectIdenticalTo(enumerator, fromArray: self._enumerators) } } }) } /// Stores the given event in the buffer, evicting the earliest event if the /// buffer would be over capacity, then forwards it to all waiting /// enumerators. /// /// If a terminating event is put into the buffer, it will stop accepting /// any further events (to obey the contract of Enumerable). func put(event: Event<T>) { dispatch_barrier_sync(_queue) { if (self._terminated) { return } self._eventBuffer.append(event) if let capacity = self._capacity { while self._eventBuffer.count > capacity { self._eventBuffer.removeAtIndex(0) } } self._terminated = event.isTerminating for enumerator in self._enumerators { enumerator.put(event) } } } }
mit
7462f806deb9c1384bead6db343b712d
25.837838
103
0.689829
3.527531
false
false
false
false
alexjohnj/spotijack
LibSpotijackTests/SpotijackSession Tests/SpotijackSessionSpotijackingTests.swift
1
15324
// // SpotijackSessionSpotijackingTests.swift // LibSpotijackTests // // Created by Alex Jackson on 11/08/2017. // Copyright © 2017 Alex Jackson. All rights reserved. // import XCTest import Foundation @testable import LibSpotijack //swiftlint:disable:next type_body_length internal class SpotijackSessionSpotijackingTests: XCTestCase { // MARK: - General Polling func testStartStopPolling() { let (session, _, _) = SpotijackSessionManager.makeStandardApplications() session.startPolling(every: 1.0) XCTAssertNotNil(session._applicationPollingTimer) XCTAssertTrue(session.isPolling) session.stopPolling() XCTAssertFalse(session.isPolling) XCTAssertNil(session._applicationPollingTimer) } func testStartPollingRespectsInterval() { let expectedInterval: TimeInterval = 1.0 let (session, _, _) = SpotijackSessionManager.makeStandardApplications() session.startPolling(every: expectedInterval) XCTAssertEqual(session._applicationPollingTimer?.timeInterval, expectedInterval) } // MARK: - Spotijacking Specific func testSpotijackingWithAsyncDelayGeneratesFiles() { let expectedRecordingCount = 2 var receivedRecordingCount: Int? let spotijackingExpectation = expectation(description: "Waiting for Spotijacking process to finish") let (session, spotify, ahp) = SpotijackSessionManager.makeStandardApplications() let recordingConfiguration = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 0.1, recordingStartDelay: 0.1) XCTAssertNoThrow(try session.startSpotijacking(config: recordingConfiguration)) // The delays here are to account for the pause Spotijack takes between starting new recordings. let queue = DispatchQueue.global(qos: .userInitiated) let waitTime = { DispatchTime.now() + 0.15 } queue.asyncAfter(deadline: waitTime()) { spotify.nextTrack() queue.asyncAfter(deadline: waitTime()) { spotify.nextTrack() queue.asyncAfter(deadline: waitTime()) { receivedRecordingCount = ahp._recordings.count spotijackingExpectation.fulfill() } } } wait(for: [spotijackingExpectation], timeout: 1.0) session.stopSpotijacking() XCTAssertNotNil(receivedRecordingCount) XCTAssertEqual(receivedRecordingCount, expectedRecordingCount) } func testSpotijackingWithoutAsyncDelayGeneratesFiles() { let expectedRecordingCount = 2 let (session, spotify, ahp) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 50, // Will poll manually recordingStartDelay: 0) XCTAssertNoThrow(try session.startSpotijacking(config: config)) let nextTrack = { session._applicationPollingTimer?.fire() spotify.nextTrack() session._applicationPollingTimer?.fire() } // Simulate three track changes producing two recordings nextTrack() nextTrack() XCTAssertEqual(ahp._recordings.count, expectedRecordingCount) } func testEndingSpotijackingGeneratesARecordingFile() { let expectedRecordingCount = 3 let (session, spotify, ahp) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 50, recordingStartDelay: 0) let nextTrack = { session._applicationPollingTimer?.fire() spotify.nextTrack() session._applicationPollingTimer?.fire() } XCTAssertNoThrow(try session.startSpotijacking(config: config)) nextTrack() // Recording 1 nextTrack() // Recording 2 session.stopSpotijacking() // Should generate recording 3 XCTAssertEqual(ahp._recordings.count, expectedRecordingCount) } func testReachingEndOfPlaybackQueuePostsNotification() { var notificationWasPosted = false let (session, spotify, _) = SpotijackSessionManager.makeStandardApplications() let obs = session.notificationCenter.addObserver(forType: DidReachEndOfPlaybackQueue.self, object: session, queue: .main, using: { _ in notificationWasPosted = true }) let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 50.0, recordingStartDelay: 0) XCTAssertNoThrow(try session.startSpotijacking(config: config)) session._applicationPollingTimer?.fire() let nextTrack = { session._applicationPollingTimer?.fire() spotify.nextTrack() session._applicationPollingTimer?.fire() } for _ in 0..<3 { nextTrack() } XCTAssertTrue(notificationWasPosted) } func testReachingEndOfPlaybackQueueEndsSpotijacking() { let (session, spotify, _) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 50.0, recordingStartDelay: 0.0) XCTAssertNoThrow(try session.startSpotijacking(config: config)) let nextTrack = { session._applicationPollingTimer?.fire() spotify.nextTrack() session._applicationPollingTimer?.fire() } for _ in 0..<3 { nextTrack() } XCTAssertFalse(session.isSpotijacking) } func testEndingSpotijackingResumesPollingAtPreviousInterval() { let expectedInterval = 42.0 let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: expectedInterval + 1, recordingStartDelay: 0.0) let (session, _, _) = SpotijackSessionManager.makeStandardApplications() session.startPolling(every: expectedInterval) XCTAssertNoThrow(try session.startSpotijacking(config: config)) XCTAssertNotEqual(session._applicationPollingTimer?.timeInterval, expectedInterval) session.stopSpotijacking() XCTAssertEqual(session._applicationPollingTimer?.timeInterval, expectedInterval) } func testEndSpotijackingWithoutPreviousPollingIntervalStopsPolling() { let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 42.0, recordingStartDelay: 0.0) let (session, _, _) = SpotijackSessionManager.makeStandardApplications() session.stopPolling() // Ensure polling has not been started XCTAssertNoThrow(try session.startSpotijacking(config: config)) session.stopSpotijacking() XCTAssertNil(session._applicationPollingTimer) } func testStartNewRecordingUpdatesAudioHijackProSessionTags() { let (session, spotify, ahp) = SpotijackSessionManager.makeStandardApplications() let ahpSession = ahp._sessions.first(where: { $0.name == "Spotijack" })! let expectedTrack = spotify._playbackQueue.first! let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 1, recordingStartDelay: 0.0) XCTAssertNoThrow(try session.startSpotijacking(config: config)) session.stopSpotijacking() XCTAssertEqual(ahpSession._titleTag, expectedTrack.name) XCTAssertEqual(ahpSession._albumTag, expectedTrack.album) XCTAssertEqual(ahpSession._artistTag, expectedTrack.artist) XCTAssertEqual(ahpSession._albumArtistTag, expectedTrack.albumArtist) XCTAssertEqual(ahpSession._discNumberTag, String(describing: expectedTrack.discNumber)) XCTAssertEqual(ahpSession._trackNumberTag, String(describing: expectedTrack.trackNumber)) } /// Test ending a recording via the Audio Hijack Pro application also ends Spotijacking. Failure to do so would lead /// to an inconsistent internal state. func testEndRecordingViaAHPEndsSpotijacking() { let (session, _, ahp) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: false, disableShuffling: false, disableRepeat: false, pollingInterval: 50.0, recordingStartDelay: 0.0) let ahpSession = ahp._sessions.first(where: { $0.name == "Spotijack" })! XCTAssertNoThrow(try session.startSpotijacking(config: config)) ahpSession.stopRecording() session.pollSpotify() session.pollAudioHijackPro() XCTAssertFalse(session.isSpotijacking) } func testEndingSpotijackingPostsNotification() { let (session, _, _) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration() var wasNotified = false let obs = session.notificationCenter.addObserver(forType: DidEndSpotijacking.self, object: session, queue: .main, using: { _ in wasNotified = true }) XCTAssertNoThrow(try session.startSpotijacking(config: config)) session.stopSpotijacking() XCTAssertTrue(wasNotified) } // MARK: - Recording Configuration func testStartSpotijackingRespectsDisableShufflingConfiguration() { let (session, spotify, _) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: true, disableShuffling: true, disableRepeat: true, pollingInterval: 50, recordingStartDelay: 0.0) spotify.setShuffling(true) XCTAssertNoThrow(try session.startSpotijacking(config: config)) XCTAssertFalse(spotify.shuffling) } func testStartSpotijackingRespectsDisableRepeatingConfiguration() { let (session, spotify, _) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: true, disableShuffling: true, disableRepeat: true, pollingInterval: 50, recordingStartDelay: 0.0) spotify.setRepeating(true) XCTAssertNoThrow(try session.startSpotijacking(config: config)) XCTAssertFalse(spotify.repeating) } func testStartSpotijackingRespectsMuteSessionRecordingConfiguration() { let (session, _, ahp) = SpotijackSessionManager.makeStandardApplications() let ahpSession = ahp._sessions.first(where: { $0.name == "Spotijack" })! let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: true, disableShuffling: true, disableRepeat: true, pollingInterval: 50, recordingStartDelay: 0.0) ahpSession.setSpeakerMuted(true) XCTAssertNoThrow(try session.startSpotijacking(config: config)) XCTAssertTrue(ahpSession.speakerMuted) } func testStartSpotijackingRespectsRecordingConfigurationPollingInterval() { let expectedInterval = 50.0 let (session, _, _) = SpotijackSessionManager.makeStandardApplications() let config = SpotijackSessionManager.RecordingConfiguration(muteSpotify: true, disableShuffling: true, disableRepeat: true, pollingInterval: expectedInterval, recordingStartDelay: 0.0) XCTAssertNoThrow(try session.startSpotijacking(config: config)) XCTAssertEqual(session._applicationPollingTimer?.timeInterval, expectedInterval) } }
mit
842c586bec4db7b6c0137c11d2346846
48.912052
120
0.55557
6.114525
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/ReaderCardDiscoverAttributionView.swift
2
9490
import Foundation import WordPressShared @objc public protocol ReaderCardDiscoverAttributionViewDelegate: NSObjectProtocol { func attributionActionSelectedForVisitingSite(_ view: ReaderCardDiscoverAttributionView) } private enum ReaderCardDiscoverAttribution: Int { case none // Default, no action case visitSite // Action for verbose attribution to visit a site } @objc open class ReaderCardDiscoverAttributionView: UIView, NibLoadable { fileprivate let gravatarImageName = "gravatar" fileprivate let blavatarImageName = "post-blavatar-placeholder" @IBOutlet fileprivate weak var imageView: CircularImageView! @IBOutlet fileprivate weak var textLabel: UILabel! fileprivate lazy var originalAttributionParagraphAttributes: [NSAttributedString.Key: Any] = { return WPStyleGuide.originalAttributionParagraphAttributes() }() fileprivate var attributionAction: ReaderCardDiscoverAttribution = .none { didSet { // Enable/disable userInteraction on self if we allow an action. self.isUserInteractionEnabled = attributionAction != .none } } @objc weak var delegate: ReaderCardDiscoverAttributionViewDelegate? override open var backgroundColor: UIColor? { didSet { applyOpaqueBackgroundColors() } } var displayAsLink = false // MARK: - Lifecycle Methods open override func awakeFromNib() { super.awakeFromNib() // Add a tap gesture for detecting a tap on the label and acting on the current attributionAction. //// Ideally this would have independent tappable links but this adds a bit of overrhead for text/link detection //// on a UILabel. We might consider migrating to somethnig lik TTTAttributedLabel for more discrete link //// detection via UILabel. //// Also, rather than detecting a tap on the whole view, we add it to the label and imageView specifically, //// to avoid accepting taps outside of the label's text content, on display. //// Brent C. Aug/23/2016 let selector = #selector(ReaderCardDiscoverAttributionView.textLabelTapGesture(_:)) let labelTap = UITapGestureRecognizer(target: self, action: selector) textLabel.addGestureRecognizer(labelTap) // Also add a tap recognizer on the imageView. let imageTap = UITapGestureRecognizer(target: self, action: selector) imageView.addGestureRecognizer(imageTap) // Enable userInteraction on the label/imageView by default while userInteraction // is toggled on self in attributionAction: didSet for valid actions. textLabel.isUserInteractionEnabled = true imageView.isUserInteractionEnabled = true backgroundColor = .listForeground applyOpaqueBackgroundColors() } // MARK: - Configuration /** Applies opaque backgroundColors to all subViews to avoid blending, for optimized drawing. */ fileprivate func applyOpaqueBackgroundColors() { imageView?.backgroundColor = backgroundColor textLabel?.backgroundColor = backgroundColor } @objc open func configureView(_ contentProvider: ReaderPostContentProvider?) { if contentProvider?.sourceAttributionStyle() == SourceAttributionStyle.post { configurePostAttribution(contentProvider!) } else if contentProvider?.sourceAttributionStyle() == SourceAttributionStyle.site { configureSiteAttribution(contentProvider!, verboseAttribution: false) } else { reset() } } @objc open func configureViewWithVerboseSiteAttribution(_ contentProvider: ReaderPostContentProvider?) { if let contentProvider = contentProvider { configureSiteAttribution(contentProvider, verboseAttribution: true) } else { reset() } } fileprivate func reset() { imageView.image = nil textLabel.attributedText = nil attributionAction = .none } fileprivate func configurePostAttribution(_ contentProvider: ReaderPostContentProvider) { let url = contentProvider.sourceAvatarURLForDisplay() let placeholder = UIImage(named: gravatarImageName) imageView.downloadImage(from: url, placeholderImage: placeholder) imageView.shouldRoundCorners = true let str = stringForPostAttribution(contentProvider.sourceAuthorNameForDisplay(), blogName: contentProvider.sourceBlogNameForDisplay()) let attributes = originalAttributionParagraphAttributes textLabel.attributedText = NSAttributedString(string: str, attributes: attributes) attributionAction = .none } fileprivate func configureSiteAttribution(_ contentProvider: ReaderPostContentProvider, verboseAttribution verbose: Bool) { let url = contentProvider.sourceAvatarURLForDisplay() let placeholder = UIImage(named: blavatarImageName) imageView.downloadImage(from: url, placeholderImage: placeholder) imageView.shouldRoundCorners = false let blogName = contentProvider.sourceBlogNameForDisplay() let pattern = patternForSiteAttribution(verbose) let str = String(format: pattern, blogName!) let range = (str as NSString).range(of: blogName!) let font = WPStyleGuide.fontForTextStyle(WPStyleGuide.originalAttributionTextStyle(), symbolicTraits: .traitItalic) let attributes = originalAttributionParagraphAttributes let attributedString = NSMutableAttributedString(string: str, attributes: attributes) attributedString.addAttribute(.font, value: font, range: range) if !displayAsLink { WPStyleGuide.applyReaderCardAttributionLabelStyle(textLabel) } else { textLabel.textColor = .primary textLabel.highlightedTextColor = .primary } textLabel.attributedText = attributedString attributionAction = .visitSite } fileprivate func stringForPostAttribution(_ authorName: String?, blogName: String?) -> String { var str = "" if (authorName != nil) && (blogName != nil) { let pattern = NSLocalizedString("Originally posted by %@ on %@", comment: "Used to attribute a post back to its original author and blog. The '%@' characters are placholders for the author's name, and the author's blog repsectively.") str = String(format: pattern, authorName!, blogName!) } else if authorName != nil { let pattern = NSLocalizedString("Originally posted by %@", comment: "Used to attribute a post back to its original author. The '%@' characters are a placholder for the author's name.") str = String(format: pattern, authorName!) } else if blogName != nil { let pattern = NSLocalizedString("Originally posted on %@", comment: "Used to attribute a post back to its original blog. The '%@' characters are a placholder for the blog name.") str = String(format: pattern, blogName!) } return str } fileprivate func patternForSiteAttribution(_ verbose: Bool) -> String { var pattern: String if verbose { pattern = NSLocalizedString("Visit %@ for more", comment: "A call to action to visit the specified blog. The '%@' characters are a placholder for the blog name.") } else { pattern = NSLocalizedString("Visit %@", comment: "A call to action to visit the specified blog. The '%@' characters are a placholder for the blog name.") } return pattern } // MARK: - Touches open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) // Add highlight if the touch begins inside of the textLabel's frame guard let touch: UITouch = event?.allTouches?.first else { return } if textLabel.bounds.contains(touch.location(in: textLabel)) { textLabel.isHighlighted = true } } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) // Remove highlight if the touch moves outside of the textLabel's frame guard textLabel.isHighlighted else { return } guard let touch: UITouch = event?.allTouches?.first else { return } if !textLabel.bounds.contains(touch.location(in: textLabel)) { textLabel.isHighlighted = false } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard textLabel.isHighlighted else { return } textLabel.isHighlighted = false } open override func touchesCancelled(_ touches: Set<UITouch>?, with event: UIEvent?) { super.touchesCancelled(touches!, with: event) guard textLabel.isHighlighted else { return } textLabel.isHighlighted = false } // MARK: - Actions @objc open func textLabelTapGesture(_ gesture: UITapGestureRecognizer) { switch attributionAction { case .visitSite: delegate?.attributionActionSelectedForVisitingSite(self) default: break } } }
gpl-2.0
566cef8950b44c2e92de556120ff11d5
39.042194
186
0.677239
5.582353
false
false
false
false
mentalfaculty/impeller
Sources/Forest.swift
1
5672
// // Forest.swift // Impeller // // Created by Drew McCormack on 05/02/2017. // Copyright © 2017 Drew McCormack. All rights reserved. // import Foundation public class ConflictResolver { func resolved(fromConflictOf valueTree: ValueTree, with otherValueTree: ValueTree) -> ValueTree { return valueTree.metadata.timestamp >= otherValueTree.metadata.timestamp ? valueTree : otherValueTree } } public protocol ForestSerializer { func load(from url:URL) throws -> Forest func save(_ forest:Forest, to url:URL) throws } public struct Forest: Sequence { private var valueTreesByReference = [ValueTreeReference:ValueTree]() public init() {} public init(valueTrees: [ValueTree]) { for tree in valueTrees { self.valueTreesByReference[tree.valueTreeReference] = tree } } public var absenteeProvider: (([ValueTreeReference]) -> [ValueTree?])? public func makeIterator() -> AnyIterator<ValueTree> { let trees = Array(valueTreesByReference.values) var i = -1 return AnyIterator { i += 1 return i < trees.count ? trees[i] : nil } } public mutating func deleteValueTrees(descendentFrom reference: ValueTreeReference) { let timestamp = Date.timeIntervalSinceReferenceDate let plantedTree = PlantedValueTree(forest: self, root: reference) for ref in plantedTree { var tree = valueTree(at: ref)! tree.metadata.isDeleted = true tree.metadata.timestamp = timestamp update(tree) } } // Inserts a value tree, or updates an existing one public mutating func update(_ valueTree: ValueTree) { let ref = valueTree.valueTreeReference valueTreesByReference[ref] = valueTree } public mutating func merge(_ plantedValueTree: PlantedValueTree, resolvingConflictsWith conflictResolver: ConflictResolver = ConflictResolver()) { let timestamp = Date.timeIntervalSinceReferenceDate // Gather identifiers for trees before the merge from both forests var treeRefsPriorToMerge = Set<ValueTreeReference>() let existingPlantedValueTree = PlantedValueTree(forest: self, root: plantedValueTree.root) for ref in existingPlantedValueTree { treeRefsPriorToMerge.insert(ref) } for ref in plantedValueTree { treeRefsPriorToMerge.insert(ref) } // Merge for ref in plantedValueTree { var resolvedTree: ValueTree! var resolvedVersion: RepositedVersion = 0 var resolvedTimestamp = timestamp var changed = true let treeInOtherForest = plantedValueTree.forest.valueTree(at: ref)! let treeInThisForest = valueTree(at: ref) if treeInThisForest == nil { // Does not exist in this forest. Just copy it over. resolvedTree = treeInOtherForest resolvedVersion = treeInOtherForest.metadata.version resolvedTimestamp = treeInOtherForest.metadata.timestamp } else if treeInThisForest == treeInOtherForest { // Values unchanged from store. Don't commit data again resolvedTree = treeInOtherForest resolvedVersion = treeInOtherForest.metadata.version resolvedTimestamp = treeInOtherForest.metadata.timestamp changed = false } else if treeInOtherForest.metadata.version == treeInThisForest!.metadata.version { // Store has not changed since the base value was taken, so just commit the new value directly resolvedTree = treeInOtherForest resolvedVersion = treeInOtherForest.metadata.version + 1 } else { // Conflict with store. Resolve. resolvedTree = conflictResolver.resolved(fromConflictOf: treeInThisForest!, with: treeInOtherForest) resolvedVersion = Swift.max(treeInOtherForest.metadata.version, treeInThisForest!.metadata.version) + 1 } if changed { resolvedTree.metadata.timestamp = resolvedTimestamp resolvedTree.metadata.version = resolvedVersion update(resolvedTree) } } // Determine what refs exist in the resolved tree var treeRefsPostMerge = Set<ValueTreeReference>() let resolvedPlantedValueTree = PlantedValueTree(forest: self, root: plantedValueTree.root) for ref in resolvedPlantedValueTree { treeRefsPostMerge.insert(ref) } // Delete orphans let orphanRefs = treeRefsPriorToMerge.subtracting(treeRefsPostMerge) for orphanRef in orphanRefs { var orphan = valueTree(at: orphanRef)! orphan.metadata.isDeleted = true orphan.metadata.timestamp = timestamp orphan.metadata.version += 1 update(orphan) } } public func valueTree(at reference: ValueTreeReference) -> ValueTree? { return valueTreesByReference[reference] } public func valueTrees(changedSince timestamp: TimeInterval) -> [ValueTree] { var valueTrees = [ValueTree]() for (_, valueTree) in self.valueTreesByReference { let time = valueTree.metadata.timestamp if timestamp <= time { valueTrees.append(valueTree) } } return valueTrees } }
mit
36652bf7e9f2ea342d74f861fdd7cc60
37.060403
150
0.628461
4.952838
false
false
false
false
cloudipsp/ios-sdk
ExampleSwift/ExampleSwift/ViewController.swift
1
1805
import UIKit import Cloudipsp class ViewController: UIViewController, PSPayCallbackDelegate { @IBOutlet weak var textFieldMerchantID: UITextField! @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldDescription: UITextField! @IBOutlet weak var textFieldAmount: UITextField! @IBOutlet weak var textFieldCurrency: UITextField! @IBOutlet weak var cardInputLayout: PSCardInputLayout! var cloudipspWebView: PSCloudipspWKWebView! override func viewDidLoad() { super.viewDidLoad() cloudipspWebView = PSCloudipspWKWebView(frame: CGRect(x: 0, y: 64, width: self.view.bounds.width, height: self.view.bounds.height)) self.view.addSubview(cloudipspWebView) } @IBAction func onPayPressed(_ sender: Any) { let generatedOrderId = String(format: "Swift_%d", arc4random()) let cloudipspApi = PSCloudipspApi(merchant: Int(textFieldMerchantID.text!) ?? 0, andCloudipspView: self.cloudipspWebView) let card = self.cardInputLayout.confirm() if (card == nil) { debugPrint("Empty card") } else { let order = PSOrder(order: Int(textFieldAmount.text!) ?? 0, aStringCurrency: textFieldCurrency.text!, aIdentifier: generatedOrderId, aAbout: textFieldDescription.text!) cloudipspApi?.pay(card, with: order, andDelegate: self) } } @IBAction func onTestCardPressed(_ sender: Any) { self.cardInputLayout.test() } func onPaidProcess(_ receipt: PSReceipt!) { debugPrint("onPaidProcess: %@", receipt.status) } func onPaidFailure(_ error: Error!) { debugPrint("onPaidFailure: %@", error.localizedDescription) } func onWaitConfirm() { debugPrint("onWaitConfirm") } }
mit
a831760fda5fed71ea5753bbae764308
35.836735
180
0.679778
4.257075
false
false
false
false
jason790/RFCalculatorKeyboard
RFCalculatorKeyboard/RFCalculatorKeyboard.swift
3
5343
// // RFCalculatorKeyboard.swift // RFCalculatorKeyboard // // Created by Guilherme Moura on 8/15/15. // Copyright (c) 2015 Reefactor, Inc. All rights reserved. // import UIKit public protocol RFCalculatorDelegate: class { func calculator(calculator: RFCalculatorKeyboard, didChangeValue value: String) } enum CalculatorKey: Int { case Zero = 1 case One case Two case Three case Four case Five case Six case Seven case Eight case Nine case Decimal case Clear case Delete case Multiply case Divide case Subtract case Add case Equal } public class RFCalculatorKeyboard: UIView { public weak var delegate: RFCalculatorDelegate? public var numbersBackgroundColor = UIColor(white: 0.97, alpha: 1.0) { didSet { adjustLayout() } } public var numbersTextColor = UIColor.blackColor() { didSet { adjustLayout() } } public var operationsBackgroundColor = UIColor(white: 0.75, alpha: 1.0) { didSet { adjustLayout() } } public var operationsTextColor = UIColor.whiteColor() { didSet { adjustLayout() } } public var equalBackgroundColor = UIColor(red:0.96, green:0.5, blue:0, alpha:1) { didSet { adjustLayout() } } public var equalTextColor = UIColor.whiteColor() { didSet { adjustLayout() } } public var showDecimal = false { didSet { processor.automaticDecimal = !showDecimal adjustLayout() } } var view: UIView! private var processor = RFCalculatorProcessor() @IBOutlet weak var zeroDistanceConstraint: NSLayoutConstraint! required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadXib() } override public init(frame: CGRect) { super.init(frame: frame) loadXib() } private func loadXib() { view = loadViewFromNib() view.frame = bounds view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight adjustLayout() addSubview(view) } private func loadViewFromNib() -> UIView { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "CalculatorKeyboard", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView return view } private func adjustLayout() { let view = viewWithTag(CalculatorKey.Decimal.rawValue) if let decimal = view { let width = UIScreen.mainScreen().bounds.width / 4.0 zeroDistanceConstraint.constant = showDecimal ? width + 2.0 : 1.0 layoutIfNeeded() } let bundle = NSBundle(forClass: self.dynamicType) let image = UIImage(named: "RF_black_background", inBundle: bundle, compatibleWithTraitCollection: nil) for var i = 1; i <= CalculatorKey.Decimal.rawValue; i++ { if let button = self.view.viewWithTag(i) as? UIButton { button.setBackgroundImage(image, forState: .Normal) button.tintColor = numbersBackgroundColor button.setTitleColor(numbersTextColor, forState: .Normal) } } for var i = CalculatorKey.Clear.rawValue; i <= CalculatorKey.Add.rawValue; i++ { if let button = self.view.viewWithTag(i) as? UIButton { button.setBackgroundImage(image, forState: .Normal) button.tintColor = operationsBackgroundColor button.setTitleColor(operationsTextColor, forState: .Normal) } } if let button = self.view.viewWithTag(CalculatorKey.Equal.rawValue) as? UIButton { button.setBackgroundImage(image, forState: .Normal) button.tintColor = equalBackgroundColor button.setTitleColor(equalTextColor, forState: .Normal) } } @IBAction func buttonPressed(sender: UIButton) { let key = CalculatorKey(rawValue: sender.tag)! switch (sender.tag) { case (CalculatorKey.Zero.rawValue)...(CalculatorKey.Nine.rawValue): var output = processor.storeOperand(sender.tag-1) delegate?.calculator(self, didChangeValue: output) case CalculatorKey.Decimal.rawValue: var output = processor.addDecimal() delegate?.calculator(self, didChangeValue: output) case CalculatorKey.Clear.rawValue: var output = processor.clearAll() delegate?.calculator(self, didChangeValue: output) case CalculatorKey.Delete.rawValue: var output = processor.deleteLastDigit() delegate?.calculator(self, didChangeValue: output) case (CalculatorKey.Multiply.rawValue)...(CalculatorKey.Add.rawValue): var output = processor.storeOperator(sender.tag) delegate?.calculator(self, didChangeValue: output) case CalculatorKey.Equal.rawValue: var output = processor.computeFinalValue() delegate?.calculator(self, didChangeValue: output) break default: break } } }
mit
655f37f03383df0d1e6b33dbada06d1f
31.381818
111
0.61632
4.857273
false
false
false
false
masbog/iOS-SDK
Examples/nearables/TemperatureExample-Swift/TemperatureExample-Swift/MasterViewController.swift
9
2063
// // MasterViewController.swift // TemperatureExample-Swift // // Created by Grzegorz Krukiewicz-Gacek on 24.12.2014. // Copyright (c) 2014 Estimote Inc. All rights reserved. // import UIKit class MasterViewController: UITableViewController, ESTNearableManagerDelegate { var nearables:Array<ESTNearable>! var nearableManager:ESTNearableManager! override func viewDidLoad() { super.viewDidLoad() nearables = [] nearableManager = ESTNearableManager() nearableManager.delegate = self nearableManager .startRangingForType(ESTNearableType.All) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let selectedNearable = nearables[indexPath.row] as ESTNearable (segue.destinationViewController as DetailViewController).nearable = selectedNearable } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return nearables.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let nearable = nearables[indexPath.row] as ESTNearable cell.textLabel!.text = ESTNearableDefinitions.nameForType(nearable.type) cell.detailTextLabel!.text = nearable.identifier return cell } // MARK: - ESTNearableManager delegate func nearableManager(manager: ESTNearableManager!, didRangeNearables nearables: [AnyObject]!, withType type: ESTNearableType) { self.nearables = nearables as Array<ESTNearable> tableView.reloadData() } }
mit
a900f696268fdea8416ccdedd9d88e84
31.746032
131
0.696558
5.34456
false
false
false
false
GuiminChu/JianshuExample
LearnRxSwift/LearnRxSwift/ImagePicker/ExUIImage.swift
2
19264
// // UIImage+Yep.swift // Yep // // Created by NIX on 15/3/16. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import ImageIO import MobileCoreServices.UTType public extension UIImage { public func largestCenteredSquareImage() -> UIImage { let scale = self.scale let originalWidth = self.size.width * scale let originalHeight = self.size.height * scale let edge: CGFloat if originalWidth > originalHeight { edge = originalHeight } else { edge = originalWidth } let posX = (originalWidth - edge) / 2.0 let posY = (originalHeight - edge) / 2.0 let cropSquare = CGRect(x: posX, y: posY, width: edge, height: edge) let imageRef = self.cgImage!.cropping(to: cropSquare)! return UIImage(cgImage: imageRef, scale: scale, orientation: self.imageOrientation) } public func resizeToTargetSize(_ targetSize: CGSize) -> UIImage { let size = self.size let widthRatio = targetSize.width / self.size.width let heightRatio = targetSize.height / self.size.height let scale = UIScreen.main.scale let newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: scale * floor(size.width * heightRatio), height: scale * floor(size.height * heightRatio)) } else { newSize = CGSize(width: scale * floor(size.width * widthRatio), height: scale * floor(size.height * widthRatio)) } let rect = CGRect(x: 0, y: 0, width: floor(newSize.width), height: floor(newSize.height)) //println("size: \(size), newSize: \(newSize), rect: \(rect)") UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func scaleToMinSideLength(_ sideLength: CGFloat) -> UIImage { let pixelSideLength = sideLength * UIScreen.main.scale //println("pixelSideLength: \(pixelSideLength)") //println("size: \(size)") let pixelWidth = size.width * scale let pixelHeight = size.height * scale //println("pixelWidth: \(pixelWidth)") //println("pixelHeight: \(pixelHeight)") let newSize: CGSize if pixelWidth > pixelHeight { guard pixelHeight > pixelSideLength else { return self } let newHeight = pixelSideLength let newWidth = (pixelSideLength / pixelHeight) * pixelWidth newSize = CGSize(width: floor(newWidth), height: floor(newHeight)) } else { guard pixelWidth > pixelSideLength else { return self } let newWidth = pixelSideLength let newHeight = (pixelSideLength / pixelWidth) * pixelHeight newSize = CGSize(width: floor(newWidth), height: floor(newHeight)) } if scale == UIScreen.main.scale { let newSize = CGSize(width: floor(newSize.width / scale), height: floor(newSize.height / scale)) //println("A scaleToMinSideLength newSize: \(newSize)") UIGraphicsBeginImageContextWithOptions(newSize, false, scale) let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = newImage { return image } return self } else { //println("B scaleToMinSideLength newSize: \(newSize)") UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let image = newImage { return image } return self } } public func fixRotation() -> UIImage { if self.imageOrientation == .up { return self } let width = self.size.width let height = self.size.height var transform = CGAffineTransform.identity switch self.imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: width, y: height) transform = transform.rotated(by: CGFloat(Double.pi)) case .left, .leftMirrored: transform = transform.translatedBy(x: width, y: 0) transform = transform.rotated(by: CGFloat(Double.pi / 2)) case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: height) transform = transform.rotated(by: CGFloat(-Double.pi / 2)) default: break } switch self.imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: width, y: 0); transform = transform.scaledBy(x: -1, y: 1); case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: height, y: 0); transform = transform.scaledBy(x: -1, y: 1); default: break } let selfCGImage = self.cgImage let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: selfCGImage!.bitsPerComponent, bytesPerRow: 0, space: selfCGImage!.colorSpace!, bitmapInfo: selfCGImage!.bitmapInfo.rawValue); context!.concatenate(transform) switch self.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context!.draw(selfCGImage!, in: CGRect(x: 0,y: 0, width: height, height: width)) default: context!.draw(selfCGImage!, in: CGRect(x: 0,y: 0, width: width, height: height)) } let cgImage = context!.makeImage()! return UIImage(cgImage: cgImage) } } // MARK: Message Image public enum MessageImageTailDirection { case left case right } public extension UIImage { public func cropToAspectRatio(_ aspectRatio: CGFloat) -> UIImage { let size = self.size let originalAspectRatio = size.width / size.height var rect = CGRect.zero if originalAspectRatio > aspectRatio { let width = size.height * aspectRatio rect = CGRect(x: (size.width - width) * 0.5, y: 0, width: width, height: size.height) } else if originalAspectRatio < aspectRatio { let height = size.width / aspectRatio rect = CGRect(x: 0, y: (size.height - height) * 0.5, width: size.width, height: height) } else { return self } let cgImage = self.cgImage!.cropping(to: rect)! return UIImage(cgImage: cgImage) } } public extension UIImage { public func imageWithGradientTintColor(_ tintColor: UIColor) -> UIImage { return imageWithTintColor(tintColor, blendMode: CGBlendMode.overlay) } public func imageWithTintColor(_ tintColor: UIColor, blendMode: CGBlendMode) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) tintColor.setFill() let bounds = CGRect(origin: CGPoint.zero, size: size) UIRectFill(bounds) self.draw(in: bounds, blendMode: blendMode, alpha: 1) if blendMode != CGBlendMode.destinationIn { self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1) } let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage! } } public extension UIImage { public func renderAtSize(_ size: CGSize) -> UIImage { // 确保 size 为整数,防止 mask 里出现白线 let size = CGSize(width: ceil(size.width), height: ceil(size.height)) UIGraphicsBeginImageContextWithOptions(size, false, 0) // key let context = UIGraphicsGetCurrentContext() draw(in: CGRect(origin: CGPoint.zero, size: size)) let cgImage = context!.makeImage()! let image = UIImage(cgImage: cgImage) UIGraphicsEndImageContext() return image } public func maskWithImage(_ maskImage: UIImage) -> UIImage { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(self.size, false, scale) let context = UIGraphicsGetCurrentContext() var transform = CGAffineTransform.identity.concatenating(CGAffineTransform(scaleX: 1.0, y: -1.0)) transform = transform.concatenating(CGAffineTransform(translationX: 0.0, y: self.size.height)) context!.concatenate(transform) let drawRect = CGRect(origin: CGPoint.zero, size: self.size) context!.clip(to: drawRect, mask: maskImage.cgImage!) context!.draw(self.cgImage!, in: drawRect) let roundImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundImage! } public struct BubbleMaskImage { public static let leftTail: UIImage = { let scale = UIScreen.main.scale let orientation: UIImageOrientation = .up var maskImage = UIImage(cgImage: UIImage(named: "left_tail_image_bubble")!.cgImage!, scale: scale, orientation: orientation) maskImage = maskImage.resizableImage(withCapInsets: UIEdgeInsets(top: 25, left: 27, bottom: 20, right: 20), resizingMode: UIImageResizingMode.stretch) return maskImage }() public static let rightTail: UIImage = { let scale = UIScreen.main.scale let orientation: UIImageOrientation = .up var maskImage = UIImage(cgImage: UIImage(named: "right_tail_image_bubble")!.cgImage!, scale: scale, orientation: orientation) maskImage = maskImage.resizableImage(withCapInsets: UIEdgeInsets(top: 24, left: 20, bottom: 20, right: 27), resizingMode: UIImageResizingMode.stretch) return maskImage }() } public func bubbleImageWithTailDirection(_ tailDirection: MessageImageTailDirection, size: CGSize, forMap: Bool = false) -> UIImage { //let orientation: UIImageOrientation = tailDirection == .Left ? .Up : .UpMirrored let maskImage: UIImage if tailDirection == .left { maskImage = BubbleMaskImage.leftTail.renderAtSize(size) } else { maskImage = BubbleMaskImage.rightTail.renderAtSize(size) } if forMap { let image = cropToAspectRatio(size.width / size.height).resizeToTargetSize(size) UIGraphicsBeginImageContextWithOptions(image.size, true, image.scale) image.draw(at: CGPoint.zero) let bottomShadowImage = UIImage(named: "location_bottom_shadow")! let bottomShadowHeightRatio: CGFloat = 0.185 // 20 / 108 bottomShadowImage.draw(in: CGRect(x: 0, y: floor(image.size.height * (1 - bottomShadowHeightRatio)), width: image.size.width, height: ceil(image.size.height * bottomShadowHeightRatio))) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let bubbleImage = finalImage!.maskWithImage(maskImage) return bubbleImage } // fixRotation 会消耗大量内存,改在发送前做 let bubbleImage = /*self.fixRotation().*/cropToAspectRatio(size.width / size.height).resizeToTargetSize(size).maskWithImage(maskImage) return bubbleImage } } // MARK: - Decode public extension UIImage { public func decodedImage() -> UIImage { return decodedImage(scale: scale) } public func decodedImage(scale: CGFloat) -> UIImage { let imageRef = cgImage let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: nil, width: imageRef!.width, height: imageRef!.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) if let context = context { let rect = CGRect(x: 0, y: 0, width: CGFloat(imageRef!.width), height: CGFloat(imageRef!.height)) context.draw(imageRef!, in: rect) let decompressedImageRef = context.makeImage()! return UIImage(cgImage: decompressedImageRef, scale: scale, orientation: imageOrientation) } return self } } // MARK: Resize public extension UIImage { public func resizeToSize(_ size: CGSize, withTransform transform: CGAffineTransform, drawTransposed: Bool, interpolationQuality: CGInterpolationQuality) -> UIImage? { let newRect = CGRect(origin: CGPoint.zero, size: size).integral let transposedRect = CGRect(origin: CGPoint.zero, size: CGSize(width: size.height, height: size.width)) let bitmapContext = CGContext(data: nil, width: Int(newRect.width), height: Int(newRect.height), bitsPerComponent: cgImage!.bitsPerComponent, bytesPerRow: 0, space: cgImage!.colorSpace!, bitmapInfo: cgImage!.bitmapInfo.rawValue) bitmapContext!.concatenate(transform) bitmapContext!.interpolationQuality = interpolationQuality bitmapContext!.draw(cgImage!, in: drawTransposed ? transposedRect : newRect) if let newCGImage = bitmapContext!.makeImage() { let newImage = UIImage(cgImage: newCGImage) return newImage } return nil } public func transformForOrientationWithSize(_ size: CGSize) -> CGAffineTransform { var transform = CGAffineTransform.identity switch imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: size.width, y: size.height) transform = transform.rotated(by: CGFloat(Double.pi)) case .left, .leftMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.rotated(by: CGFloat(Double.pi / 2)) case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: size.height) transform = transform.rotated(by: CGFloat(-Double.pi / 2)) default: break } switch imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: size.height, y: 0) transform = transform.scaledBy(x: -1, y: 1) default: break } return transform } public func resizeToSize(_ size: CGSize, withInterpolationQuality interpolationQuality: CGInterpolationQuality) -> UIImage? { let drawTransposed: Bool switch imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: drawTransposed = true default: drawTransposed = false } return resizeToSize(size, withTransform: transformForOrientationWithSize(size), drawTransposed: drawTransposed, interpolationQuality: interpolationQuality) } } public extension UIImage { public var yep_avarageColor: UIColor { let rgba = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4) let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB() let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context: CGContext = CGContext(data: rgba, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: info.rawValue)! context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1)) let alpha: CGFloat = (rgba[3] > 0) ? (CGFloat(rgba[3]) / 255.0) : 1 let multiplier = alpha / 255.0 return UIColor(red: CGFloat(rgba[0]) * multiplier, green: CGFloat(rgba[1]) * multiplier, blue: CGFloat(rgba[2]) * multiplier, alpha: alpha) } } // MARK: Progressive public extension UIImage { public var yep_progressiveImage: UIImage? { guard let cgImage = cgImage else { return nil } let data = NSMutableData() guard let distination = CGImageDestinationCreateWithData(data, kUTTypeJPEG, 1, nil) else { return nil } let jfifProperties = [ kCGImagePropertyJFIFIsProgressive as String: kCFBooleanTrue as Bool, kCGImagePropertyJFIFXDensity as String: 72, kCGImagePropertyJFIFYDensity as String: 72, kCGImagePropertyJFIFDensityUnit as String: 1, ] as [String : Any] let properties = [ kCGImageDestinationLossyCompressionQuality as String: 0.9, kCGImagePropertyJFIFDictionary as String: jfifProperties, ] as [String : Any] CGImageDestinationAddImage(distination, cgImage, properties as CFDictionary?) guard CGImageDestinationFinalize(distination) else { return nil } guard data.length > 0 else { return nil } guard let progressiveImage = UIImage(data: data as Data) else { return nil } return progressiveImage } } extension UIImage { // 给 Image 着色 func tint(color: UIColor) -> UIImage? { let drawRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, scale) color.setFill() UIRectFill(drawRect) draw(in: drawRect, blendMode: .destinationIn, alpha: 1.0) let tintedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } }
mit
41b6d2acf6a065f06e7e3ffa8973fab5
34.891589
236
0.596761
5.168775
false
false
false
false
StupidTortoise/personal
iOS/Swift/DeleteAddCell/DeleteAddCell/ViewController.swift
1
4400
// // ViewController.swift // DeleteAddCell // // Created by tortoise on 7/20/15. // Copyright (c) 2015 703. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var navigationitem: UINavigationItem! @IBOutlet weak var tableView: UITableView! @IBOutlet var textField: UITextField! var teams: [String] = ["南宁", "贵港"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationitem.rightBarButtonItem = self.editButtonItem() self.navigationitem.title = "单元格插入和删除" self.textField.hidden = true self.textField.delegate = self self.tableView.delegate = self self.tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) self.tableView.setEditing(editing, animated: true) if editing { self.textField.hidden = false } else { self.textField.hidden = true } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.teams.count + 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } let bAddCell = indexPath.row == self.teams.count if !bAddCell { cell?.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell?.textLabel?.text = self.teams[indexPath.row] } else { self.textField.frame = CGRectMake(10, 0, 300, 44) self.textField.text = "" cell?.contentView.addSubview(self.textField) } return cell! } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { println("editingStyleForRowAtIndexPath!") if indexPath.row == self.teams.count { return UITableViewCellEditingStyle.Insert } else { return UITableViewCellEditingStyle.Delete } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { println("commitEditingStyle!") println(self.teams) let indexPaths = NSArray(object: indexPath) as [AnyObject] if editingStyle == UITableViewCellEditingStyle.Delete { self.teams.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Fade) } else if editingStyle == UITableViewCellEditingStyle.Insert { self.teams.insert(self.textField.text, atIndex: self.teams.count) self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Fade) } self.tableView.reloadData() } func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool { if indexPath.row == self.teams.count { return false } else { return true } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { let cell = textField.superview?.superview as? UITableViewCell self.tableView.setContentOffset(CGPointMake(0, cell!.frame.origin.y), animated: true) } }
gpl-2.0
3edf0957a3e0353aeaf44143dba41115
34.577236
148
0.651508
5.560356
false
false
false
false
pankcuf/DataContext
DataContext/Classes/UICollectionView+DataContext.swift
1
2521
// // UICollectionView+DataContext.swift // DataContext // // Created by Vladimir Pirogov on 09/01/17. // Copyright © 2017 Vladimir Pirogov. All rights reserved. // import Foundation import UIKit extension UICollectionView { open func collectionDataContext() -> CollectionDataContext? { return self.context as? CollectionDataContext } open override func contextDidChange() { if let ctx = self.context as? CollectionDataContext { self.createEmptyView() self.headers(ctx.uniqueHeaderIds()) self.headers(ctx.uniqueFooterIds()) self.cells(ctx.uniqueCellIds()) } } open func createEmptyView() { if let emptyCtx = self.collectionDataContext()?.emptyContext { self.backgroundView = Bundle.main.loadNibNamed(emptyCtx.reuseId, owner: self, options: nil)?.first as? UIView } } override open func update(with context: ViewUpdateContext?) { if let collectionCtx = context as? CollectionViewUpdateContext { self.updateRowContext(collectionCtx) self.updateEmptyContext(collectionCtx) } } open func updateEmptyContext(_ response: CollectionViewUpdateContext?) { guard let ctx = self.collectionDataContext() else { return } let hasNoSections = ctx.sectionContext.isEmpty self.backgroundView?.isHidden = !hasNoSections self.backgroundView?.context = ctx.emptyContext } open func updateRowContext(_ response: CollectionViewUpdateContext?) { if let updates = response?.sectionsUpdates { self.performBatchUpdates({ for update in updates { let iset = IndexSet(integer: update.index) switch update.actionType { case .add: self.insertSections(iset) break case .change: self.reloadSections(iset) break case .remove: self.deleteSections(iset) break } } }, completion: nil) } else { self.reloadData() } } open func collectionView(_ collectionView: UICollectionView, contextFor section: Int) -> CollectionDataSectionContext? { guard let ctx = self.collectionDataContext() else { return nil } let sectionContext = ctx.sectionContext[section] return sectionContext } open func collectionView(_ collectionView: UICollectionView, contextForRowAt indexPath: IndexPath) -> CollectionDataCellContext? { let sectionContext = self.collectionView(collectionView, contextFor: indexPath.section) let rowContext = sectionContext?.rowContext[indexPath.row] return rowContext } }
mit
148e363e3d1a047c7aa72db709e2905b
22.333333
131
0.708333
4.158416
false
false
false
false
djflsdl08/BasicIOS
Timer/Timer/StopwatchViewController.swift
1
5345
// // StopwatchViewController.swift // Timer // // Created by 김예진 on 2017. 11. 3.. // Copyright © 2017년 Kim,Yejin. All rights reserved. // import UIKit class StopwatchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var lapResetButton: UIButton! @IBOutlet var tableView: UITableView! var timer = Timer() //var isTimerRunning = false var seconds = 0 var lapSeconds = 0 var lapCount = 0 var lapDatas = [lapData]() var compareTime = ["min":Int.max,"max":Int.min,"minIndex":0,"maxIndex":0] @IBAction func startStopButton(_ sender: UIButton) { lapResetButton.isEnabled = true if sender.currentTitle == "Start" { runTimer() sender.setTitle("Stop", for: .normal) sender.setTitleColor(.red, for: .normal) lapResetButton.setTitle("Lap", for: .normal) } else if sender.currentTitle == "Stop" { timer.invalidate() sender.setTitle("Start", for: .normal) sender.setTitleColor(.green, for: .normal) lapResetButton.setTitle("Reset", for: .normal) } } @IBAction func lapResetButton(_ sender: UIButton) { if sender.currentTitle == "Lap" { findMinMax(index : lapCount) lapCount += 1 let time = timerLabelFormat(time: TimeInterval(lapSeconds)) let newLap = lapData(lapTime: time, lapCount: lapCount) lapDatas.append(newLap) DispatchQueue.main.async { self.tableView.reloadData() } lapSeconds = 0 } else if sender.currentTitle == "Reset" { timer.invalidate() seconds = 0 lapSeconds = 0 lapCount = 0 timerLabel.text = timerLabelFormat(time: TimeInterval(seconds)) lapResetButton.isEnabled = false lapResetButton.setTitle("Lap", for: .normal) lapDatas.removeAll() compareTimeInit() DispatchQueue.main.async { self.tableView.reloadData() } } } func compareTimeInit() { compareTime["min"] = Int.max compareTime["max"] = Int.min compareTime["minIndex"] = 0 compareTime["maxIndex"] = 0 } func findMinMax(index : Int) { if lapSeconds < compareTime["min"]! { compareTime["min"] = lapSeconds compareTime["minIndex"] = index } else if lapSeconds > compareTime["max"]! { compareTime["max"] = lapSeconds compareTime["maxIndex"] = index } } override func viewDidLoad() { super.viewDidLoad() lapResetButton.isEnabled = false tableView.delegate = self tableView.dataSource = self } func timerLabelFormat(time: TimeInterval) -> String { let date = NSDate(timeIntervalSince1970: Double(time)) let formatter = DateFormatter() formatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! formatter.dateFormat = "mm:ss" return formatter.string(from: date as Date) } func runTimer() { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(StopwatchViewController.updateTimer)), userInfo: nil, repeats: true) } func updateTimer() { seconds += 1 lapSeconds += 1 timerLabel.text = timerLabelFormat(time: TimeInterval(seconds)) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.backgroundColor = UIColor.black return lapDatas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true) let cellIdentifier = "cell" guard let cell = tableView.dequeueReusableCell ( withIdentifier: cellIdentifier, for: indexPath ) as? LapTableViewCell else { fatalError("The dequeued cell is not an instance of LapTableViewCell.") } let data = lapDatas[indexPath.row] //print("indexPath.row : \(indexPath.row)") //print("minIndex : \(Int(compareTime["minIndex"]!))") //print("maxIndex : \(Int(compareTime["maxIndex"]!))") //print("-------------------------") cell.lapCount.textColor = UIColor.white cell.time.textColor = UIColor.white if indexPath.row == Int(compareTime["minIndex"]!) { cell.lapCount.textColor = UIColor.green cell.time.textColor = UIColor.green } else if indexPath.row == Int(compareTime["maxIndex"]!) { cell.lapCount.textColor = UIColor.red cell.time.textColor = UIColor.red } cell.lapCount.text = "Lap \(data.lapCount)" cell.time.text = data.lapTime return cell } }
mit
273e74213b0fe34f8c3fb85a0bdc0fdb
31.736196
157
0.5744
4.855323
false
false
false
false
mohamede1945/quran-ios
VFoundation/Measure.swift
2
1527
// // Measure.swift // Quran // // Created by Mohamed Afifi on 4/1/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation public func measure<T>(_ tag: String = #function, limit: TimeInterval = 0, _ body: () throws -> T) rethrows -> T { let measurer = Measurer(tag: tag, limit: limit) let result = try body() measurer.end() return result } public struct Measurer { public let start = CFAbsoluteTimeGetCurrent() public let tag: String public let limit: TimeInterval public init(tag: String = #function, limit: TimeInterval = 0) { self.tag = tag self.limit = limit } @discardableResult public func end() -> TimeInterval { let end = CFAbsoluteTimeGetCurrent() // <<<<<<<<<< end time let timeInterval = end - start if timeInterval >= limit { print("[\(tag)]: Time Elabsed \(timeInterval) seconds") } return timeInterval } }
gpl-3.0
5c579dcac81136e1f73182513f753107
28.941176
114
0.656843
4.138211
false
false
false
false
2345Team/Swifter-Tips
14.命名空间 + 单例/SingleTon/SingleTon/ViewController.swift
1
3990
// // ViewController.swift // SingleTon // // Created by yangbin on 16/9/5. // Copyright © 2016年 yangbin. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 因为在 Swift 中可以无缝直接使用 GCD,所以我们可以很方便地把类似方式的单例用 Swift 进行改写 class MyManager { class var sharedManager : MyManager { struct Static { static var onceToken : dispatch_once_t = 0 static var staticInstance : MyManager? = nil } dispatch_once(&Static.onceToken) { Static.staticInstance = MyManager() } return Static.staticInstance! } } // 因为 Swift 1.2 之前并不支持存储类型的类属性,所以我们需要使用一个 struct 来存储类型变量。 // 这样的写法当然没什么问题,但是在 Swift 里我们其实有一个更简单的保证线程安全的方式,那就是 let。把上面的写法简化一下,可以变成: class MyManager1 { class var sharedManager : MyManager1 { struct Static { static let sharedInstance : MyManager1 = MyManager1() } return Static .sharedInstance } } // 还有另一种更受大家欢迎,并被认为是 Swift 1.2 之前的最佳实践的做法。由于 Swift 1.2 之前 class 不支持存储式的 property,我们想要使用一个只存在一份的属性时,就只能将其定义在全局的 scope 中。值得庆幸的是,在 Swift 中是有访问级别的控制的,我们可以在变量定义前面加上 private 关键字,使这个变量只在当前文件中可以被访问。这样我们就可以写出一个没有嵌套的,语法上也更简单好看的单例了: // private let sharedInstance = MyManager2() // // class MyManager2 { // class var sharedManager : MyManager2 { // return sharedInstance // } // } // Swift 1.2 之前还不支持例如 static let 和 static var 这样的存储类变量。但是在 1.2 中 Swift 添加了类变量的支持,因此单例可以进一步简化。 // 将上面全局的 sharedInstance 拿到 class 中,这样结构上就更紧凑和合理了。 // 在 Swift 1.2 以及之后,如果没有特别的需求,我们推荐使用下面这样的方式来写一个单例: class MyManager3 { static let sharedInstance = MyManager3() private init() { print("Nice Job") } func hello() { print("Hello") } } let my = MyManager3.sharedInstance // my.hello() // 这种写法不仅简洁,而且保证了单例的独一无二。在初始化类变量的时候,Apple 将会把这个初始化包装在一次 swift_once_block_invoke 中,以保证它的唯一性。另外,我们在这个类型中加入了一个私有的初始化方法,来覆盖默认的公开初始化方法,这让项目中的其他地方不能够通过 init 来生成自己的 MyManager 实例,也保证了类型单例的唯一性。如果你需要的是类似 defaultManager 的形式的单例 (也就是说这个类的使用者可以创建自己的实例) 的话,可以去掉这个私有的 init 方法。 // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5874c3ea2ff9db82d38a0434a18c7be7
30.21978
268
0.568462
3.823688
false
false
false
false
agilewalker/SwiftyChardet
SwiftyChardet/mbcharsetprober.swift
1
3182
/* ######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Wu Hui Yuan - port to Swift # Mark Pilgrim - port to Python # Shy Shalom - original C code # Proofpoint, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### */ class MultiByteCharSetProber: CharSetProber { /* MultiByteCharSetProber */ var _last_char: Data var codingSM: CodingStateMachine { fatalError("var codingSM getter not implemented") } var distributionAnalyzer: CharDistributionAnalysis { fatalError("var distributionAnalyzer getter not implemented") } override init(langFilter: LanguageFilter = []) { self._last_char = Data(bytes: [0, 0]) super.init(langFilter: langFilter) } override func reset() { super.reset() self.codingSM.reset() self.distributionAnalyzer.reset() self._last_char = Data(bytes: [0, 0]) } override func feed(_ byte_str: Data) -> ProbingState { outer: for (i, c) in byte_str.enumerated() { let coding_state = self.codingSM.next_state(c) switch (coding_state) { case .error: self.state = .not_me break outer case .its_me: self.state = .found_it break outer case .start: let char_len = self.codingSM.currentCharLen if i == 0 { self._last_char[1] = byte_str[0] self.distributionAnalyzer.feed(self._last_char, char_len) } else { self.distributionAnalyzer.feed(byte_str[i - 1 ..< i + 1], char_len) } default: continue } } self._last_char[0] = byte_str.last! if self.state == .detecting { if (self.distributionAnalyzer.gotEnoughData && (self.confidence > self.SHORTCUT_THRESHOLD)) { self.state = .found_it } } return self.state } override var confidence: Double { return self.distributionAnalyzer.confidence } }
lgpl-2.1
f615ec430b217c1e01913bded0e1178d
32.145833
105
0.600251
4.311653
false
false
false
false
apple/swift-format
Sources/generate-pipeline/PipelineGenerator.swift
1
3274
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 Foundation /// Generates the extensions to the lint and format pipelines. final class PipelineGenerator: FileGenerator { /// The rules collected by scanning the formatter source code. let ruleCollector: RuleCollector /// Creates a new pipeline generator. init(ruleCollector: RuleCollector) { self.ruleCollector = ruleCollector } func write(into handle: FileHandle) throws { handle.write( """ //===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// // This file is automatically generated with generate-pipeline. Do Not Edit! import SwiftFormatCore import SwiftFormatRules import SwiftSyntax /// A syntax visitor that delegates to individual rules for linting. /// /// This file will be extended with `visit` methods in Pipelines+Generated.swift. class LintPipeline: SyntaxVisitor { /// The formatter context. let context: Context /// Stores lint and format rule instances, indexed by the `ObjectIdentifier` of a rule's /// class type. var ruleCache = [ObjectIdentifier: Rule]() /// Creates a new lint pipeline. init(context: Context) { self.context = context super.init(viewMode: .sourceAccurate) } """ ) for (nodeType, lintRules) in ruleCollector.syntaxNodeLinters.sorted(by: { $0.key < $1.key }) { handle.write( """ override func visit(_ node: \(nodeType)) -> SyntaxVisitorContinueKind { """) for ruleName in lintRules.sorted() { handle.write( """ visitIfEnabled(\(ruleName).visit, for: node) """) } handle.write( """ return .visitChildren } """) } handle.write( """ } extension FormatPipeline { func visit(_ node: Syntax) -> Syntax { var node = node """ ) for ruleName in ruleCollector.allFormatters.map({ $0.typeName }).sorted() { handle.write( """ node = \(ruleName)(context: context).visit(node) """) } handle.write( """ return node } } """) } }
apache-2.0
27eabae0830990b3de7fc4092fb8b4b6
26.283333
98
0.544288
5.123631
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Course Alerts/Model/CourseAlert.swift
1
1422
// // CourseAlert.swift // PennMobile // // Created by Raunaq Singh on 10/25/20. // Copyright © 2020 PennLabs. All rights reserved. // import Foundation struct CourseAlert: Decodable { let id: Int let createdAt: String let originalCreatedAt: String let updatedAt: String let section: String let user: String let deleted: Bool let autoResubscribe: Bool let notificationSent: Bool let notificationSentAt: String? let closeNotification: Bool let closeNotificationSent: Bool let closeNotificationSentAt: String? let deletedAt: String? let isActive: Bool let isWaitingForClose: Bool let sectionStatus: String enum CodingKeys: String, CodingKey { case id, section, user, deleted case createdAt = "created_at" case originalCreatedAt = "original_created_at" case updatedAt = "updated_at" case autoResubscribe = "auto_resubscribe" case notificationSent = "notification_sent" case notificationSentAt = "notification_sent_at" case closeNotification = "close_notification" case closeNotificationSent = "close_notification_sent" case closeNotificationSentAt = "close_notification_sent_at" case deletedAt = "deleted_at" case isActive = "is_active" case isWaitingForClose = "is_waiting_for_close" case sectionStatus = "section_status" } }
mit
150aa89734860ed0bc8d50c1ebf7c946
28.604167
67
0.683322
4.345566
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/Former/Former/RowFormers/StepperRowFormer.swift
2
3114
// // StepperRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 7/30/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol StepperFormableRow: FormableRow { func formStepper() -> UIStepper func formTitleLabel() -> UILabel? func formDisplayLabel() -> UILabel? } open class StepperRowFormer<T: UITableViewCell> : BaseRowFormer<T>, Formable where T: StepperFormableRow { // MARK: Public open var value: Double = 0 open var titleDisabledColor: UIColor? = .lightGray open var displayDisabledColor: UIColor? = .lightGray public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } @discardableResult public final func onValueChanged(_ handler: @escaping ((Double) -> Void)) -> Self { onValueChanged = handler return self } @discardableResult public final func displayTextFromValue(_ handler: @escaping ((Double) -> String?)) -> Self { displayTextFromValue = handler return self } open override func cellInitialized(_ cell: T) { super.cellInitialized(cell) cell.formStepper().addTarget(self, action: #selector(StepperRowFormer.valueChanged(stepper:)), for: .valueChanged) } open override func update() { super.update() cell.selectionStyle = .none let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() let stepper = cell.formStepper() stepper.value = value stepper.isEnabled = enabled displayLabel?.text = displayTextFromValue?(value) ?? "\(value)" if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayColor.map { displayLabel?.textColor = $0 } _ = stepperTintColor.map { stepper.tintColor = $0 } titleColor = nil displayColor = nil stepperTintColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .black } if displayColor == nil { displayColor = displayLabel?.textColor ?? .black } if stepperTintColor == nil { stepperTintColor = stepper.tintColor } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor stepper.tintColor = stepperTintColor?.withAlphaComponent(0.5) } } // MARK: Private private final var onValueChanged: ((Double) -> Void)? private final var displayTextFromValue: ((Double) -> String?)? private final var titleColor: UIColor? private final var displayColor: UIColor? private final var stepperTintColor: UIColor? @objc private dynamic func valueChanged(stepper: UIStepper) { let value = stepper.value self.value = value cell.formDisplayLabel()?.text = displayTextFromValue?(value) ?? "\(value)" onValueChanged?(value) } }
mit
4f982718e8b8c484ad16036f28452835
33.588889
122
0.635721
5.078303
false
false
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/Extension/NSDate-Extension.swift
1
2064
// // NSDate-Extension.swift // LHBWeibo // // Created by LHB on 16/8/19. // Copyright © 2016年 LHB. All rights reserved. // import UIKit class NSDate_Extension: NSDate { } extension NSDate { class func createDateString(createAtStr : String) -> String { // 1.创建时间格式化对象 let fmt = NSDateFormatter() fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" fmt.locale = NSLocale(localeIdentifier: "en") // 2.将字符串时间,转成NSDate类型 guard let createDate = fmt.dateFromString(createAtStr) else { return "" } // 3.创建当前时间 let nowDate = NSDate() // 4.计算创建时间和当前时间的时间差 let interval = Int(nowDate.timeIntervalSinceDate(createDate)) // 5.对时间间隔处理 // 5.1.显示刚刚 if interval < 60 { return "刚刚" } // 5.2.59分钟前 if interval < 60 * 60 { return "\(interval / 60)分钟前" } // 5.3.11小时前 if interval < 60 * 60 * 24 { return "\(interval / (60 * 60))小时前" } // 5.4.创建日历对象 let calendar = NSCalendar.currentCalendar() // 5.5.处理昨天数据: 昨天 12:23 if calendar.isDateInYesterday(createDate) { fmt.dateFormat = "昨天 HH:mm" let timeStr = fmt.stringFromDate(createDate) return timeStr } // 5.6.处理一年之内: 02-22 12:22 let cmps = calendar.components(.Year, fromDate: createDate, toDate: nowDate, options: []) if cmps.year < 1 { fmt.dateFormat = "MM-dd HH:mm" let timeStr = fmt.stringFromDate(createDate) return timeStr } // 5.7.超过一年: 2014-02-12 13:22 fmt.dateFormat = "yyyy-MM-dd HH:mm" let timeStr = fmt.stringFromDate(createDate) return timeStr } }
apache-2.0
5ea785dcb2a041390ec660d6b1a04e6b
25.478873
97
0.522618
4.0671
false
false
false
false
Yoloabdo/CS-193P
DropIt/DropIt/DropitViewController.swift
1
2712
// // ViewController.swift // DropIt // // Created by abdelrahman mohamed on 3/1/16. // Copyright © 2016 Abdulrhman dev. All rights reserved. // import UIKit class DropitViewController: UIViewController { @IBOutlet weak var viewGame: BezierPathsView! lazy var animator: UIDynamicAnimator = { let lazyAnimtor = UIDynamicAnimator(referenceView: self.viewGame) return lazyAnimtor }() var dropitBehav = DropItBehavior() var dropsPerRow = 10 var dropSize: CGSize { var size = viewGame.bounds.size.width / CGFloat(dropsPerRow) size += CGFloat.random(20) return CGSize(width: size, height: size) } @IBAction func drop(sender: UITapGestureRecognizer) { drop() } func addPathBarrier(x: CGFloat, y : CGFloat, name: String){ let size = viewGame.bounds.size.width / CGFloat(10) let barrierSize = CGSize(width: size, height: size) let barrierOrigin = CGPoint(x: x - barrierSize.width/2 , y: y - barrierSize.height/2) let path = UIBezierPath(ovalInRect: CGRect(origin: barrierOrigin, size: barrierSize)) dropitBehav.addBarrier(path, name: name) viewGame.setPath(path, name: name) } override func viewDidLoad() { super.viewDidLoad() animator.addBehavior(dropitBehav) } private struct PathStory { static let barrierName = "centerBarrier" } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // addPathBarrier(viewGame.bounds.midX * 1.5 , y: viewGame.bounds.midX, name: "first") // addPathBarrier(viewGame.bounds.midX/2, y: viewGame.bounds.midX, name: "third") addPathBarrier(viewGame.bounds.midX, y: viewGame.bounds.midY, name: PathStory.barrierName) } func drop() { var frame = CGRect(origin: CGPointZero, size: dropSize) frame.origin.x = CGFloat.random(dropsPerRow) * dropSize.width let dropView = UIView(frame: frame) dropView.backgroundColor = UIColor.random viewGame.addSubview(dropView) dropitBehav.addDrop(dropView) } } private extension CGFloat { static func random(max: Int) -> CGFloat { return CGFloat(arc4random() % UInt32(max)) } } private extension UIColor{ class var random: UIColor { switch arc4random() % 5 { case 0: return UIColor.greenColor() case 1: return UIColor.redColor() case 2: return UIColor.blueColor() case 3: return UIColor.orangeColor() case 4: return UIColor.purpleColor() default: return UIColor.blackColor() } } }
mit
b8523badb5a91ab197fa36c9265c50ac
28.16129
98
0.636665
4.126332
false
false
false
false
Dwarven/ShadowsocksX-NG
ShadowsocksX-NG/ImportWindowController.swift
2
1914
// // ImportWindowController.swift // ShadowsocksX-NG // // Created by 邱宇舟 on 2019/9/10. // Copyright © 2019 qiuyuzhou. All rights reserved. // import Cocoa class ImportWindowController: NSWindowController { @IBOutlet weak var inputBox: NSTextField! override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. let pb = NSPasteboard.general if #available(OSX 10.13, *) { if let text = pb.string(forType: NSPasteboard.PasteboardType.URL) { if let url = URL(string: text) { if url.scheme == "ss" { inputBox.stringValue = text } } } } if let text = pb.string(forType: NSPasteboard.PasteboardType.string) { let urls = ServerProfileManager.findURLSInText(text) if urls.count > 0 { inputBox.stringValue = text } } } @IBAction func handleImport(_ sender: NSButton) { let mgr = ServerProfileManager.instance let urls = ServerProfileManager.findURLSInText(inputBox.stringValue) let addCount = mgr.addServerProfileByURL(urls: urls) if addCount > 0 { let alert = NSAlert.init() alert.alertStyle = .informational; alert.messageText = "Success to add \(addCount) server.".localized alert.addButton(withTitle: "OK") alert.runModal() self.close() } else { let alert = NSAlert.init() alert.alertStyle = .informational; alert.messageText = "Not found valid shadowsocks server urls.".localized alert.addButton(withTitle: "OK") alert.runModal() } } }
gpl-3.0
43f02f6d1c987a82e8bae7da4ddc22d1
32.45614
134
0.57892
4.791457
false
false
false
false
airfight/ATAnimatons
GYWaveView/InstrumentView.swift
1
4535
// // InstrumentView.swift // ATAnimatons // // Created by ZGY on 2018/1/16. //Copyright © 2018年 macpro. All rights reserved. // // Author: Airfight // My GitHub: https://github.com/airfight // My Blog: http://airfight.github.io/ // My Jane book: http://www.jianshu.com/users/17d6a01e3361 // Current Time: 2018/1/16 上午10:26 // GiantForJade: Efforts to do my best // Real developers ship. import UIKit class InstrumentView: UIView { private var progressLayer:CAShapeLayer? private var colorsLayer:CAGradientLayer? private var startAngle = CGFloat.pi * 0.75 private var endAngle = CGFloat.pi * 2.25 private var radius:CGFloat = 0.0 private var widthA:CGFloat = 0.0 private var heightA:CGFloat = 0.0 private var sumAngle = CGFloat.pi * 1.5 var progress:CGFloat = 0 override init(frame: CGRect) { super.init(frame: frame) initData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() initData() } override func draw(_ rect: CGRect) { super.draw(rect) drawLayer() } private func initData() { self.backgroundColor = UIColor.clear radius = self.frame.width/2 widthA = self.frame.width / 2 heightA = self.frame.width / 2 } func setTemperature(_ temperature:CGFloat) { let sumNum = CGFloat(sumAngle / (CGFloat.pi * 0.03)) progress = temperature * (sumNum/100.0) setNeedsDisplay() } fileprivate func drawLayer() { let context = UIGraphicsGetCurrentContext() //获取上下文 context?.translateBy(x: self.bounds.midX, y: self.bounds.midY) let sumNum = Int(sumAngle / (CGFloat.pi * 0.03)) let colors = Colors.getMuatbleColors() for i in 0...sumNum { if i == 0 { context?.rotate(by: (CGFloat.pi * 45 / 180)) } else { context?.rotate(by: (CGFloat.pi * 0.03)) } if i%2 == 1 { context?.saveGState() context?.addLines(between: [CGPoint(x: 0, y: radius * 0.75),CGPoint(x: 0, y: radius * 0.75 + 15 )]) context?.setStrokeColor(colors[sumNum - i].cgColor) context?.setLineWidth(3) context?.setLineCap(CGLineCap.round) context?.strokePath() context?.restoreGState() } else { context?.saveGState() context?.addLines(between: [CGPoint(x: 0, y: radius * 0.75),CGPoint(x: 0, y: radius * 0.75 + 25 )]) context?.setStrokeColor(colors[sumNum - i].cgColor) context?.setLineWidth(3) context?.setLineCap(CGLineCap.round) context?.strokePath() context?.restoreGState() } } context?.translateBy(x: 0, y: 0) context?.saveGState() let path = UIBezierPath(arcCenter: CGPoint(x: 0, y: 0), radius: radius * 0.6, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false) context?.addPath(path.cgPath) path.addLine(to:CGPoint(x: -radius * 0.2, y: radius * 0.5)) path.addLine(to: CGPoint(x: -radius * 0.5, y: radius * 0.5)) path.addLine(to: CGPoint(x: -radius * 0.5, y: radius * 0.2)) context?.rotate(by: (CGFloat.pi * 45 / 180) + (CGFloat.pi * 0.03) * progress) context?.setStrokeColor(UIColor.white.cgColor) context?.setFillColor(UIColor.white.cgColor) path.fill() context?.strokePath() context?.restoreGState()//恢复成初始状态 let str:NSString = "\(Int(progress * 2.0))" + "℃" as NSString context?.saveGState() context?.rotate(by: (CGFloat.pi * 45 / 180)) let attributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 40), NSAttributedStringKey.foregroundColor: UIColor.blue] str.draw(at: CGPoint(x: -42, y:-50), withAttributes: attributes) ("当前温度" as NSString).draw(at: CGPoint(x: -60, y:10), withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 30), NSAttributedStringKey.foregroundColor: UIColor.blue]) context?.restoreGState() } }
mit
8ba2d00289804cbf52d3e95cb4f10d6a
32.044118
191
0.566756
4.096627
false
false
false
false
robconrad/fledger-mac
FledgerMac/AppDelegate.swift
1
1978
// // AppDelegate.swift // FledgerMac // // Created by Robert Conrad on 8/9/15. // Copyright (c) 2015 Robert Conrad. All rights reserved. // import Cocoa import FledgerCommon @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var window: NSWindow? var storyboard: NSStoryboard? func applicationDidFinishLaunching(aNotification: NSNotification) { window = NSApplication.sharedApplication().windows.first! storyboard = NSStoryboard(name: "Main", bundle: nil) ServiceBootstrap.preRegister() if (UserSvc().isLoggedIn()) { ServiceBootstrap.register() showMainTabView() } else { showLoginView() } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func showMainTabView() { let mainTabController = storyboard?.instantiateControllerWithIdentifier("mainTabViewController") as! MainTabViewController window?.contentViewController = mainTabController window?.contentView = mainTabController.view } func showLoginView() { let loginController = storyboard?.instantiateControllerWithIdentifier("loginViewController") as! LoginViewController loginController.loginHandler = { valid in if valid { self.showMainTabView() } } window?.contentViewController = loginController window?.contentView = loginController.view window?.makeFirstResponder(loginController.email) } @IBAction func logout(sender: AnyObject) { UserSvc().logout() showLoginView() } override func validateMenuItem(menuItem: NSMenuItem) -> Bool { if let item = menuItem as? AppMenuItem { return item.isValid() } return true } }
mit
bd9b3c2824378d962577f904b7990e10
26.109589
130
0.632457
5.683908
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/ProtocolServiceMultiplexer.swift
1
754
// // PSM.swift // Bluetooth // // Created by Alsey Coleman Miller on 3/1/16. // Copyright © 2016 PureSwift. All rights reserved. // /// Protocol/Service Multiplexer (PSM). @frozen public enum ProtocolServiceMultiplexer: UInt8 { case sdp = 0x0001 case rfcomm = 0x0003 case tcs = 0x0005 case ctp = 0x0007 case bnep = 0x000F case hidc = 0x0011 case hidi = 0x0013 case upnp = 0x0015 case avctp = 0x0017 case avdtp = 0x0019 /// Advanced Control - Browsing case avctp13 = 0x001B /// Unrestricted Digital Information Profile C-Plane case udicp = 0x001D /// Attribute Protocol case att = 0x001F }
mit
cae60953c70ba7ac8d37235fcd1d8a7f
22.53125
56
0.576361
3.454128
false
false
false
false
ekreative/testbuild-rocks-ios
AppsV2/AVProjectController.swift
1
3956
// // AVProjectController.swift // AppsV2 // // Created by Device Ekreative on 6/27/15. // Copyright (c) 2015 Sergei Polishchuk. All rights reserved. // import UIKit class AVProjectController: AVParentViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { @IBOutlet weak var tableView: UITableView! var refresher:UIRefreshControl! var selectedProject:AVProject! lazy var fetchResults :NSFetchedResultsController = { let request = NSFetchRequest(entityName: AVProject.entityName()) request.sortDescriptors = [NSSortDescriptor(key: "id", ascending: true)] let fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: RKObjectManager.sharedManager().managedObjectStore.mainQueueManagedObjectContext, sectionNameKeyPath: nil, cacheName: nil) var error: NSError? fetchedResultsController.performFetch(&error) if let error = error { NSLog("Error %@, %@", error, error.userInfo ?? "") abort(); } return fetchedResultsController }() override func viewDidLoad() { super.viewDidLoad() fetchResults.delegate = self loadProjects() var barButton = UIBarButtonItem(title: "Log out", style: UIBarButtonItemStyle.Plain, target: self, action: "logout") self.navigationItem.rightBarButtonItem = barButton self.navigationController refresher = UIRefreshControl() refresher.attributedTitle = NSAttributedString(string: "Pull to refresh") refresher.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) tableView.addSubview(refresher) tableView.delegate = self tableView.dataSource = self } func logout(){ AVUser.logout() } func loadProjects(isRefresher:Bool = false){ AVRequestHelper.getProjectList({ (operation, mappingResult) -> Void in self.fetchResults.performFetch(nil) self.tableView.reloadData() if isRefresher { self.refresher.endRefreshing() } }, failure: { (operation, error) -> Void in SVProgressHUD.showErrorWithStatus("Network error") }) } func refresh(sender:AnyObject){ loadProjects(isRefresher: true) } // MARK:- UITableView Delegates func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if fetchResults.fetchedObjects?.count > 0{ return fetchResults.fetchedObjects!.count } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let project = fetchResults.objectAtIndexPath(indexPath) as! AVProject var cell = tableView.dequeueReusableCellWithIdentifier("projectCell") as! AVProjectCell cell.projectName.text = project.name?.uppercaseString cell.createdTime.text = Helper.getTimeByTimeStr(project.created!).uppercaseString cell.iconProject.sd_setImageWithURL(NSURL(string: API_BASE_URL+"/image.png")!, placeholderImage: UIImage(named: "project_placeholder")) return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showApps" { let selectedRow = self.tableView.indexPathForCell(sender as! AVProjectCell) let appsListVC = segue.destinationViewController as! AVAppsListController var project = fetchResults.objectAtIndexPath(selectedRow!) as! AVProject appsListVC.project = project } } }
mit
6ec36eeb52f7391f9375a31f5d5b30c8
35.971963
233
0.668099
5.52514
false
false
false
false
ishkawa/APIKit
Tests/APIKitTests/SessionTests.swift
1
7822
import Foundation import APIKit import XCTest class SessionTests: XCTestCase { var adapter: TestSessionAdapter! var session: Session! override func setUp() { super.setUp() adapter = TestSessionAdapter() session = Session(adapter: adapter) } func testSuccess() throws { let dictionary = ["key": "value"] adapter.data = try XCTUnwrap(JSONSerialization.data(withJSONObject: dictionary, options: [])) let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.send(request) { response in switch response { case .success(let dictionary): XCTAssertEqual((dictionary as? [String: String])?["key"], "value") case .failure: XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Response error func testParseDataError() { adapter.data = "{\"broken\": \"json}".data(using: .utf8, allowLossyConversion: false) let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as NSError) = error { XCTAssertEqual(responseError.domain, NSCocoaErrorDomain) XCTAssertEqual(responseError.code, 3840) } else { XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } func testUnacceptableStatusCodeError() { adapter.urlResponse = HTTPURLResponse(url: NSURL(string: "")! as URL, statusCode: 400, httpVersion: nil, headerFields: nil) let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as ResponseError) = error, case .unacceptableStatusCode(let statusCode) = responseError { XCTAssertEqual(statusCode, 400) } else { XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } func testNonHTTPURLResponseError() { adapter.urlResponse = URLResponse() let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.send(request) { result in if case .failure(let error) = result, case .responseError(let responseError as ResponseError) = error, case .nonHTTPURLResponse(let urlResponse) = responseError { XCTAssert(urlResponse === self.adapter.urlResponse) } else { XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Request error func testRequestError() { struct Error: Swift.Error {} let expectation = self.expectation(description: "wait for response") let request = TestRequest() { urlRequest in throw Error() } session.send(request) { result in if case .failure(let error) = result, case .requestError(let requestError) = error { XCTAssert(requestError is Error) } else { XCTFail() } expectation.fulfill() } waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Cancel func testCancel() { let expectation = self.expectation(description: "wait for response") let request = TestRequest() session.send(request) { result in if case .failure(let error) = result, case .connectionError(let connectionError as NSError) = error { XCTAssertEqual(connectionError.code, 0) } else { XCTFail() } expectation.fulfill() } session.cancelRequests(with: TestRequest.self) waitForExpectations(timeout: 1.0, handler: nil) } func testCancelFilter() { let successExpectation = expectation(description: "wait for response") let successRequest = TestRequest(path: "/success") session.send(successRequest) { result in if case .failure = result { XCTFail() } successExpectation.fulfill() } let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest(path: "/failure") session.send(failureRequest) { result in if case .success = result { XCTFail() } failureExpectation.fulfill() } session.cancelRequests(with: TestRequest.self) { request in return request.path == failureRequest.path } waitForExpectations(timeout: 1.0, handler: nil) } struct AnotherTestRequest: Request { typealias Response = Void var baseURL: URL { return URL(string: "https://example.com")! } var method: HTTPMethod { return .get } var path: String { return "/" } } func testCancelOtherRequest() { let successExpectation = expectation(description: "wait for response") let successRequest = AnotherTestRequest() session.send(successRequest) { result in if case .failure = result { XCTFail() } successExpectation.fulfill() } let failureExpectation = expectation(description: "wait for response") let failureRequest = TestRequest() session.send(failureRequest) { result in if case .success = result { XCTFail() } failureExpectation.fulfill() } session.cancelRequests(with: TestRequest.self) waitForExpectations(timeout: 1.0, handler: nil) } // MARK: Class methods func testSharedSession() { XCTAssert(Session.shared === Session.shared) } func testSubclassClassMethods() { class SessionSubclass: Session { static let testSesssion = SessionSubclass(adapter: TestSessionAdapter()) var functionCallFlags = [String: Bool]() override class var shared: Session { return testSesssion } override func send<Request : APIKit.Request>(_ request: Request, callbackQueue: CallbackQueue?, handler: @escaping (Result<Request.Response, SessionTaskError>) -> Void) -> SessionTask? { functionCallFlags[(#function)] = true return super.send(request) } override func cancelRequests<Request : APIKit.Request>(with requestType: Request.Type, passingTest test: @escaping (Request) -> Bool) { functionCallFlags[(#function)] = true } } let testSession = SessionSubclass.testSesssion SessionSubclass.send(TestRequest()) SessionSubclass.cancelRequests(with: TestRequest.self) XCTAssertEqual(testSession.functionCallFlags["send(_:callbackQueue:handler:)"], true) XCTAssertEqual(testSession.functionCallFlags["cancelRequests(with:passingTest:)"], true) } }
mit
800f0f5425a93ac9f4cbcb500e85e6cd
29.916996
198
0.574533
5.353867
false
true
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/WKWebViewWithSettableInputViews.swift
1
5732
import WebKit import CocoaLumberjackSwift class WKWebViewWithSettableInputViews: WKWebView { private var storedInputView: UIView? private var storedInputAccessoryView: UIView? override init(frame: CGRect, configuration: WKWebViewConfiguration) { super.init(frame: frame, configuration: configuration) WKWebViewWithSettableInputViews.overrideUserInteractionRequirementForElementFocusIfNecessary() overrideNestedContentViewGetters() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func reloadInputViews() { guard let contentView = nestedContentView() else { assertionFailure("Couldn't find content view") return } contentView.reloadInputViews() } override open var inputAccessoryView: UIView? { get { return trueSelf()?.storedInputAccessoryView } set { self.storedInputAccessoryView = newValue } } override open var inputView: UIView? { get { return trueSelf()?.storedInputView } set { self.storedInputView = newValue } } private func add(selector: Selector, to target: AnyClass, origin: AnyClass, originSelector: Selector) { guard !target.responds(to: selector), let newMethod = class_getInstanceMethod(origin, originSelector), let typeEncoding = method_getTypeEncoding(newMethod) else { assertionFailure("Couldn't add method") return } class_addMethod(target, selector, method_getImplementation(newMethod), typeEncoding) } private func nestedContentView() -> UIView? { return scrollView.subviews.first(where: { return String(describing: type(of: $0)).hasPrefix("WKContent") }) } private func trueSelf() -> WKWebViewWithSettableInputViews? { return (NSStringFromClass(type(of: self)) == "WKContentView_withCustomInputViewGetterRelays" ? wmf_firstSuperviewOfType(SectionEditorWebView.self) : self) } private func overrideNestedContentViewGetters() { guard let contentView = nestedContentView() else { assertionFailure("Couldn't find content view") return } if let existingClass = NSClassFromString("WKContentView_withCustomInputViewGetterRelays") { object_setClass(contentView, existingClass) return } guard let newContentViewClass = objc_allocateClassPair(object_getClass(contentView), "WKContentView_withCustomInputViewGetterRelays", 0) else { assertionFailure("Couldn't get class") return } self.add( selector: #selector(getter: UIResponder.inputAccessoryView), to: newContentViewClass.self, origin: SectionEditorWebView.self, originSelector: #selector(getter: SectionEditorWebView.inputAccessoryView) ) objc_registerClassPair(newContentViewClass) object_setClass(contentView, newContentViewClass) } } typealias ClosureType = @convention(c) (Any, Selector, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void private var didSetKeyboardRequiresUserInteraction = false extension WKWebViewWithSettableInputViews { // Swizzle a WKWebView method to allow web elements to be focused without user interaction // Replace the method with an implementation that wraps the existing implementation and always passes true for `userIsInteracting` // https://stackoverflow.com/questions/32449870/programmatically-focus-on-a-form-in-a-webview-wkwebview static func overrideUserInteractionRequirementForElementFocusIfNecessary() { assert(Thread.isMainThread) guard !didSetKeyboardRequiresUserInteraction else { return } defer { didSetKeyboardRequiresUserInteraction = true } guard let WKContentView: AnyClass = NSClassFromString("WKContentView") else { DDLogError("keyboardDisplayRequiresUserAction extension: Cannot find the WKContentView class") return } // The method signature changed over time, try all of them to find the one for this platform let selectorStrings = [ "_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:", "_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:", "_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:" ] #if DEBUG var found = false #endif for selectorString in selectorStrings { let sel = sel_getUid(selectorString) guard let method = class_getInstanceMethod(WKContentView, sel) else { continue } let originalImp = method_getImplementation(method) let original: ClosureType = unsafeBitCast(originalImp, to: ClosureType.self) let block : @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Bool, Any?) -> Void = { (me, arg0, arg1, arg2, arg3, arg4) in original(me, sel, arg0, true, arg2, arg3, arg4) } let imp = imp_implementationWithBlock(block) method_setImplementation(method, imp) #if DEBUG found = true #endif break } #if DEBUG assert(found, "Didn't find the method to swizzle. Maybe the signature changed.") #endif } }
mit
23e505827e58512f8cbd43ff33211edc
37.993197
162
0.652128
5.337058
false
false
false
false
oscarfuentes/Architecture
Pods/Bond/Bond/Extensions/iOS/UISegmentedControl+Bond.swift
21
2560
// // The MIT License (MIT) // // Copyright (c) 2015 Jens Nilsson (@phiberjenz) // // 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 UISegmentedControl { private struct AssociatedKeys { static var SelectedSegmentIndexKey = "bnd_SelectedSegmentIndexKey" } public var bnd_selectedSegmentIndex: Observable<Int> { if let bnd_selectedSegmentIndex: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.SelectedSegmentIndexKey) { return bnd_selectedSegmentIndex as! Observable<Int> } else { let bnd_selectedSegmentIndex = Observable<Int>(self.selectedSegmentIndex) objc_setAssociatedObject(self, &AssociatedKeys.SelectedSegmentIndexKey, bnd_selectedSegmentIndex, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) var updatingFromSelf: Bool = false bnd_selectedSegmentIndex.observeNew { [weak self] selectedSegmentIndex in if !updatingFromSelf { self?.selectedSegmentIndex = selectedSegmentIndex } } self.bnd_controlEvent.filter { $0 == UIControlEvents.ValueChanged }.observe { [weak self, weak bnd_selectedSegmentIndex] event in guard let unwrappedSelf = self, let bnd_selectedSegmentIndex = bnd_selectedSegmentIndex else { return } updatingFromSelf = true bnd_selectedSegmentIndex.next(unwrappedSelf.selectedSegmentIndex) updatingFromSelf = false } return bnd_selectedSegmentIndex } } }
mit
a9a618e3cac709421b559b155797e29b
43.137931
161
0.728125
4.904215
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Extension/UIView+ScreenShot.swift
1
4872
// // UIView+ScreenShot.swift // zhuishushenqi // // Created by Nory Cao on 2017/4/17. // Copyright © 2017年 QS. All rights reserved. // import Foundation import UIKit import PKHUD func RGBAColor<T>(_ red:T, _ green:T, _ blue:T, _ alpha:CGFloat? = 1) -> UIColor { var redString = "\(red)" var greenString = "\(green)" var blueString = "\(blue)" if redString.hasPrefix("0x") || redString.hasPrefix("0X") { redString = redString.qs_subStr(from: 2) } if greenString.hasPrefix("0x") || greenString.hasPrefix("0X") { greenString = greenString.qs_subStr(from: 2) } if blueString.hasPrefix("0x") || blueString.hasPrefix("0X") { blueString = blueString.qs_subStr(from: 2) } // if T.self == CGFloat.self || T.self == Int.self || T.self == Double.self { // let redFloatValue:CGFloat = red as! CGFloat // let greenFloatValue:CGFloat = green as! CGFloat // let blueFloatValue:CGFloat = blue as! CGFloat // return UIColor(red: redFloatValue/255, green: greenFloatValue/255, blue: blueFloatValue/255, alpha: alpha ?? 1) // } return UIColor(hexString: "#\(redString)\(greenString)\(blueString)") ?? UIColor.black } extension UIView { func screenShot()->UIImage?{ let size = self.bounds.size let transform:CGAffineTransform = __CGAffineTransformMake(-1, 0, 0, 1, size.width, 0) UIGraphicsBeginImageContextWithOptions(size, self.isOpaque, 0.0) let context = UIGraphicsGetCurrentContext() context?.concatenate(transform) self.layer.render(in: context!) let image:UIImage? = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func nextController()->UIViewController?{ var nextResponder:UIResponder? = self.next while (nextResponder != nil) { if nextResponder?.isKind(of: UIViewController.self) == true { return nextResponder as? UIViewController } nextResponder = nextResponder?.next } return nil } func showTipView(tip:String) { HUD.flash(.label(tip), delay: 3) } func showProgress() { HUD.flash(.labeledProgress(title: "正在请求...", subtitle: nil)) } func hideProgress() { HUD.hide(animated: true) } func showTip(tip:String) { let tag = 10124 if let tipLabel = self.viewWithTag(tag) { tipLabel.removeFromSuperview() } let width = tip.qs_width(UIFont.systemFont(ofSize: 14), height: 30) let label = UILabel(frame: CGRect(x: ScreenWidth/2 - (width + 20)/2, y: self.bounds.height/2 - 15, width: width + 20, height: 30)) label.backgroundColor = UIColor.gray label.textAlignment = .center label.layer.cornerRadius = 15 label.clipsToBounds = true label.font = UIFont.systemFont(ofSize: 14) label.textColor = UIColor.white label.text = tip label.tag = tag self.addSubview(label) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+3) { label.removeFromSuperview() label.text = nil } } func addShadow(cornerRadius:CGFloat) { self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowRadius = cornerRadius self.layer.shadowOffset = CGSize(width: 0.5, height: 0.5) self.layer.shadowOpacity = 0.3 } static let shadowLayerAccess = "shadowLayerAccess" static let backgroundViewAccess = "backgroundViewAccess" func addShadow(borderRadius:CGFloat) { if self.bounds.equalTo(CGRect.zero) { return } for layer in self.layer.sublayers ?? [] { if layer.accessibilityLabel == UIView.shadowLayerAccess { layer.removeFromSuperlayer() } } for view in self.subviews { if view.accessibilityLabel == UIView.backgroundViewAccess { view.removeFromSuperview() } } let backgroundView = UIView(frame: self.bounds) backgroundView.backgroundColor = UIColor.clear backgroundView.isUserInteractionEnabled = true addSubview(backgroundView) let layer = CAShapeLayer() layer.frame = self.bounds let path = UIBezierPath(roundedRect: layer.bounds, cornerRadius: borderRadius) layer.shadowPath = path.cgPath layer.shadowColor = RGBAColor(0, 0, 0, 0.5).cgColor layer.shadowRadius = borderRadius layer.masksToBounds = false self.layer.insertSublayer(layer, below: backgroundView.layer) } func removeSubviews() { for subview in self.subviews { subview.removeFromSuperview() } } }
mit
0ddd86bbe083e6889d9f71afadd6f12b
33.721429
138
0.617363
4.471941
false
false
false
false
ello/ello-ios
Specs/Controllers/PushNotificationControllerSpec.swift
1
5867
@testable import Ello import Quick import Nimble class PushNotificationControllerSpec: QuickSpec { class MockViewController: UIViewController { var presented = false override func present( _ viewControllerToPresent: UIViewController, animated flag: Bool, completion: Block? = nil ) { presented = true } } override func spec() { describe("PushNotificationController") { var currentBadgeCount = 0 beforeEach { currentBadgeCount = UIApplication.shared.applicationIconBadgeNumber } afterEach { UIApplication.shared.applicationIconBadgeNumber = currentBadgeCount } describe("-hasAlert(_:)") { context("has alert") { it("returns true") { let userInfo: [AnyHashable: Any] = [ "application_target": "notifications/posts/4", "type": "repost", "aps": [ "alert": [ "body": "@bob has reposted one of your posts", "title": "New Repost" ], "badge": NSNumber(value: 4) ] ] expect(PushNotificationController.shared.hasAlert(userInfo)) == true } } context("no alert") { it("returns false") { let userInfo: [AnyHashable: Any] = [ "type": "reset_badge_count", "aps": [ "badge": NSNumber(value: 0) ] ] expect(PushNotificationController.shared.hasAlert(userInfo)) == false } } } context("-updateBadgeCount(_:)") { context("has badge") { it("updates to new value") { UIApplication.shared.applicationIconBadgeNumber = 5 let userInfo: [AnyHashable: Any] = [ "type": "reset_badge_count", "aps": [ "badge": NSNumber(value: 0) ] ] PushNotificationController.shared.updateBadgeCount(userInfo) // yes, apparently, *printing* the value makes this spec pass print("count: \(UIApplication.shared.applicationIconBadgeNumber)") expect(UIApplication.shared.applicationIconBadgeNumber) == 0 } } context("no badge") { it("does nothing") { UIApplication.shared.applicationIconBadgeNumber = 5 let userInfo: [AnyHashable: Any] = [ "type": "reset_badge_count", "aps": [ ] ] PushNotificationController.shared.updateBadgeCount(userInfo) expect(UIApplication.shared.applicationIconBadgeNumber) == 5 } } } describe("requestPushAccessIfNeeded") { let keychain = FakeKeychain() beforeEach { AuthToken.sharedKeychain = keychain } context("when the user isn't authenticated") { it("does not present prompt") { keychain.isPasswordBased = false let controller = PushNotificationController( defaults: UserDefaults(), keychain: keychain ) let vc = MockViewController() controller.requestPushAccessIfNeeded(vc) expect(vc.presented) == false } } context("when the user is authenticated, but has denied access") { it("does not present prompt") { keychain.isPasswordBased = true let controller = PushNotificationController( defaults: UserDefaults(), keychain: keychain ) controller.permissionDenied = true let vc = MockViewController() controller.requestPushAccessIfNeeded(vc) expect(vc.presented) == false } } context( "when the user is authenticated, hasn't previously denied access, and hasn't seen the custom alert before" ) { it("presents a prompt") { keychain.authToken = "abcde" keychain.isPasswordBased = true let controller = PushNotificationController( defaults: UserDefaults(), keychain: keychain ) controller.permissionDenied = false controller.needsPermission = true let vc = MockViewController() controller.requestPushAccessIfNeeded(vc) expect(vc.presented) == true } } } } } }
mit
7fb288deda8ab0f09ecd62a4ec0bdaf6
36.608974
126
0.420147
7.128797
false
false
false
false
ktmswzw/FeelClient
FeelingClient/MVC/VM/OpenMessageModel.swift
1
2075
// // OpenMessageModel.swift // FeelingClient // // Created by vincent on 20/3/16. // Copyright © 2016 xecoder. All rights reserved. // import Foundation typealias CompletionHandler2 = (MessagesSecret) -> Void public class OpenMessageModel:BaseApi { let msg: MessageApi = MessageApi.defaultMessages //id var id: String = "" //接受对象 var to: String = "" //发送人 var from: String = "" //期限 var limitDate: String = "" //内容 var content: String = "" //图片地址 var photos: [String] = [] //视频地址 var video: String = "" //音频地址 var sound: String = "" //阅后即焚 var burnAfterReading: Bool = false //问题 var question: String? //答案 var answer: String? var x:Double = 0.0 var y:Double = 0.0 var msgscrent = MessagesSecret()// 内容 var msgscrentId = "";//解密后的id func verifyAnswer(view:UIView,completeHander: CompletionHandlerType) { msg.verifyMsg(self.id, answer: self.answer!) { (r:BaseApi.Result) in completeHander(r) } } func arrival(view:UIView,completeHander: CompletionHandler2) { if msgscrentId.length != 0 { msg.arrival(msgscrentId) { (r:BaseApi.Result) -> Void in switch (r) { case .Success(let r): self.msgscrent = r as! MessagesSecret; print(self.msgscrent) completeHander(self.msgscrent) break; case .Failure(let msg): view.makeToast(msg as! String, duration: 1, position: .Center) break; } } } else{ } } public weak var delegate: OpenMessageModelDelegate? // new initializer public init(delegate: OpenMessageModelDelegate) { self.delegate = delegate } } public protocol OpenMessageModelDelegate: class { }
mit
6f2d53ad35cbc77fb117ca22c1a353ff
21.988506
82
0.543272
4.138716
false
false
false
false
pfvernon2/swiftlets
iOSX/iOS/UIImage+Scaling.swift
1
4558
// // UIImage+Scaling.swift // swiftlets // // Created by Frank Vernon on 1/19/16. // Copyright © 2016 Frank Vernon. All rights reserved. // import UIKit extension UIImage { ///Scale image to the size supplied. If screen resolution is desired, pass scale == 0.0 func scale(toSize size:CGSize, flip:Bool = false, scale:CGFloat = .unity) -> UIImage? { let newRect:CGRect = CGRect(x:0, y:0, width:size.width, height:size.height).integral UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } guard let context:CGContext = UIGraphicsGetCurrentContext() else { return nil } // Set the quality level to use when rescaling context.interpolationQuality = CGInterpolationQuality.high //flip if requested if flip { let flipVertical:CGAffineTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height) context.concatenate(flipVertical) } // Draw into the context; this scales the image draw(in: newRect) // Get the resized image from the context and a UIImage guard let newImageRef:CGImage = context.makeImage() else { return nil } let newImage:UIImage = UIImage(cgImage: newImageRef) return newImage; } func scaleProportional(toSize size:CGSize, scale:CGFloat = 1.0) -> UIImage? { var proportialSize = size if self.size.width > self.size.height { proportialSize = CGSize(width: (self.size.width/self.size.height) * proportialSize.height, height: proportialSize.height) } else { proportialSize = CGSize(width: proportialSize.width, height: (self.size.height/self.size.width) * proportialSize.width) } return self.scale(toSize: proportialSize) } func circular() -> UIImage? { let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height)) let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square)) imageView.contentMode = .scaleAspectFill imageView.image = self imageView.layer.cornerRadius = square.width.halved imageView.layer.masksToBounds = true UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } imageView.layer.render(in: context) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } //https://gist.github.com/ffried/0cbd6366bb9cf6fc0208 public func imageRotated(byDegrees degrees: CGFloat, flip: Bool) -> UIImage? { func degreesToRadians(_ degrees:CGFloat) -> CGFloat { degrees / 180.0 * CGFloat(Double.pi) } // calculate the size of the rotated view's containing box for our drawing space let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size)) rotatedViewBox.transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees)) let rotatedSize = rotatedViewBox.frame.size // Create the bitmap context UIGraphicsBeginImageContext(rotatedSize) defer { UIGraphicsEndImageContext() } guard let bitmap:CGContext = UIGraphicsGetCurrentContext() else { return nil } // Move the origin to the middle of the image so we will rotate and scale around the center. bitmap.translateBy(x: rotatedSize.width.halved, y: rotatedSize.height.halved) // Rotate the image context bitmap.rotate(by: degreesToRadians(degrees)) // Now, draw the rotated/scaled image into the context bitmap.scaleBy(x: flip ? -1.0 : 1.0, y: -1.0) draw(in: CGRect(x: -size.width.halved, y: -size.height.halved, width: size.width, height: size.height)) let newImage:UIImage? = UIGraphicsGetImageFromCurrentImageContext() return newImage } } public extension UIImage { convenience init?(systemName: String, scale: UIImage.SymbolScale) { let config = UIImage.SymbolConfiguration(scale: scale) self.init(systemName: systemName, withConfiguration: config) } }
apache-2.0
1baf89ddceaa2a63f1de8b18da2dd6fe
36.661157
133
0.630239
4.673846
false
false
false
false
cloudinary/cloudinary_ios
Cloudinary/Classes/Core/Features/Helpers/Results/Helpers/CLDBoundingBox.swift
1
2849
// // CLDBoundingBox.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreGraphics @objcMembers open class CLDBoundingBox: CLDBaseResult { open var topLeft: CGPoint? { return CLDBoundingBox.parsePoint(resultJson, key: String(describing: CLDBoundingBoxJsonKey.topLeft)) } open var size: CGSize? { return CLDBoundingBox.parseSize(resultJson, key: String(describing: CLDBoundingBoxJsonKey.size)) } internal static func parsePoint(_ json: [String : AnyObject], key: String) -> CGPoint? { guard let point = json[key] as? [String : Double], let x = point[CommonResultKeys.x.description], let y = point[CommonResultKeys.y.description] else { return nil } return CGPoint(x: CGFloat(x), y: CGFloat(y)) } internal static func parseSize(_ json: [String : AnyObject], key: String) -> CGSize? { guard let point = json[key] as? [String : Double], let width = point[CommonResultKeys.width.description], let height = point[CommonResultKeys.height.description] else { return nil } return CGSize(width: CGFloat(width), height: CGFloat(height)) } // MARK: - Private Helpers fileprivate func getParam(_ param: CLDBoundingBoxJsonKey) -> AnyObject? { return resultJson[String(describing: param)] } fileprivate enum CLDBoundingBoxJsonKey: CustomStringConvertible { case topLeft, size var description: String { switch self { case .topLeft: return "tl" case .size: return "size" } } } }
mit
5ee0b538e8ee467c9260ae90b5aa2736
38.027397
108
0.664093
4.536624
false
false
false
false
masters3d/xswift
exercises/bowling/Sources/BowlingExample.swift
1
3089
struct Bowling { enum BowlingError: Error { case invalidNumberOfPins case tooManyPinsInFrame case gameIsOver case gameInProgress } private let minPins = 0 private let maxPins = 10 private var scoreCard = [Int: [Int]]() private var currentFrame: Int { return scoreCard.keys.max() ?? 1 } private var isLastFrame: Bool { return currentFrame == 10 } mutating func roll(pins: Int) throws { try validate(pins: pins) var currentValue = scoreCard[currentFrame] ?? [] currentValue.append(pins) scoreCard[currentFrame] = currentValue if frameComplete() && !isLastFrame { scoreCard[currentFrame + 1] = [] } } func score() throws -> Int { guard gameIsComplete() else { throw BowlingError.gameInProgress } var result = 0 for index in 1...10 { if let frame = scoreCard[index] { result += scoreFrame(frame, index: index) } } return result } private func scoreFrame(_ frame: [Int], index: Int) -> Int { let strikeOrSpare = [frame.first, frame.reduce(0, +)] .flatMap { $0 } .contains(maxPins) if strikeOrSpare { let scores = [scoreCard[index], scoreCard[index + 1], scoreCard[index + 2]].flatMap { $0 }.flatMap { $0 } let firstThree = scores[0...2] return firstThree.reduce(0, +) } else { return frame.reduce(0, +) } } private func validate(pins: Int) throws { guard minPins...maxPins ~= pins else { throw BowlingError.invalidNumberOfPins } guard validFrame(pins: pins) else { throw BowlingError.tooManyPinsInFrame } guard !gameIsComplete() else { throw BowlingError.gameIsOver } } private func validFrame(pins: Int) -> Bool { if isLastFrame { let lastRollWasStrike = scoreCard[currentFrame]?.last == 10 if lastRollWasStrike || isSpare() { return true } } let lastRoll = scoreCard[currentFrame]?.last ?? 0 return lastRoll + pins <= maxPins } private func gameIsComplete() -> Bool { return isLastFrame && frameComplete() } private func frameComplete() -> Bool { if isLastFrame { return isOpenFrame() && frameFilled() || frameFilled(rolls: 3) } return frameFilled() || isStrike() } private func frameFilled(rolls: Int = 2) -> Bool { return scoreCard[currentFrame]?.count == rolls } private func isStrike() -> Bool { return scoreCard[currentFrame]?.first == 10 } private func isSpare() -> Bool { guard let rolls = scoreCard[currentFrame] else { return false } let total = rolls.reduce(0, +) return total == 10 } private func isOpenFrame() -> Bool { return !isSpare() && !isStrike() } }
mit
a6923fef851aec600b7360f8e182e958
24.528926
117
0.554548
4.431851
false
false
false
false
savelii/BSON
Sources/ISO8601.swift
1
8283
import Foundation /// Reads a `String` into hours, minutes and seconds private func parseTimestamp(_ timestamp: String) -> (hours: Int, minutes: Int, seconds: Int, used: Int)? { var index = 0 let maxIndex = timestamp.characters.count // We always at least have minutes and hours guard maxIndex >= 4 else { return nil } guard let hours = Int(timestamp[index..<index+2]) else { return nil } index += 2 // If there's a semicolon, advance if timestamp[index] == ":" && index + 3 <= maxIndex { index += 1 } guard let minutes = Int(timestamp[index..<index+2]) else { return nil } index += 2 var seconds = 0 // If there are seconds if maxIndex >= index + 2 { // If there's a semicolon, advance if timestamp[index] == ":" { index += 1 } // If there are still two characters left (in the case of a colon), try to parse it into an `Int` for seconds guard maxIndex >= index + 2, let s = Int(timestamp[index..<index+2]) else { return nil } seconds = s index += 2 } return (hours, minutes, seconds, index) } /// Parses a timestamp (not date) from a `String` including timezones private func parseTime(from string: String) -> Time? { var index = 0 let maxIndex = string.characters.count guard let result = parseTimestamp(string) else { return nil } index += result.used let hours = result.hours let minutes = result.minutes let seconds = result.seconds var offsetHours = 0 var offsetMinutes = 0 var offsetSeconds = 0 // If there's a timezone marker if maxIndex >= index + 3 && (string[index] == "+" || string[index] == "-" || string[index] == "Z") { switch string[index] { case "+": index += 1 guard let offsetResult = parseTimestamp(string[index..<maxIndex]) else { return nil } index += offsetResult.used // Subtract from epoch time, since we're ahead of UTC offsetHours = -(offsetResult.hours) offsetMinutes = -(offsetResult.minutes) offsetSeconds = -(offsetResult.seconds) case "-": index += 1 guard let offsetResult = parseTimestamp(string[index..<maxIndex]) else { return nil } index += offsetResult.used // Add to epoch time, since we're behind of UTC offsetHours = offsetResult.hours offsetMinutes = offsetResult.minutes offsetSeconds = offsetResult.seconds case "Z": break default: return nil } } return (hours, minutes, seconds, offsetHours, offsetMinutes, offsetSeconds) } /// Parses an ISO8601 string into a `Date` object /// /// TODO: Doesn't work with weeks yet /// /// TODO: Doesn't work with empty years yet (except 2016)! /// /// TODO: Doesn't work with yeardays, only months internal func parseISO8601(from string: String) -> Date? { let year: Int let maxIndex = string.characters.count - 1 var index = 0 if string[0] == "-" { let fmt = DateFormatter() fmt.locale = Locale(identifier: "en_US_POSIX") fmt.dateFormat = "yyyy" guard let yyyy = Int(fmt.string(from: Date())) else { return nil } year = yyyy index += 1 } else if string.characters.count >= 4 { guard let tmpYear = Int(string[0..<4]) else { return nil } year = tmpYear index += 4 } else { return nil } guard index <= maxIndex else { return nil } if string[index] == "-" { index += 1 } if string[index] == "W" { // parse week } else { // parse yearday too, not just months guard index + 2 <= maxIndex else { return nil } guard let month = Int(string[index..<index + 2]) else { return nil } index += 2 guard index <= maxIndex else { return date(year: year, month: month) } if string[index] == "-" { index += 1 } guard index <= maxIndex else { return date(year: year, month: month) } let day: Int if index + 1 > maxIndex { guard let d = Int(string[index..<index + 1]) else { return nil } day = d return date(year: year, month: month, day: day) } else if index + 2 > maxIndex { guard let d = Int(string[index..<index + 2]) else { return nil } day = d return date(year: year, month: month, day: day) } else if string[index + 1] == "T" { guard let d = Int(string[index..<index + 1]) else { return nil } day = d index += 2 return date(year: year, month: month, day: day, time: parseTime(from: string[index..<maxIndex])) } else if string[index + 2] == "T" { guard let d = Int(string[index..<index + 2]) else { return nil } day = d index += 3 return date(year: year, month: month, day: day, time: parseTime(from: string[index..<maxIndex + 1])) } else { return nil } } return nil } typealias Time = (hours: Int, minutes: Int, seconds: Int, offsetHours: Int, offsetMinutes: Int, offsetSeconds: Int) /// Calculates the amount of passed days private func totalDays(inMonth month: Int, forYear year: Int, currentDay day: Int) -> Int { // Subtract one day. The provided day is not the amount of days that have passed, it's the current day var days = day - 1 // Add leap day for months beyond 2 if year % 4 == 0 { days += 1 } switch month { case 1: return 0 + day - 1 case 2: return 31 + day - 1 case 3: return days + 59 case 4: return days + 90 case 5: return days + 120 case 6: return days + 151 case 7: return days + 181 case 8: return days + 212 case 9: return days + 243 case 10: return days + 273 case 11: return days + 304 default: return days + 334 } } /// Calculates epoch date from provided time information private func date(year: Int, month: Int, day: Int? = nil, time: Time? = nil) -> Date { let seconds = (time?.seconds ?? 0) - (time?.offsetSeconds ?? 0) let minutes = (time?.minutes ?? 0) - (time?.offsetMinutes ?? 0) // Remove one hours, to indicate the hours that passed this day // Not the current hour let hours = (time?.hours ?? 0) + (time?.offsetHours ?? 0) let day = day ?? 0 let yearDay = totalDays(inMonth: month, forYear: year, currentDay: day) let year = year - 1900 let epoch = seconds + minutes*60 + hours*3600 + yearDay*86400 + (year-70)*31536000 + ((year-69)/4)*86400 - ((year-1)/100)*86400 + ((year+299)/400)*86400 return Date(timeIntervalSince1970: Double(epoch)) } // MARK - String helpers private extension String { subscript(_ i: Int) -> String { get { let index = self.characters.index(self.characters.startIndex, offsetBy: i) return String(self.characters[index]) } } subscript(_ i: CountableRange<Int>) -> String { get { var result = "" for j in i { let index = self.characters.index(self.characters.startIndex, offsetBy: j) result += String(self.characters[index]) } return result } } }
mit
3a5af3aa61b6baf9afc6852beed3485c
26.518272
117
0.513823
4.446055
false
false
false
false
davejlin/treehouse
swift/swift2/stormy-weather-app/Stormy/ViewController.swift
1
3509
// // ViewController.swift // Stormy // // Created by Pasan Premaratne on 4/9/16. // Copyright © 2016 Treehouse. All rights reserved. // import UIKit extension CurrentWeather { var temperatureString: String { return "\(Int(temperature))º" } var humidityString: String { let percentageValue = Int(humidity * 100) return "\(percentageValue)%" } var precipitationProbabilityString: String { let percentageValue = Int(precipitationProbability * 100) return "\(percentageValue)%" } } class ViewController: UIViewController { @IBOutlet weak var currentTemperatureLabel: UILabel! @IBOutlet weak var currentHumidityLabel: UILabel! @IBOutlet weak var currentPrecipitationLabel: UILabel! @IBOutlet weak var currentWeatherIcon: UIImageView! @IBOutlet weak var currentSummaryLabel: UILabel! @IBOutlet weak var refreshButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! private static let forecastAPIKey = "89a49f4c339998d20903054b5191925c" // use your darksky.net weather API key here private let coordinate = Coordinate(latitude: 42.0429429, longitude: -87.68146) private lazy var forecastAPIClient = ForecastAPIClient(APIKey: forecastAPIKey) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. fetchCurrentWeather() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func fetchCurrentWeather() { forecastAPIClient.fetchCurrentWeather(coordinate) { result in dispatch_async(dispatch_get_main_queue()) { self.toggleRefreshAnimation(false) } switch result { case .Success(let currentWeather): dispatch_async(dispatch_get_main_queue()) { self.display(currentWeather) } case .Failure(let error as NSError): dispatch_async(dispatch_get_main_queue()) { self.showAlert("Unable to retrieve forecast", message: error.localizedDescription) } default: break } } } func display(weather: CurrentWeather) { currentTemperatureLabel.text = weather.temperatureString currentPrecipitationLabel.text = weather.precipitationProbabilityString currentHumidityLabel.text = weather.humidityString currentSummaryLabel.text = weather.summary currentWeatherIcon.image = weather.icon } func showAlert(title: String, message: String?, style: UIAlertControllerStyle = .Alert) { let alertController = UIAlertController(title: title, message: message, preferredStyle: style) let dismissAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(dismissAction) presentViewController(alertController, animated: true, completion: nil) } @IBAction func refreshButtonTapped(sender: AnyObject) { fetchCurrentWeather() toggleRefreshAnimation(true) } func toggleRefreshAnimation(on: Bool) { refreshButton.hidden = on if on { activityIndicator.startAnimating() } else { activityIndicator.stopAnimating() } } }
unlicense
a2cb3096200292cf634d7bc721deb334
30.881818
119
0.658397
5.1347
false
false
false
false
mansoor92/MaksabComponents
Example/Pods/StylingBoilerPlate/StylingBoilerPlate/Classes/Extensions/String+custom.swift
1
2065
// // String+custom.swift // Pods // // Created by Incubasys on 14/09/2017. // // import Foundation extension String{ public static func boldAttributedString(boldComponent: String, otherComponent: String, boldFont: UIFont, otherfont: UIFont, textColor: UIColor, boldTextColor: UIColor = UIColor.appColor(color: .DarkText), boldFirst: Bool = true) -> NSAttributedString { let boldAttrs = [NSFontAttributeName: boldFont, NSForegroundColorAttributeName: boldTextColor] let boldAttributedString = NSAttributedString(string:"\(boldComponent) ", attributes: boldAttrs) let otherAttrs = [NSFontAttributeName: otherfont, NSForegroundColorAttributeName: textColor] let otherAttributedString = NSAttributedString(string:"\(otherComponent)", attributes: otherAttrs) let finalAttributedString: NSMutableAttributedString! if boldFirst{ finalAttributedString = NSMutableAttributedString(attributedString: boldAttributedString) finalAttributedString.append(otherAttributedString) }else{ finalAttributedString = NSMutableAttributedString(attributedString: otherAttributedString) finalAttributedString.append(boldAttributedString) } return finalAttributedString } public static func getMaxHeight(text: String, font: UIFont, width: CGFloat, maxHeight: CGFloat) -> CGFloat { let label = UILabel(frame: CGRect(x: 0, y: 0, width: width,height: CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.font = font label.text = text label.sizeToFit() let height = label.frame.size.height + 16 if height > maxHeight{ return maxHeight }else{ return height } } func localized() -> String { return NSLocalizedString(self, tableName: "Localizable", bundle: Bundle.stylingBoilerPlateBundle, value: "ABC", comment: "Localized string") } }
mit
4a84673136fd6a20a958d541ed273538
38.711538
258
0.686683
5.241117
false
false
false
false
zisko/swift
test/IRGen/reflection_metadata.swift
1
4894
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s | %FileCheck %s // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -disable-reflection-names -emit-ir %s | %FileCheck %s --check-prefix=STRIP_REFLECTION_NAMES // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -disable-reflection-metadata -emit-ir %s | %FileCheck %s --check-prefix=STRIP_REFLECTION_METADATA // STRIP_REFLECTION_NAMES_DAG: {{.*}}swift5_reflect // STRIP_REFLECTION_NAMES_DAG: {{.*}}swift5_fieldmd // STRIP_REFLECTION_NAMES_DAG: {{.*}}swift5_assocty // STRIP_REFLECTION_NAMES-DAG: {{.*}}swift5_capture // STRIP_REFLECTION_NAMES-DAG: {{.*}}swift5_typeref // STRIP_REFLECTION_NAMES-NOT: {{.*}}swift5_reflstr // STRIP_REFLECTION_NAMES-NOT: {{.*}}swift5_builtin // STRIP_REFLECTION_NAMES-DAG: @"$S19reflection_metadata10MyProtocol_pMF" = internal constant {{.*}}swift5_fieldmd // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_reflect // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_fieldmd // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_assocty // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_capture // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_typeref // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_reflstr // STRIP_REFLECTION_METADATA-NOT: {{.*}}swift5_builtin // CHECK-DAG: @__swift_reflection_version = linkonce_odr hidden constant i16 {{[0-9]+}} // CHECK-DAG: private constant [2 x i8] c"i\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"ms\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"me\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"mc\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [2 x i8] c"C\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [2 x i8] c"S\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [2 x i8] c"E\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [2 x i8] c"I\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [2 x i8] c"t\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [4 x i8] c"mgs\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [4 x i8] c"mge\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [4 x i8] c"mgc\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"GC\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"GS\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: private constant [3 x i8] c"GE\00", section "{{[^"]*}}swift5_reflstr{{[^"]*}}" // CHECK-DAG: @"\01l__swift5_reflection_descriptor" = private constant { {{.*}} } { i32 1, i32 1, i32 2, {{.*}} } // CHECK-DAG: @"$S19reflection_metadata10MyProtocol_pMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata7MyClassCMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata11ConformanceVAA10MyProtocolAAMA" = internal constant {{.*}}swift5_assocty // CHECK-DAG: @"$S19reflection_metadata8MyStructVMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata6MyEnumOMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata14MyGenericClassCMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata15MyGenericStructVMF" = internal constant {{.*}}swift5_fieldmd // CHECK-DAG: @"$S19reflection_metadata13MyGenericEnumOMF" = internal constant {{.*}}swift5_fieldmd public protocol MyProtocol { associatedtype Inner var inner: Inner { get } } public class MyClass { let i: Int let ms: MyStruct let me: MyEnum public init(i: Int, ms: MyStruct, me: MyEnum) { self.i = i self.ms = ms self.me = me } } public struct Conformance : MyProtocol { public var inner: Int = 0 } public struct MyStruct { let i: Int let mc: MyClass let me: MyEnum } public enum MyEnum { case C(MyClass) indirect case S(MyStruct) indirect case E(MyEnum) case I(Int) } public class MyGenericClass<T : MyProtocol> { let t: T let i: T.Inner let mgs: MyGenericStruct<T> let mge: MyGenericEnum<T> public init(t: T, i: T.Inner, mgs: MyGenericStruct<T>, mge: MyGenericEnum<T>) { self.t = t self.i = i self.mgs = mgs self.mge = mge } } public struct MyGenericStruct<T : MyProtocol> { let t: T let i: T.Inner let mgc: MyGenericClass<T> let mge: MyGenericEnum<T> } public enum MyGenericEnum<T : MyProtocol> { case GC(MyGenericClass<T>) indirect case GS(MyGenericStruct<T>) indirect case GE(MyGenericEnum<T>) case I(Int) } public func makeSomeClosures<T : MyProtocol>(t: T) -> (() -> ()) { return { _ = t } }
apache-2.0
d6e7d008bbe551c28d2ee5d91ed54607
41.929825
170
0.6604
3.204977
false
false
false
false
lucaslimapoa/NewsAPISwift
Example/Source/ListSourcesViewController.swift
1
2456
// // ListSourcesViewController.swift // NewsAPISwift // // Created by lucas lima on 6/3/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import NewsAPISwift class ListSourcesViewController: UITableViewController { let newsAPI = NewsAPI(apiKey: "f9fa20fea27f44b79b2c779acdef4421") var sources = [NewsSource]() { didSet { DispatchQueue.main.async { self.tableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() title = "NewsAPISwift" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) newsAPI.getSources { result in switch result { case .success(let sourceList): self.sources = sourceList case .failure(let error): fatalError("\(error)") } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.destination is ListArticlesViewController { let articlesViewController = segue.destination as! ListArticlesViewController articlesViewController.newsAPI = newsAPI articlesViewController.source = sources[tableView.indexPathForSelectedRow!.row] } } // override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let articlesViewController = UIStoryboard(name: "Main", bundle: nil) // .instantiateViewController(withIdentifier: "ListArticlesViewController") as! ListArticlesViewController // // articlesViewController.newsAPI = newsAPI // articlesViewController.source = sources[indexPath.row] // // navigationController?.pushViewController(articlesViewController, animated: true) // } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sources.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "SourceCell", for: indexPath) cell.textLabel?.text = sources[indexPath.row].name return cell } }
mit
8bc4ed5d1ff43814d89072337b53d38b
30.883117
117
0.64277
5.041068
false
false
false
false
verticon/MecklenburgTrailOfHistory
Trail of History/Detail View/DetailView.swift
1
20197
// // DetailViewController.swift // Trail of History // // Created by Robert Vaessen on 12/30/16. // Copyright © 2018 Robert Vaessen. All rights reserved. // import AVFoundation import UIKit import AVKit import WebKit import SafariServices import VerticonsToolbox private class PresentingAnimator : NSObject, UIViewControllerAnimatedTransitioning { private let initiatingFrame: CGRect // The frame of the element that was tapped to initiate the Detail View presentation private let imageFrame: CGRect // The final size of the Detail View's image view subview. private let image: UIImage private var toViewController: UIViewController! init(initiatingFrame: CGRect, imageFrame: CGRect, image: UIImage) { self.initiatingFrame = initiatingFrame self.imageFrame = imageFrame self.image = image super.init() } func transitionDuration(using: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.5 } func animateTransition(using context: UIViewControllerContextTransitioning) { self.toViewController = context.viewController(forKey: UITransitionContextViewControllerKey.to)! let finalFrame = context.finalFrame(for: self.toViewController) // Start by displaying the image, completely transparent, in the initiating frame. The image will fill the frame // and its aspect ratio will be preserved. UIImageView's default behavior is to center the image. A UIScrollView // is used so as to display the upper left portion, hopefully all of the width (i.e. the statue's upper torso). let imageView = UIImageView(image: image) imageView.contentMode = .scaleAspectFill let size = image.aspectFill(in: initiatingFrame.size) imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) let scrollView = UIScrollView(frame: initiatingFrame) scrollView.backgroundColor = .orange // A visual clue that things are misalighend, i.e. we should see no orange scrollView.addSubview(imageView) scrollView.alpha = 0 // The scroll view will end up on top of the detail view so we need to be able to tap it as well scrollView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss(_:)))) context.containerView.addSubview(scrollView) let animations = { // Turn the image opaque and then move/resize it from the initiating frame to the final frame of the Detail View's image subview. UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/2) { scrollView.alpha = 1 } UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2) { scrollView.frame = self.imageFrame let size = self.image.aspectFill(in: self.imageFrame.size) imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) } } UIView.animateKeyframes(withDuration: transitionDuration(using: context) * 2 / 3, delay: 0, animations: animations) { _ in // Reduce the Detail View's height so that only its image view subview is showing. The detail view's frame should // then exactly match the frame of the ScrollView/ImageView that was presented by the first part of the anumation. self.toViewController.view.clipsToBounds = true let frame = self.toViewController.view.frame self.toViewController.view.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: self.imageFrame.size.height) context.containerView.addSubview(self.toViewController.view) // Expand the Detail View's size to reveal its text subview. UIView.animate(withDuration: self.transitionDuration(using: context) / 3, delay: 0, animations: { self.toViewController.view.frame = finalFrame }) { _ in context.completeTransition(!context.transitionWasCancelled) } } } @objc func dismiss(_ gestureRecognizer: UITapGestureRecognizer) { toViewController.dismiss(animated: true, completion: nil) } } private class DismissingAnimator : NSObject, UIViewControllerAnimatedTransitioning { private let initiatingFrame: CGRect private let imageFrame: CGRect init(initiatingFrame: CGRect, imageFrame: CGRect) { self.initiatingFrame = initiatingFrame self.imageFrame = imageFrame super.init() } func transitionDuration(using: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.5 } func animateTransition(using context: UIViewControllerContextTransitioning) { let fromViewController = context.viewController(forKey: UITransitionContextViewControllerKey.from)! let frame = fromViewController.view.frame let imageFrame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: self.imageFrame.origin.y + self.imageFrame.size.height) // Begin by rolling up the text view until only the image shows UIView.animate(withDuration: transitionDuration(using: context) / 3, animations: { fromViewController.view.frame = imageFrame }) { _ in // Remove the remainder (the image) of the detail view, thus revealing the scroll view that was created be the presenting animator fromViewController.view.removeFromSuperview() let scrollView = context.containerView.subviews[0] as! UIScrollView let imageView = scrollView.subviews[0] as! UIImageView let animations = { // Now move the scroll view back to the initiating frame. UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/2) { scrollView.frame = self.initiatingFrame let size = imageView.image!.aspectFill(in: self.initiatingFrame.size) imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) } // Finally fade the scroll view to transparent so as to reveal the initiating frame. UIView.addKeyframe(withRelativeStartTime: 1/2, relativeDuration: 1/2) { scrollView.alpha = 0 } } UIView.animateKeyframes(withDuration: self.transitionDuration(using: context) * 2 / 3, delay: 0, animations: animations) { _ in context.completeTransition(!context.transitionWasCancelled) } } } } private class TransitionController : NSObject, UIViewControllerTransitioningDelegate { private let initiatingFrame: CGRect private let image: UIImage private let targetController: DetailViewController private let presentingAnimator: UIViewControllerAnimatedTransitioning private let dismissingAnimator: UIViewControllerAnimatedTransitioning init(targetController: DetailViewController, initiatingFrame: CGRect, imageFrame: CGRect, image: UIImage) { self.targetController = targetController self.initiatingFrame = initiatingFrame self.image = image self.presentingAnimator = PresentingAnimator(initiatingFrame: initiatingFrame, imageFrame: imageFrame, image: image) self.dismissingAnimator = DismissingAnimator(initiatingFrame: initiatingFrame, imageFrame: imageFrame) super.init() } private var setupNeeded = true func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { // At this point we can be sure that the target controller's view (the detail view) has been set and thus that we can add a gesture recognizer to it. // If we were to perform this setup in the init method then we would impose a condition upon the sequence of steps in the static present method. if setupNeeded { setupNeeded = false targetController.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapHandler(_:)))) } return presentingAnimator } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return dismissingAnimator } @objc func tapHandler(_ gestureRecognizer: UITapGestureRecognizer) { targetController.dismiss(animated: true, completion: nil) } } private class DetailViewController : UIViewController { var transitionController: TransitionController! { // Store a strong reference (since controller.transitioningDelegate is weak) didSet { transitioningDelegate = transitionController } } var detailView: DetailView! // Store a strong reference (since controller.transitioningDelegate is weak) } /* 1) The image view mode will be aspect fill. 2) The image view width will be set equal to the detail view's width and the height will be set so as to maintain the aspect ratio. 3) The image view will be contained by a scroll view whose size will be equal the image view's size but with the restriction that the height may not exceed 1/2 of the detail view's height 4) Thus we will see all of the image's width and some or all of the image's height */ class DetailView : UIView, AVPlayerViewControllerDelegate { static func present(poi: PointOfInterest, startingFrom: CGRect) { let window = UIApplication.shared.delegate!.window!! let presenter = window.visibleViewController! let barHeight = presenter.navigationController?.navigationBar.frame.maxY ?? UIApplication.shared.statusBarFrame.height let controller = DetailViewController() //controller.view.backgroundColor = UIColor(white: 1, alpha: 0.5) // Allow the underlying view to be seen through a white haze. let detailView = DetailView(poi: poi, controller: controller, barHeight: barHeight) controller.detailView = detailView controller.transitionController = TransitionController(targetController: controller, initiatingFrame: startingFrom.offsetBy(dx: 0, dy: barHeight), imageFrame: detailView.imageViewFrame(), image: poi.image) controller.modalPresentationStyle = .custom presenter.present(controller, animated: true, completion: nil) } private static let inset: CGFloat = 16 private static func detailViewFrame(barHeight: CGFloat) -> CGRect { let size = UIScreen.main.bounds.size let frame = CGRect(x: 0, y: barHeight, width: size.width, height: size.height - barHeight) return frame.insetBy(dx: DetailView.inset, dy: DetailView.inset) } private let poiName : String fileprivate let statueImageView = UIImageView() fileprivate let imageScrollView = UIScrollView() private let movieButton = UIButton() private let nameLabel = UILabel() private let descriptionTextView = UITextView() private let learnMoreUrl: URL? private let learnMoreButton = UIButton() private var listenerToken: PointOfInterest.ListenerToken! private let movieUrl: URL? private let barHeight: CGFloat private let controller: UIViewController private let scrollViewHeightConstraint: NSLayoutConstraint private init(poi: PointOfInterest, controller: UIViewController, barHeight: CGFloat) { self.controller = controller self.barHeight = barHeight poiName = poi.name movieUrl = poi.movieUrl learnMoreUrl = poi.meckncGovUrl scrollViewHeightConstraint = imageScrollView.heightAnchor.constraint(equalToConstant: 0) super.init(frame: DetailView.detailViewFrame(barHeight: barHeight)) self.borderWidth = 1 self.cornerRadius = 4 self.borderColor = .tohTerracotaColor self.backgroundColor = .tohGreyishBrownTwoColor self.translatesAutoresizingMaskIntoConstraints = false controller.view.addSubview(self) update(using: poi) let size = imageViewSize() statueImageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) statueImageView.contentMode = .scaleAspectFill imageScrollView.addSubview(statueImageView) imageScrollView.translatesAutoresizingMaskIntoConstraints = false addSubview(imageScrollView) nameLabel.textAlignment = .center nameLabel.font = UIFont(name: "HoeflerText-Black", size: 18)! nameLabel.font = descriptionTextView.font?.withSize(18) // Why is this line necessary? The size parameter to UIFont's initializer has no effect. nameLabel.textColor = .tohTerracotaColor nameLabel.backgroundColor = .tohGreyishBrownTwoColor nameLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(nameLabel) descriptionTextView.textAlignment = .justified descriptionTextView.isEditable = false descriptionTextView.isSelectable = false descriptionTextView.font = UIFont(name: "HoeflerText-Regular", size: 18)! descriptionTextView.font = descriptionTextView.font?.withSize(18) // Why is this line necessary? The size parameter to UIFont's initializer has no effect. descriptionTextView.textColor = .white descriptionTextView.backgroundColor = .tohGreyishBrownTwoColor descriptionTextView.translatesAutoresizingMaskIntoConstraints = false addSubview(descriptionTextView) if movieUrl != nil { movieButton.setImage(#imageLiteral(resourceName: "PlayMovieButton"), for: .normal) movieButton.addTarget(self, action: #selector(playMovie), for: .touchUpInside) } else { movieButton.isHidden = true } movieButton.translatesAutoresizingMaskIntoConstraints = false addSubview(movieButton) if learnMoreUrl != nil { learnMoreButton.setTitle("Learn more ...", for: .normal) } else { learnMoreButton.isHidden = true } learnMoreButton.translatesAutoresizingMaskIntoConstraints = false learnMoreButton.addTarget(self, action: #selector(learnMore(_:)), for: .touchUpInside) learnMoreButton.setTitleColor(.tohTerracotaColor, for: .normal) learnMoreButton.backgroundColor = .tohGreyishBrownTwoColor addSubview(learnMoreButton) NSLayoutConstraint.activate([ // TODO: Understand why it is necessary to contrain the detail view itself (the first 4 constraints) self.topAnchor.constraint(equalTo: controller.view.topAnchor, constant: barHeight + DetailView.inset), self.centerXAnchor.constraint(equalTo: controller.view.centerXAnchor), self.widthAnchor.constraint(equalToConstant: frame.width), self.heightAnchor.constraint(equalToConstant: frame.height), imageScrollView.topAnchor.constraint(equalTo: self.topAnchor), imageScrollView.leftAnchor.constraint(equalTo: self.leftAnchor), imageScrollView.rightAnchor.constraint(equalTo: self.rightAnchor), scrollViewHeightConstraint, learnMoreButton.centerXAnchor.constraint(equalTo: self.centerXAnchor), learnMoreButton.bottomAnchor.constraint(equalTo: self.bottomAnchor), nameLabel.topAnchor.constraint(equalTo: imageScrollView.bottomAnchor, constant: 4), nameLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor), descriptionTextView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 4), descriptionTextView.bottomAnchor.constraint(equalTo: learnMoreButton.topAnchor), descriptionTextView.centerXAnchor.constraint(equalTo: self.centerXAnchor), descriptionTextView.widthAnchor.constraint(equalTo: imageScrollView.widthAnchor), movieButton.rightAnchor.constraint(equalTo: imageScrollView.rightAnchor, constant: -8), movieButton.bottomAnchor.constraint(equalTo: imageScrollView.bottomAnchor, constant: -8), movieButton.widthAnchor.constraint(equalToConstant: 32), movieButton.heightAnchor.constraint(equalToConstant: 32), ]) listenerToken = PointOfInterest.addListener(poiListener) } required public init?(coder aDecoder: NSCoder) { fatalError("Init with coder not implemented") } deinit { _ = PointOfInterest.removeListener(token: listenerToken) } @objc func learnMore(_ sender: UIButton) { if let link = learnMoreUrl { UIApplication.shared.open(link) } } func poiListener(event: Firebase.Observer.Event, key: Firebase.Observer.Key, poi: PointOfInterest) { if poi.name == poiName { switch event { case .updated: update(using: poi) self.setNeedsDisplay() case .removed: controller.dismiss(animated: false, completion: nil) default: break } } } public override func layoutSubviews() { let height = imageViewSize().height let limit = DetailView.detailViewFrame(barHeight: barHeight).size.height / 2 scrollViewHeightConstraint.constant = height > limit ? limit : height super.layoutSubviews() let lineHeight = descriptionTextView.font!.lineHeight let totalHeight = descriptionTextView.bounds.height let remainder = totalHeight.truncatingRemainder(dividingBy: lineHeight) descriptionTextView.contentInset.top = lineHeight descriptionTextView.setContentOffset(CGPoint(x: 0, y: -remainder/2), animated: false) } private func update(using poi: PointOfInterest) { // AFAIK If no other action is taken then the image view will size itself to the image, even if this results in a size larger than the window. statueImageView.image = poi.image nameLabel.text = poi.name /* let justified = NSMutableParagraphStyle() justified.alignment = NSTextAlignment.justified let text = NSMutableAttributedString(string: "\(poi.name)\n\n\(poi.description)\n", attributes: [ NSAttributedStringKey.font : UIFont(name: "HoeflerText-Regular", size: 18)!, NSAttributedStringKey.paragraphStyle : justified, NSAttributedStringKey.foregroundColor : UIColor.white ]) let centered = NSMutableParagraphStyle() centered.alignment = NSTextAlignment.center text.addAttributes([ NSAttributedStringKey.font : UIFont(name: "HoeflerText-Black", size: 18)!, NSAttributedStringKey.paragraphStyle : centered, NSAttributedStringKey.foregroundColor : UIColor.tohTerracotaColor ], range: NSRange(location: 0, length: poi.name.count)) descriptionTextView.attributedText = text */ descriptionTextView.text = poi.description } @objc private func playMovie() { let player = AVPlayer(url: movieUrl!) let playerViewController = AVPlayerViewController() playerViewController.player = player controller.present(playerViewController, animated: true) { playerViewController.player!.play() } } func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error) { print("There was a playback error: \(error)") } func imageViewSize() -> CGSize { let imageSize = statueImageView.image!.size let imageViewWidth = DetailView.detailViewFrame(barHeight: barHeight).width let imageViewHeight = (imageSize.height / imageSize.width) * imageViewWidth return CGSize(width: imageViewWidth, height: imageViewHeight) } func imageViewFrame() -> CGRect { let frame = DetailView.detailViewFrame(barHeight: barHeight) let size = imageViewSize() return CGRect(x: frame.origin.x, y: frame.origin.y, width: size.width, height: size.height) } }
mit
f6197b6ff7ea4307cd52bd9cb813be08
46.85782
213
0.699
5.347101
false
false
false
false
weissmar/CharacterSheet
iOS_Files/characterSheet/AppDelegate.swift
1
6356
// // AppDelegate.swift // characterSheet // // Created by Rachel Weissman-Hohler on 8/11/16. // Copyright © 2016 Rachel Weissman-Hohler. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Initialize sign-in (from https://developers.google.com/identity/sign-in/ios/sign-in?ver=swift ) var configureError: NSError? GGLContext.sharedInstance().configureWithError(&configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") GIDSignIn.sharedInstance().delegate = self return true } func application(application: UIApplication, openURL url: NSURL, options: [String: AnyObject]) -> Bool { return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String, annotation: options[UIApplicationOpenURLOptionsAnnotationKey]) } // MARK: API Post Call func postTokenToAPI(token: String, complete: (success: Bool, party: String?) -> ()) { let tokenString = "Bearer " + token let myURL = "https://abstract-key-135222.appspot.com/sign-in" let request = NSMutableURLRequest(URL: NSURL(string: myURL)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue(tokenString, forHTTPHeaderField: "Authorization") let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in //************************************************************************* print(NSString(data: data!, encoding: NSUTF8StringEncoding)!) print(String(response)) print(String(error)) print("_____") //************************************************************************* do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as? NSDictionary if let parsedData = json { if let partyID = parsedData["party"] as? String { complete(success: true, party: partyID) } } else { complete(success: false, party: nil) } } catch { print(error) print("Error: couldn't parse json:") let stringData = String(response) print(stringData) complete(success: false, party: nil) } }) task.resume() } func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) { if (error == nil) { // Perform any operations on signed in user here. let idToken = user.authentication.idToken // send token to back-end to validate and get user's character info postTokenToAPI(idToken) { (success: Bool, party: String?) -> () in if success { let rootViewController = self.window!.rootViewController as? ViewController rootViewController?.userToken = idToken if !(party?.isEmpty)! { // get party info and display party page rootViewController?.partyID = party rootViewController?.performSegueWithIdentifier("existingPartySegue", sender: self) } else { // show create new party page rootViewController?.partyID = nil rootViewController?.performSegueWithIdentifier("newPartySegue", sender: self) } } else { // redirect back to sign-in page GIDSignIn.sharedInstance().signOut() } } } else { print("\(error.localizedDescription)") } } func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!, withError error: NSError!) { // Perform any operations when the user disconnects from app here. // ************************************************************************************** } 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
93ce9811c4b9a3f8b960b6adaaae830c
48.263566
285
0.613375
5.73556
false
false
false
false
naoyashiga/Dunk
DribbbleReader/BaseViewController.swift
1
3919
// // BaseViewController.swift // DribbbleReader // // Created by naoyashiga on 2015/05/22. // Copyright (c) 2015年 naoyashiga. All rights reserved. // import UIKit class BaseViewController: UIViewController { var pageMenu : CAPSPageMenu? override func viewDidLoad() { super.viewDidLoad() var controllerArray : [UIViewController] = [] self.navigationItem.title = "Dunk" self.navigationController?.isNavigationBarHidden = false self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.navigationBarTitleTextColor()] self.navigationController?.navigationBar.barTintColor = UIColor.navigationBarBackgroundColor() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = false let popularShot = ShotCollectionViewController(nibName: "ShotCollectionViewController", bundle: nil) popularShot.title = "Popular" popularShot.API_URL = Config.POPULAR_URL popularShot.loadShots() controllerArray.append(popularShot) let gifShot = ShotCollectionViewController(nibName: "ShotCollectionViewController", bundle: nil) gifShot.title = "GIFs" gifShot.API_URL = Config.GIF_URL gifShot.loadShots() controllerArray.append(gifShot) let teamsShot = ShotCollectionViewController(nibName: "ShotCollectionViewController", bundle: nil) teamsShot.title = "Teams" teamsShot.API_URL = Config.TEAMS_URL teamsShot.loadShots() controllerArray.append(teamsShot) let reboundsShot = ShotCollectionViewController(nibName: "ShotCollectionViewController", bundle: nil) reboundsShot.title = "Rebounds" reboundsShot.API_URL = Config.REBOUNDS_URL reboundsShot.loadShots() controllerArray.append(reboundsShot) let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor.scrollMenuBackgroundColor()), .viewBackgroundColor(UIColor.viewBackgroundColor()), .selectionIndicatorColor(UIColor.selectionIndicatorColor()), .bottomMenuHairlineColor(UIColor.bottomMenuHairlineColor()), .selectedMenuItemLabelColor(UIColor.selectedMenuItemLabelColor()), .unselectedMenuItemLabelColor(UIColor.unselectedMenuItemLabelColor()), .selectionIndicatorHeight(2.0), .menuItemFont(UIFont(name: "HiraKakuProN-W6", size: 13.0)!), .menuHeight(34.0), .menuItemWidth(80.0), .menuMargin(0.0), // "useMenuLikeSegmentedControl": true, .menuItemSeparatorRoundEdges(true), // "enableHorizontalBounce": true, // "scrollAnimationDurationOnMenuItemTap": 300, .centerMenuItems(true)] pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height), pageMenuOptions: parameters) self.view.addSubview(pageMenu!.view) self.addChildViewController(pageMenu!) pageMenu?.didMove(toParentViewController: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
a140abf59c0b51ae6f83f3d505c941a6
42.043956
187
0.678581
5.387895
false
false
false
false
mzaks/FlexBuffersSwift
FlexBuffersTests/FlexBufferRoundtripTest.swift
1
11121
// // FlexBufferRoundtripTest.swift // FlexBuffers // // Created by Maxim Zaks on 14.01.17. // Copyright © 2017 Maxim Zaks. All rights reserved. // import XCTest import FlexBuffers class FlexBufferRoundtripTest: XCTestCase { func test1() { // {vec:[-100,"Fred",4.0],bar:[1,2,3],bar3:[1,2,3]foo:100,mymap{foo:"Fred"}} let flx = FlexBuffer() try!flx.addMap { try!flx.addVector(key: "vec") { flx.add(value: -100) flx.add(value: "Fred") flx.add(value:4.0) } try!flx.add(key: "bar", value: [1, 2, 3]) try!flx.addVector(key: "bar3") { flx.add(value:1) flx.add(value:2) flx.add(value:3) } flx.add(key: "foo", value: 100) try!flx.addMap(key: "mymap") { flx.add(key: "foo", value: "Fred") } } let data = try!flx.finish() let v = FlexBuffer.decode(data: data)!.asMap! print(v.debugDescription) print("{vec:[-100,\"Fred\",4.0],bar:[1,2,3],bar3:[1,2,3]foo:100,mymap{foo:\"Fred\"}}".count) XCTAssertEqual(v.count, 5) XCTAssertEqual(v["vec"]?.asVector?[0]?.asInt, -100) XCTAssertEqual(v["vec"]?.asVector?[1]?.count, 4) XCTAssertEqual(v["vec"]?.asVector?[1]?.asString, "Fred") XCTAssertEqual(v["vec"]?.asVector?[2]?.asDouble, 4) XCTAssertEqual(v["bar"]?.asVector?[0]?.asInt, 1) XCTAssertEqual(v["bar"]?.asVector?[1]?.asInt, 2) XCTAssertEqual(v["bar"]?.asVector?[2]?.asInt, 3) XCTAssertEqual(v["bar3"]?.asVector?[0]?.asInt, 1) XCTAssertEqual(v["bar3"]?.asVector?[1]?.asInt, 2) XCTAssertEqual(v["bar3"]?.asVector?[2]?.asInt, 3) XCTAssertEqual(v["mymap"]?.asMap?.count, 1) XCTAssertEqual(v["mymap"]?.asMap?["foo"]?.count, 4) XCTAssertEqual(v["mymap"]?.asMap?["foo"]?.asString, "Fred") XCTAssertEqual(v["foo"]?.asInt, 100) } func test2(){ let flx = FlexBuffer() try!flx.addMap { flx.add(key: "age", value: 35) try!flx.add(key: "flags", value: [true, false, true, true]) flx.add(key: "weight", value: 72.5) try!flx.addMap(key: "address"){ flx.add(key: "city", value: "Bla") flx.add(key: "zip", value: "12345") flx.add(key: "countryCode", value: "XX") } } let data = try!flx.finish() let v = FlexBuffer.decode(data: data)!.asMap! XCTAssertEqual(v.count, 4) XCTAssertEqual(v["age"]?.asInt, 35) XCTAssertEqual(v["flags"]?.count, 4) XCTAssertEqual(v["flags"]?.asVector?[0]?.asBool, true) XCTAssertEqual(v["flags"]?.asVector?[1]?.asBool, false) XCTAssertEqual(v["flags"]?.asVector?[2]?.asBool, true) XCTAssertEqual(v["flags"]?.asVector?[3]?.asBool, true) XCTAssertEqual(v["weight"]?.asFloat, 72.5) XCTAssertEqual(v["address"]?.count, 3) XCTAssertEqual(v["address"]?.asMap?["city"]?.asString, "Bla") XCTAssertEqual(v["address"]?.asMap?["zip"]?.asString, "12345") XCTAssertEqual(v["address"]?.asMap?["countryCode"]?.asString, "XX") } func testTuples(){ let flx = FlexBuffer() try!flx.addMap { try!flx.add(key: "a", value: (1, 2)) try!flx.add(key: "b", value: (1.0, 2.5)) try!flx.add(key: "c", value: (UInt(1), 2)) try!flx.add(key: "d", value: (1, 2, 3)) try!flx.add(key: "e", value: (1.0, 2.5, 4.0)) try!flx.add(key: "f", value: (UInt(1), 2, 3)) try!flx.add(key: "g", value: (1, 2, 3, 4)) try!flx.add(key: "h", value: (1.0, 2.5, 4.0, 5.5)) try!flx.add(key: "i", value: (UInt(1), 2, 3, 4)) } let data = try!flx.finish() let v = FlexBuffer.decode(data: data)!.asMap! XCTAssertEqual(v.count, 9) XCTAssertEqual(v["a"]?.asTuppleInt?.0, 1) XCTAssertEqual(v["a"]?.asTuppleInt?.1, 2) XCTAssertEqual(v["b"]?.asTuppleDouble?.0, 1.0) XCTAssertEqual(v["b"]?.asTuppleDouble?.1, 2.5) XCTAssertEqual(v["c"]?.asTuppleUInt?.0, 1) XCTAssertEqual(v["c"]?.asTuppleUInt?.1, 2) XCTAssertEqual(v["d"]?.asTripleInt?.0, 1) XCTAssertEqual(v["d"]?.asTripleInt?.1, 2) XCTAssertEqual(v["d"]?.asTripleInt?.2, 3) XCTAssertEqual(v["e"]?.asTripleDouble?.0, 1) XCTAssertEqual(v["e"]?.asTripleDouble?.1, 2.5) XCTAssertEqual(v["e"]?.asTripleDouble?.2, 4) XCTAssertEqual(v["f"]?.asTripleUInt?.0, 1) XCTAssertEqual(v["f"]?.asTripleUInt?.1, 2) XCTAssertEqual(v["f"]?.asTripleUInt?.2, 3) XCTAssertEqual(v["g"]?.asQuadrupleInt?.0, 1) XCTAssertEqual(v["g"]?.asQuadrupleInt?.1, 2) XCTAssertEqual(v["g"]?.asQuadrupleInt?.2, 3) XCTAssertEqual(v["g"]?.asQuadrupleInt?.3, 4) XCTAssertEqual(v["h"]?.asQuadrupleDouble?.0, 1) XCTAssertEqual(v["h"]?.asQuadrupleDouble?.1, 2.5) XCTAssertEqual(v["h"]?.asQuadrupleDouble?.2, 4) XCTAssertEqual(v["h"]?.asQuadrupleDouble?.3, 5.5) XCTAssertEqual(v["i"]?.asQuadrupleUInt?.0, 1) XCTAssertEqual(v["i"]?.asQuadrupleUInt?.1, 2) XCTAssertEqual(v["i"]?.asQuadrupleUInt?.2, 3) XCTAssertEqual(v["i"]?.asQuadrupleUInt?.3, 4) XCTAssertEqual(v["a"]?.asTripleInt?.0, nil) XCTAssertEqual(v["a"]?.asQuadrupleInt?.0, nil) } func testTransformVectorToArray(){ let flx = FlexBuffer() try?flx.add(array: [true, true , false, true]) let data = try!flx.finish() let v = FlexBuffer.decode(data: data)!.asVector! let array = v.makeIterator().compactMap{$0.asBool} XCTAssertEqual(array, [true, true , false, true]) } func testStringWithSpecialCharacter() { let flx = FlexBuffer() flx.add(value: "hello \t \" there / \n\r") let flxData = try!flx.finish() let flx1 = FlexBuffer.decode(data: flxData) XCTAssertEqual(flx1?.debugDescription, "\"hello \\t \\\" there / \\n\\r\"") XCTAssertEqual(flx1?.jsonString, "\"hello \\t \\\" there \\/ \\n\\r\"") print(flx1!.debugDescription) } func testToDictMethod() { let flx = FlexBuffer() try? flx.addMap { flx.add(key: "bla", value: true) } let flxData = try?flx.finish() let flx1 = FlexBuffer.decode(data: flxData!) let dict = flx1?.asMap?.toDict{ return $0.asBool } XCTAssertEqual(["bla": true], dict!) } func testFlxbValues() { let object = [ "i": 25, "b": true, "s": "Hello", "ss": "My name is" as StaticString, "d": 2.5, "u": 45 as UInt, "bs": [true, false , true] as FlxbValueVector, "bss": [1, 3.4, "abc", FlxbValueNil(), 45] as FlxbValueVector, "o": ["a": 12] as FlxbValueMap, "vo" : [ ["a": 1]as FlxbValueMap, [1, 2, 3] as FlxbValueVector] as FlxbValueVector ] as FlxbValueMap let data = try!FlexBuffer.encode(object) XCTAssertEqual(data.root?.count, 10) XCTAssertEqual(data.root?["i"]?.asInt, 25) XCTAssertEqual(data.root?["b"]?.asBool, true) XCTAssertEqual(data.root?["s"]?.asString, "Hello") XCTAssertEqual(data.root?["ss"]?.asString, "My name is") XCTAssertEqual(data.root?["d"]?.asDouble, 2.5) XCTAssertEqual(data.root?["u"]?.asUInt, 45) XCTAssertEqual(data.root?["bs"]?.count, 3) XCTAssertEqual(data.root?["bs"]?[0]?.asBool, true) XCTAssertEqual(data.root?["bs"]?[1]?.asBool, false) XCTAssertEqual(data.root?["bs"]?[2]?.asBool, true) XCTAssertEqual(data.root?["bss"]?.asVector?.count, 5) XCTAssertEqual(data.root?["bss"]?[0]?.asInt, 1) XCTAssertEqual(data.root?["bss"]?[1]?.asDouble, 3.4) XCTAssertEqual(data.root?["bss"]?[2]?.asString, "abc") XCTAssertEqual(data.root?["bss"]?[3]?.isNull, true) XCTAssertEqual(data.root?["bss"]?[4]?.asInt, 45) XCTAssertEqual(data.root?["o"]?.count, 1) XCTAssertEqual(data.root?["o"]?["a"]?.asInt, 12) XCTAssertEqual(data.root?["vo"]?.count, 2) XCTAssertEqual(data.root?["vo"]?[0]?.count, 1) XCTAssertEqual(data.root?["vo"]?[0]?["a"]?.asInt, 1) XCTAssertEqual(data.root?["vo"]?[1]?.count, 3) XCTAssertEqual(data.root?["vo"]?[1]?[0]?.asInt, 1) XCTAssertEqual(data.root?["vo"]?[1]?[1]?.asInt, 2) XCTAssertEqual(data.root?["vo"]?[1]?[2]?.asInt, 3) } func testFlxbValuesAccessThroughString() { let object = [ "i": 25, "b": true, "s": "Hello", "ss": "My name is" as StaticString, "d": 2.5, "u": 45 as UInt, "bs": [true, false , true] as FlxbValueVector, "bss": [1, 3.4, "abc", FlxbValueNil(), 45] as FlxbValueVector, "o": ["a": 12] as FlxbValueMap, "vo" : [ ["a": 1]as FlxbValueMap, [1, 2, 3] as FlxbValueVector] as FlxbValueVector ] as FlxbValueMap let data = try!FlexBuffer.encode(object) XCTAssertEqual(data.root?.count, 10) XCTAssertEqual(data.root?.get(key: "i")?.asInt, 25) XCTAssertEqual(data.root?.get(key: "b")?.asBool, true) XCTAssertEqual(data.root?.get(key: "s")?.asString, "Hello") XCTAssertEqual(data.root?.get(key: "ss")?.asString, "My name is") XCTAssertEqual(data.root?.get(key: "d")?.asDouble, 2.5) XCTAssertEqual(data.root?.get(key: "u")?.asUInt, 45) XCTAssertEqual(data.root?.get(key: "bs")?.count, 3) XCTAssertEqual(data.root?.get(key: "bs")?[0]?.asBool, true) XCTAssertEqual(data.root?.get(key: "bs")?[1]?.asBool, false) XCTAssertEqual(data.root?.get(key: "bs")?[2]?.asBool, true) XCTAssertEqual(data.root?.get(key: "bss")?.asVector?.count, 5) XCTAssertEqual(data.root?.get(key: "bss")?[0]?.asInt, 1) XCTAssertEqual(data.root?.get(key: "bss")?[1]?.asDouble, 3.4) XCTAssertEqual(data.root?.get(key: "bss")?[2]?.asString, "abc") XCTAssertEqual(data.root?.get(key: "bss")?[3]?.isNull, true) XCTAssertEqual(data.root?.get(key: "bss")?[4]?.asInt, 45) XCTAssertEqual(data.root?.get(key: "o")?.count, 1) XCTAssertEqual(data.root?.get(key: "o")?["a"]?.asInt, 12) XCTAssertEqual(data.root?.get(key: "vo")?.count, 2) XCTAssertEqual(data.root?.get(key: "vo")?[0]?.count, 1) XCTAssertEqual(data.root?.get(key: "vo")?[0]?["a"]?.asInt, 1) XCTAssertEqual(data.root?.get(key: "vo")?[1]?.count, 3) XCTAssertEqual(data.root?.get(key: "vo")?[1]?[0]?.asInt, 1) XCTAssertEqual(data.root?.get(key: "vo")?[1]?[1]?.asInt, 2) XCTAssertEqual(data.root?.get(key: "vo")?[1]?[2]?.asInt, 3) } }
mit
d8ad9c75db000618795cce52b08c628f
42.607843
100
0.546133
3.429981
false
false
false
false
machelix/Swift-SpriteKit-Analog-Stick
AnalogStick Demo/AnalogStick Demo/GameScene.swift
1
8554
// // GameScene.swift // stick test // // Created by Dmitriy Mitrophanskiy on 28.09.14. // Copyright (c) 2014 Dmitriy Mitrophanskiy. All rights reserved. // import SpriteKit let kAnalogStickdiameter: CGFloat = 110 class GameScene: SKScene { var appleNode: SKSpriteNode? let jSizePlusSpriteNode = SKSpriteNode(imageNamed: "plus"), jSizeMinusSpriteNode = SKSpriteNode(imageNamed: "minus") let setJoystickStickImageBtn = SKLabelNode() let setJoystickSubstrateImageBtn = SKLabelNode() let joystickStickColorBtn = SKLabelNode(text: "Sticks Random Color") let joystickSubstrateColorBtn = SKLabelNode(text: "Substrates Random Color") private var _isSetJoystickStickImage = false, _isSetJoystickSubstrateImage = false var isSetJoystickStickImage: Bool { get { return _isSetJoystickStickImage } set { _isSetJoystickStickImage = newValue let image = newValue ? UIImage(named: "jStick") : nil moveAnalogStick.stickImage = image rotateAnalogStick.stickImage = image setJoystickStickImageBtn.text = newValue ? "Remove Stick Images" : "Set Stick Images" } } var isSetJoystickSubstrateImage: Bool { get { return _isSetJoystickSubstrateImage } set { _isSetJoystickSubstrateImage = newValue let image = newValue ? UIImage(named: "jSubstrate") : nil moveAnalogStick.substrateImage = image rotateAnalogStick.substrateImage = image setJoystickSubstrateImageBtn.text = newValue ? "Remove Substrate Images" : "Set Substrate Images" } } var joysticksdiameters: CGFloat { get { return max(moveAnalogStick.diameter, rotateAnalogStick.diameter) } set(newdiameter) { moveAnalogStick.diameter = newdiameter rotateAnalogStick.diameter = newdiameter } } let moveAnalogStick = AnalogStick(diameter: kAnalogStickdiameter) let rotateAnalogStick = AnalogStick(diameter: kAnalogStickdiameter) override func didMoveToView(view: SKView) { /* Setup your scene here */ backgroundColor = UIColor.whiteColor() let jRadius = kAnalogStickdiameter / 2 moveAnalogStick.diameter = kAnalogStickdiameter moveAnalogStick.position = CGPointMake(jRadius + 15, jRadius + 15) moveAnalogStick.trackingHandler = { analogStick in guard let aN = self.appleNode else { return } aN.position = CGPointMake(aN.position.x + (analogStick.data.velocity.x * 0.12), aN.position.y + (analogStick.data.velocity.y * 0.12)) } addChild(moveAnalogStick) rotateAnalogStick.diameter = kAnalogStickdiameter rotateAnalogStick.position = CGPointMake(CGRectGetMaxX(self.frame) - jRadius - 15, jRadius + 15) rotateAnalogStick.trackingHandler = { analogStick in self.appleNode?.zRotation = analogStick.data.angular } addChild(rotateAnalogStick) appleNode = appendAppleToPoint(CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))) insertChild(appleNode!, atIndex: 0) physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) addChild(appendAppleToPoint(CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)))) let btnsOffset = CGFloat(10) let btnsOffsetHalf = btnsOffset / 2 let joystickSizeLabel = SKLabelNode(text: "Joysticks Size:") joystickSizeLabel.fontSize = 20 joystickSizeLabel.fontColor = UIColor.blackColor() joystickSizeLabel.horizontalAlignmentMode = .Left joystickSizeLabel.verticalAlignmentMode = .Top joystickSizeLabel.position = CGPoint(x: btnsOffset, y: self.frame.size.height - btnsOffset) addChild(joystickSizeLabel) joystickStickColorBtn.fontColor = UIColor.blackColor() joystickStickColorBtn.fontSize = 20 joystickStickColorBtn.verticalAlignmentMode = .Top joystickStickColorBtn.horizontalAlignmentMode = .Left joystickStickColorBtn.position = CGPoint(x: btnsOffset, y: self.frame.size.height - 40) addChild(joystickStickColorBtn) joystickSubstrateColorBtn.fontColor = UIColor.blackColor() joystickSubstrateColorBtn.fontSize = 20 joystickSubstrateColorBtn.verticalAlignmentMode = .Top joystickSubstrateColorBtn.horizontalAlignmentMode = .Left joystickSubstrateColorBtn.position = CGPoint(x: btnsOffset, y: self.frame.size.height - 65) addChild(joystickSubstrateColorBtn) jSizePlusSpriteNode.anchorPoint = CGPoint(x: 0, y: 0.5) jSizeMinusSpriteNode.anchorPoint = CGPoint(x: 0, y: 0.5) jSizeMinusSpriteNode.position = CGPoint(x: CGRectGetMaxX(joystickSizeLabel.frame) + btnsOffset, y: CGRectGetMidY(joystickSizeLabel.frame)) jSizePlusSpriteNode.position = CGPoint(x: CGRectGetMaxX(jSizeMinusSpriteNode.frame) + btnsOffset, y: CGRectGetMidY(joystickSizeLabel.frame)) addChild(jSizePlusSpriteNode) addChild(jSizeMinusSpriteNode) setJoystickStickImageBtn.fontColor = UIColor.blackColor() setJoystickStickImageBtn.fontSize = 20 setJoystickStickImageBtn.verticalAlignmentMode = .Bottom setJoystickStickImageBtn.position = CGPointMake(CGRectGetMidX(self.frame), moveAnalogStick.position.y - btnsOffsetHalf) addChild(setJoystickStickImageBtn) setJoystickSubstrateImageBtn.fontColor = UIColor.blackColor() setJoystickSubstrateImageBtn.fontSize = 20 setJoystickStickImageBtn.verticalAlignmentMode = .Top setJoystickSubstrateImageBtn.position = CGPointMake(CGRectGetMidX(self.frame), moveAnalogStick.position.y + btnsOffsetHalf) addChild(setJoystickSubstrateImageBtn) isSetJoystickStickImage = _isSetJoystickStickImage isSetJoystickSubstrateImage = _isSetJoystickSubstrateImage } func appendAppleToPoint(position: CGPoint) -> SKSpriteNode { let appleImage = UIImage(named: "apple") precondition(appleImage != nil, "Please set right image") let texture = SKTexture(image: appleImage!) let apple = SKSpriteNode(texture: texture) apple.physicsBody = SKPhysicsBody(texture: texture, size: apple.size) apple.physicsBody!.affectedByGravity = false apple.position = position return apple } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ super.touchesBegan(touches, withEvent: event) if let touch = touches.first { let node = nodeAtPoint(touch.locationInNode(self)) switch node { case jSizePlusSpriteNode: joysticksdiameters = joysticksdiameters + 1 case jSizeMinusSpriteNode: joysticksdiameters = joysticksdiameters - 1 case setJoystickStickImageBtn: isSetJoystickStickImage = !isSetJoystickStickImage case setJoystickSubstrateImageBtn: isSetJoystickSubstrateImage = !isSetJoystickSubstrateImage case joystickStickColorBtn: isSetJoystickStickImage = false let randomColor = UIColor.random() moveAnalogStick.stickColor = randomColor rotateAnalogStick.stickColor = randomColor case joystickSubstrateColorBtn: isSetJoystickSubstrateImage = false let randomColor = UIColor.random() moveAnalogStick.substrateColor = randomColor rotateAnalogStick.substrateColor = randomColor default: appleNode?.position = touch.locationInNode(self) } } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } } extension UIColor { static func random() -> UIColor { return UIColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: 1) } }
mit
1e8320acc87a6a6d5fa425f404e86805
38.601852
148
0.653612
4.562133
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/MarkdownBarView.swift
1
8474
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import Down import WireCommonComponents protocol MarkdownBarViewDelegate: AnyObject { func markdownBarView(_ view: MarkdownBarView, didSelectMarkdown markdown: Markdown, with sender: IconButton) func markdownBarView(_ view: MarkdownBarView, didDeselectMarkdown markdown: Markdown, with sender: IconButton) } final class MarkdownBarView: UIView { weak var delegate: MarkdownBarViewDelegate? private let stackView = UIStackView() private let enabledStateIconColor = SemanticColors.Button.textInputBarItemEnabled private let highlightedStateIconColor = SemanticColors.Button.textInputBarItemHighlighted private let enabledStateBackgroundColor = SemanticColors.Button.backgroundInputBarItemEnabled private let highlightedStateBackgroundColor = SemanticColors.Button.backgroundInputBarItemHighlighted private let enabledStateBorderColor = SemanticColors.Button.borderInputBarItemEnabled private let highlightedStateBorderColor = SemanticColors.Button.borderInputBarItemHighlighted let headerButton = PopUpIconButton() let boldButton = IconButton() let italicButton = IconButton() let numberListButton = IconButton() let bulletListButton = IconButton() let codeButton = IconButton() let buttons: [IconButton] private var buttonMargin: CGFloat { return conversationHorizontalMargins.left / 2 - StyleKitIcon.Size.tiny.rawValue / 2 } required init() { buttons = [headerButton, boldButton, italicButton, numberListButton, bulletListButton, codeButton] super.init(frame: CGRect.zero) setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: 56) } private func setupViews() { stackView.axis = .horizontal stackView.distribution = .equalSpacing stackView.alignment = .center stackView.layoutMargins = UIEdgeInsets(top: 0, left: buttonMargin, bottom: 0, right: buttonMargin) stackView.isLayoutMarginsRelativeArrangement = true headerButton.setIcon(.markdownH1, size: .tiny, for: .normal) boldButton.setIcon(.markdownBold, size: .tiny, for: .normal) italicButton.setIcon(.markdownItalic, size: .tiny, for: .normal) numberListButton.setIcon(.markdownNumberList, size: .tiny, for: .normal) bulletListButton.setIcon(.markdownBulletList, size: .tiny, for: .normal) codeButton.setIcon(.markdownCode, size: .tiny, for: .normal) for button in buttons { // We apply the corner radius only for the first and the last button if button == buttons.first { button.layer.cornerRadius = 12 button.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMinXMinYCorner] } if button == buttons.last { button.layer.cornerRadius = 12 button.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner] } button.contentEdgeInsets = UIEdgeInsets(top: 9, left: 20, bottom: 9, right: 20) button.layer.borderWidth = 1 button.clipsToBounds = true button.setIconColor(enabledStateIconColor, for: .normal) button.setBorderColor(enabledStateBorderColor, for: .normal) button.setBackgroundImageColor(enabledStateBackgroundColor, for: .normal) button.setIconColor(highlightedStateIconColor, for: .highlighted) button.setBorderColor(highlightedStateBorderColor, for: .highlighted) button.setBackgroundImageColor(highlightedStateBackgroundColor, for: .highlighted) button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside) stackView.addArrangedSubview(button) } addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.bottomAnchor.constraint(equalTo: bottomAnchor), stackView.leftAnchor.constraint(equalTo: leftAnchor), stackView.rightAnchor.constraint(equalTo: rightAnchor) ]) headerButton.itemIcons = [.markdownH1, .markdownH2, .markdownH3] headerButton.delegate = self headerButton.setupView() } @objc func textViewDidChangeActiveMarkdown(note: Notification) { guard let textView = note.object as? MarkdownTextView else { return } updateIcons(for: textView.activeMarkdown) } // MARK: Actions @objc private func buttonTapped(sender: IconButton) { guard let markdown = markdown(for: sender) else { return } if sender.iconColor(for: .normal) != enabledStateIconColor { delegate?.markdownBarView(self, didDeselectMarkdown: markdown, with: sender) } else { delegate?.markdownBarView(self, didSelectMarkdown: markdown, with: sender) } } // MARK: - Conversions fileprivate func markdown(for button: IconButton) -> Markdown? { switch button { case headerButton: return headerButton.icon(for: .normal)?.headerMarkdown ?? .h1 case boldButton: return .bold case italicButton: return .italic case codeButton: return .code case numberListButton: return .oList case bulletListButton: return .uList default: return nil } } func updateIcons(for markdown: Markdown) { // change header icon if necessary if let headerIcon = markdown.headerValue?.headerIcon { headerButton.setIcon(headerIcon, size: .tiny, for: .normal) } for button in buttons { guard let buttonMarkdown = self.markdown(for: button) else { continue } let iconColor = markdown.contains(buttonMarkdown) ? highlightedStateIconColor : enabledStateIconColor let backgroundColor = markdown.contains(buttonMarkdown) ? highlightedStateBackgroundColor : enabledStateBackgroundColor let borderColor = markdown.contains(buttonMarkdown) ? highlightedStateBorderColor : enabledStateBorderColor button.setIconColor(iconColor, for: .normal) button.setBorderColor(borderColor, for: .normal) button.setBackgroundImageColor(backgroundColor, for: .normal) } } @objc func resetIcons() { buttons.forEach { $0.setIconColor(enabledStateIconColor, for: .normal) $0.setBorderColor(enabledStateBorderColor, for: .normal) $0.setBackgroundImageColor(enabledStateBackgroundColor, for: .normal) } } } extension MarkdownBarView: PopUpIconButtonDelegate { func popUpIconButton(_ button: PopUpIconButton, didSelectIcon icon: StyleKitIcon) { if button === headerButton { let markdown = icon.headerMarkdown ?? .h1 delegate?.markdownBarView(self, didSelectMarkdown: markdown, with: button) } } } private extension StyleKitIcon { var headerMarkdown: Markdown? { switch self { case .markdownH1: return .h1 case .markdownH2: return .h2 case .markdownH3: return .h3 default: return nil } } } private extension Markdown { var headerIcon: StyleKitIcon? { switch self { case .h1: return .markdownH1 case .h2: return .markdownH2 case .h3: return .markdownH3 default: return nil } } }
gpl-3.0
04ffb38c2b9af79bef8b2c49bc28300a
37.87156
131
0.682204
4.996462
false
false
false
false
benlangmuir/swift
test/TypeCoercion/protocols.swift
9
9341
// RUN: %target-typecheck-verify-swift protocol MyPrintable { func print() } protocol Titled { var title : String { get set } } struct IsPrintable1 : FormattedPrintable, Titled, Document { var title = "" func print() {} func print(_: TestFormat) {} } // Printability is below struct IsPrintable2 { } struct IsNotPrintable1 { } struct IsNotPrintable2 { func print(_: Int) -> Int {} } struct Book : Titled { var title : String } struct Lackey : Titled { var title : String { get {} set {} } } struct Number { var title : Int } func testPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, inp1: IsNotPrintable1, inp2: IsNotPrintable2, op: OtherPrintable) { var p : MyPrintable = ip1 // okay let _: MyPrintable & Titled = Book(title: "") // expected-error@-1 {{value of type 'Book' does not conform to specified type 'MyPrintable'}} p = ip1 // okay p = ip2 // okay p = inp1 // expected-error{{cannot assign value of type 'IsNotPrintable1' to type 'any MyPrintable'}} let _: MyPrintable = inp1 // expected-error@-1 {{value of type 'IsNotPrintable1' does not conform to specified type 'MyPrintable'}} p = inp2 // expected-error{{cannot assign value of type 'IsNotPrintable2' to type 'any MyPrintable'}} p = op // expected-error{{value of type 'any OtherPrintable' does not conform to 'MyPrintable' in assignment}} _ = p } func testTitledCoercion(_ ip1: IsPrintable1, book: Book, lackey: Lackey, number: Number, ip2: IsPrintable2) { var t : Titled = ip1 // okay t = ip1 t = book t = lackey t = number // expected-error{{cannot assign value of type 'Number' to type 'any Titled'}} t = ip2 // expected-error{{cannot assign value of type 'IsPrintable2' to type 'any Titled'}} _ = t } extension IsPrintable2 : MyPrintable { func print() {} } protocol OtherPrintable { func print() } struct TestFormat {} protocol FormattedPrintable : MyPrintable { func print(_: TestFormat) } struct NotFormattedPrintable1 { func print(_: TestFormat) { } } func testFormattedPrintableCoercion(_ ip1: IsPrintable1, ip2: IsPrintable2, fp: inout FormattedPrintable, p: inout MyPrintable, op: inout OtherPrintable, nfp1: NotFormattedPrintable1) { fp = ip1 fp = ip2 // expected-error{{cannot assign value of type 'IsPrintable2' to type 'any FormattedPrintable'}} fp = nfp1 // expected-error{{cannot assign value of type 'NotFormattedPrintable1' to type 'any FormattedPrintable'}} p = fp op = fp // expected-error{{value of type 'any FormattedPrintable' does not conform to 'OtherPrintable' in assignment}} fp = op // expected-error{{value of type 'any OtherPrintable' does not conform to 'FormattedPrintable' in assignment}} } protocol Document : Titled, MyPrintable { } func testMethodsAndVars(_ fp: FormattedPrintable, f: TestFormat, doc: inout Document) { fp.print(f) fp.print() doc.title = "Gone with the Wind" doc.print() } func testDocumentCoercion(_ doc: inout Document, ip1: IsPrintable1, l: Lackey) { doc = ip1 doc = l // expected-error{{cannot assign value of type 'Lackey' to type 'any Document'}} } // Check coercion of references. func refCoercion(_ p: inout MyPrintable) { } var p : MyPrintable = IsPrintable1() var fp : FormattedPrintable = IsPrintable1() // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{10-28=MyPrintable}} var ip1 : IsPrintable1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{11-23=MyPrintable}} refCoercion(&p) refCoercion(&fp) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} do { var fp_2 = fp // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{11-11=: MyPrintable}} var ip1_2 = ip1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{12-12=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { var fp_2 : FormattedPrintable = fp, ip1_2 = ip1 // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{14-32=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{44-44=: MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { var fp_2, fp_3 : FormattedPrintable // expected-note@-1{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{20-38=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{20-38=MyPrintable}} fp_2 = fp fp_3 = fp refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&fp_3) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} } do { func wrapRefCoercion1(fp_2: inout FormattedPrintable, ip1_2: inout IsPrintable1) { // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'any FormattedPrintable'}} {{31-55=MyPrintable}} // expected-note@-2{{change variable type to 'any MyPrintable' if it doesn't need to be declared as 'IsPrintable1'}} {{32-50=MyPrintable}} refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } } do { // Make sure we don't add the fix-it for tuples: var (fp_2, ip1_2) = (fp, ip1) refCoercion(&fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} refCoercion(&ip1_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'IsPrintable1'; use a value declared as type 'any MyPrintable' instead}} } do { // Make sure we don't add the fix-it for vars in different scopes: enum ParentScope { static var fp_2 = fp } refCoercion(&ParentScope.fp_2) // expected-error@-1{{inout argument could be set to a value with a type other than 'any FormattedPrintable'; use a value declared as type 'any MyPrintable' instead}} } protocol IntSubscriptable { subscript(i: Int) -> Int { get } } struct IsIntSubscriptable : IntSubscriptable { subscript(i: Int) -> Int { get {} set {} } } struct IsDoubleSubscriptable { subscript(d: Double) -> Int { get {} set {} } } struct IsIntToStringSubscriptable { subscript(i: Int) -> String { get {} set {} } } func testIntSubscripting(i_s: inout IntSubscriptable, iis: IsIntSubscriptable, ids: IsDoubleSubscriptable, iiss: IsIntToStringSubscriptable) { var x = i_s[17] i_s[5] = 7 // expected-error{{cannot assign through subscript: subscript is get-only}} i_s = iis i_s = ids // expected-error{{cannot assign value of type 'IsDoubleSubscriptable' to type 'any IntSubscriptable'}} i_s = iiss // expected-error{{cannot assign value of type 'IsIntToStringSubscriptable' to type 'any IntSubscriptable'}} } protocol MyREPLPrintable { func myReplPrint() } extension Int : MyREPLPrintable { func myReplPrint() {} } extension String : MyREPLPrintable { func myReplPrint() {} } func doREPLPrint(_ p: MyREPLPrintable) { p.myReplPrint() } func testREPLPrintable() { let i : Int = 1 _ = i as MyREPLPrintable doREPLPrint(i) doREPLPrint(1) doREPLPrint("foo") } // Bool coercion if true as Bool {}
apache-2.0
da154c439e3b596dbe1616df619abb67
36.971545
170
0.682368
3.766532
false
false
false
false
kasketis/netfox
netfox/Core/NFXHTTPModel.swift
1
9674
// // NFXHTTPModel.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // import Foundation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } @objc public class NFXHTTPModel: NSObject { @objc public var requestURL: String? @objc public var requestURLComponents: URLComponents? @objc public var requestURLQueryItems: [URLQueryItem]? @objc public var requestMethod: String? @objc public var requestCachePolicy: String? @objc public var requestDate: Date? @objc public var requestTime: String? @objc public var requestTimeout: String? @objc public var requestHeaders: [AnyHashable: Any]? public var requestBodyLength: Int? @objc public var requestType: String? @objc public var requestCurl: String? public var responseStatus: Int? @objc public var responseType: String? @objc public var responseDate: Date? @objc public var responseTime: String? @objc public var responseHeaders: [AnyHashable: Any]? public var responseBodyLength: Int? public var timeInterval: Float? @objc public lazy var randomHash = UUID().uuidString public var shortType = HTTPModelShortType.OTHER @objc public var shortTypeString: String { return shortType.rawValue } @objc public var noResponse = true func saveRequest(_ request: URLRequest) { requestDate = Date() requestTime = getTimeFromDate(requestDate!) requestURL = request.getNFXURL() requestURLComponents = request.getNFXURLComponents() requestURLQueryItems = request.getNFXURLComponents()?.queryItems requestMethod = request.getNFXMethod() requestCachePolicy = request.getNFXCachePolicy() requestTimeout = request.getNFXTimeout() requestHeaders = request.getNFXHeaders() requestType = requestHeaders?["Content-Type"] as! String? requestCurl = request.getCurl() } func saveRequestBody(_ request: URLRequest) { saveRequestBodyData(request.getNFXBody()) } func logRequest(_ request: URLRequest) { formattedRequestLogEntry().appendToFileURL(NFXPath.sessionLogURL) } func saveErrorResponse() { responseDate = Date() } func saveResponse(_ response: URLResponse, data: Data) { noResponse = false responseDate = Date() responseTime = getTimeFromDate(responseDate!) responseStatus = response.getNFXStatus() responseHeaders = response.getNFXHeaders() let headers = response.getNFXHeaders() if let contentType = headers["Content-Type"] as? String { let responseType = contentType.components(separatedBy: ";")[0] shortType = HTTPModelShortType(contentType: responseType) self.responseType = responseType } timeInterval = Float(responseDate!.timeIntervalSince(requestDate!)) saveResponseBodyData(data) formattedResponseLogEntry().appendToFileURL(NFXPath.sessionLogURL) } func saveRequestBodyData(_ data: Data) { let tempBodyString = String.init(data: data, encoding: String.Encoding.utf8) self.requestBodyLength = data.count if (tempBodyString != nil) { saveData(tempBodyString!, to: getRequestBodyFileURL()) } } func saveResponseBodyData(_ data: Data) { var bodyString: String? if shortType == .IMAGE { bodyString = data.base64EncodedString(options: .endLineWithLineFeed) } else { if let tempBodyString = String(data: data, encoding: String.Encoding.utf8) { bodyString = tempBodyString } } if let bodyString = bodyString { responseBodyLength = data.count saveData(bodyString, to: getResponseBodyFileURL()) } } fileprivate func prettyOutput(_ rawData: Data, contentType: String? = nil) -> String { guard let contentType = contentType, let output = prettyPrint(rawData, type: .init(contentType: contentType)) else { return String(data: rawData, encoding: String.Encoding.utf8) ?? "" } return output } @objc public func getRequestBody() -> String { guard let data = readRawData(from: getRequestBodyFileURL()) else { return "" } return prettyOutput(data, contentType: requestType) } @objc public func getResponseBody() -> String { guard let data = readRawData(from: getResponseBodyFileURL()) else { return "" } return prettyOutput(data, contentType: responseType) } @objc public func getRequestBodyFileURL() -> URL { return NFXPath.pathURLToFile(getRequestBodyFilename()) } @objc public func getRequestBodyFilename() -> String { return "request_body_\(requestTime!)_\(randomHash)" } @objc public func getResponseBodyFileURL() -> URL { return NFXPath.pathURLToFile(getResponseBodyFilename()) } @objc public func getResponseBodyFilename() -> String { return "response_body_\(requestTime!)_\(randomHash)" } @objc public func saveData(_ dataString: String, to fileURL: URL) { do { try dataString.write(to: fileURL, atomically: true, encoding: .utf8) } catch let error { print("[NFX]: Failed to save data to [\(fileURL)] - \(error.localizedDescription)") } } @objc public func readRawData(from fileURL: URL) -> Data? { do { return try Data(contentsOf: fileURL) } catch let error { print("[NFX]: Failed to load data from [\(fileURL)] - \(error.localizedDescription)") return nil } } @objc public func getTimeFromDate(_ date: Date) -> String? { let calendar = Calendar.current let components = (calendar as NSCalendar).components([.hour, .minute], from: date) guard let hour = components.hour, let minutes = components.minute else { return nil } if minutes < 10 { return "\(hour):0\(minutes)" } else { return "\(hour):\(minutes)" } } public func prettyPrint(_ rawData: Data, type: HTTPModelShortType) -> String? { switch type { case .JSON: do { let rawJsonData = try JSONSerialization.jsonObject(with: rawData, options: []) let prettyPrintedString = try JSONSerialization.data(withJSONObject: rawJsonData, options: [.prettyPrinted]) return String(data: prettyPrintedString, encoding: String.Encoding.utf8) } catch { return nil } default: return nil } } @objc public func isSuccessful() -> Bool { if (self.responseStatus != nil) && (self.responseStatus < 400) { return true } else { return false } } @objc public func formattedRequestLogEntry() -> String { var log = String() if let requestURL = self.requestURL { log.append("-------START REQUEST - \(requestURL) -------\n") } if let requestMethod = self.requestMethod { log.append("[Request Method] \(requestMethod)\n") } if let requestDate = self.requestDate { log.append("[Request Date] \(requestDate)\n") } if let requestTime = self.requestTime { log.append("[Request Time] \(requestTime)\n") } if let requestType = self.requestType { log.append("[Request Type] \(requestType)\n") } if let requestTimeout = self.requestTimeout { log.append("[Request Timeout] \(requestTimeout)\n") } if let requestHeaders = self.requestHeaders { log.append("[Request Headers]\n\(requestHeaders)\n") } log.append("[Request Body]\n \(getRequestBody())\n") if let requestURL = self.requestURL { log.append("-------END REQUEST - \(requestURL) -------\n\n") } return log; } @objc public func formattedResponseLogEntry() -> String { var log = String() if let requestURL = self.requestURL { log.append("-------START RESPONSE - \(requestURL) -------\n") } if let responseStatus = self.responseStatus { log.append("[Response Status] \(responseStatus)\n") } if let responseType = self.responseType { log.append("[Response Type] \(responseType)\n") } if let responseDate = self.responseDate { log.append("[Response Date] \(responseDate)\n") } if let responseTime = self.responseTime { log.append("[Response Time] \(responseTime)\n") } if let responseHeaders = self.responseHeaders { log.append("[Response Headers]\n\(responseHeaders)\n\n") } log.append("[Response Body]\n \(getResponseBody())\n") if let requestURL = self.requestURL { log.append("-------END RESPONSE - \(requestURL) -------\n\n") } return log; } }
mit
d89b0c1e7ebc650b2bd71d19ebaa89ca
31.901361
124
0.587822
4.947826
false
false
false
false
moshbit/Kotlift
test-dest/33_complex.swift
2
931
func foo(a: String, b: [String: String], c: ((String) -> Void)? = nil) -> String? { c?("a=\(a)") return a } func fooFunc(a: String, b: [String: String], c: ((String) -> Void)? = nil) -> String? { return nil } func run() -> String { var outerValue = "" let _kotliftOptional1 = foo("bar", b: [String: String](), c: { value in outerValue: value }); if _kotliftOptional1 == nil { return "fail1" }; var a = _kotliftOptional1! a = foo("bar", b: [String: String](), c: { value in outerValue: value }) fooFunc("bar", b: [String: String](), c: { value in outerValue: value }) if a != "bar" { print("fail: a=\(a) (should be bar)") return "fail2" } if outerValue != "a=bar" { print("fail: outerValue=\(outerValue) (should be a=bar)") return "fail3" } return "ok" } func main(args: [String]) { if run() != "ok" { print("fail: invalid return") } else { print("success") } } main([])
apache-2.0
e8d9636bc4fdca09de5ad59e02a679b9
24.162162
170
0.566058
3.072607
false
false
false
false
congphuthe/IAPSubscription
IAPSubscription/Subscription.swift
1
1684
/** * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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 StoreKit private var formatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.formatterBehavior = .behavior10_4 return formatter }() struct Subscription { let product: SKProduct let formattedPrice: String init(product: SKProduct) { self.product = product if formatter.locale != self.product.priceLocale { formatter.locale = self.product.priceLocale } formattedPrice = formatter.string(from: product.price) ?? "\(product.price)" } }
mit
0dddf65767ee9abd939ce43ae6b414e7
34.829787
80
0.744062
4.613699
false
false
false
false
bchrobot/StickyHeaderTabController
Example/StickyHeaderTabController/ExampleTabController.swift
1
2370
// // ExampleTabController.swift // StickyHeaderTabController // // Created by Benjamin Chrobot on 09/21/2017. // Copyright (c) 2017 Benjamin Chrobot. All rights reserved. // import UIKit import StickyHeaderTabController class ExampleTabController: StickyHeaderTabController { // MARK: - Properties private let exampleHeader = ExampleStickyHeaderView() private let exampleHero = ExampleStickyHeroView() private let exampleTabBar = ExampleTabBar(frame: .zero) // MARK: - ViewController lifecycle override func viewDidLoad() { super.viewDidLoad() commonInit() } // MARK: - Setup private func commonInit() { delegate = self stickyHeader = exampleHeader hero = exampleHero tabBar = exampleTabBar tabs = [StatesTabViewController(), ColorsTabViewController()] } // Private Methods fileprivate func updateAvatarSize() { let maxValue = exampleHeader.bounds.height let minValue = exampleHeader.pinnedHeight let currentValue = exampleHero.frame.origin.y let percentage = min(max(0, ((currentValue - minValue) / (maxValue - minValue))), 1) exampleHero.avatarSizePercentage = percentage } fileprivate func updateNameLabel() { let headerBottom = exampleHeader.frame.origin.y + exampleHeader.frame.size.height let heroTop = exampleHero.frame.origin.y let heroNameOffset = exampleHero.nameLabel.frame.origin.y let nameTop = heroTop + heroNameOffset let overlapPx = max(0, headerBottom - nameTop) let percentage = min(max(0, (overlapPx / exampleHero.nameLabel.bounds.height)), 1) exampleHeader.percentVisibleName = percentage } fileprivate func updateBlur() { let headerBottom = exampleHeader.frame.origin.y + exampleHeader.frame.size.height let heroTop = exampleHero.frame.origin.y let overlapPx = max(0, headerBottom - heroTop) let percentage = min(max(0, (overlapPx / exampleHero.bounds.height)), 1) exampleHeader.percentVisibleBlur = percentage } } extension ExampleTabController: StickyHeaderTabControllerDelegate { func stickyHeaderTabControllerDidScrollVertically(_ controller: StickyHeaderTabController) { updateAvatarSize() updateNameLabel() updateBlur() } }
mit
69639748a6dc83c1c1e03db5dbbffbb6
29.779221
96
0.691561
4.674556
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallRotate.swift
3
2925
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallRotate: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1 fileprivate let timingFunction = CAMediaTimingFunction(controlPoints: 0.7, -0.13, 0.22, 0.86) // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 // Draw circles let leftCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color) let rightCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color) let centerCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color) leftCircle.opacity = 0.8 leftCircle.frame = CGRect(x: 0, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) rightCircle.opacity = 0.8 rightCircle.frame = CGRect(x: size.width - circleSize, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) centerCircle.frame = CGRect(x: (size.width - circleSize) / 2, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize) let circle = CALayer() let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) circle.frame = frame circle.addSublayer(leftCircle) circle.addSublayer(rightCircle) circle.addSublayer(centerCircle) circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallRotate { var animation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var scaleAnimation: CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration return scaleAnimation } var rotateAnimation: CAKeyframeAnimation { let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = [0, 0.5, 1] rotateAnimation.timingFunctions = [timingFunction, timingFunction] rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi] rotateAnimation.duration = duration return rotateAnimation } }
mit
fe5ac15075fdcdb0d660ab695f2ab572
36.987013
139
0.717949
4.520866
false
false
false
false
tailoredmedia/Endpoints
Sources/Body/Multipart/MultipartBody.swift
1
3452
import Foundation /// A Body for a multipart/form-data conforming to RFC 2046 public struct MultipartBody: Body { /// CRLF (Carriage Return + Line Feed) private static let lineEnd = "\r\n" /// The default implementation of a `MultipartBodyPart` that accepts any combination for it's properties public struct Part: MultipartBodyPart { public let name: String public let filename: String? public let mimeType: String? public let charset: String? public let data: Data public init(name: String, data: Data, filename: String? = nil, mimeType: String? = nil, charset: String? = nil) { self.name = name self.data = data self.filename = filename self.mimeType = mimeType self.charset = charset } } /// The boundary without the two hyphens and CRLF public let boundary: String /// The parts of the body public var parts: [MultipartBodyPart] /// Creates a multipart body with the given parts /// /// - Parameter parts: the parts of the multipart body, as per rfc1341 there must be at least 1 part /// - Parameter boundary: the boundary of the multipart request, excluding the two hyphens and CRLF. Must not be longer than 70 characters. public init(parts: [MultipartBodyPart], boundary: String = UUID().uuidString) { self.parts = parts self.boundary = boundary } public var header: Parameters? { return [ "Content-Type": "multipart/form-data; boundary=\(boundary)" ] } public var requestData: Data { var data = Data() // See RFC 2046 5.1: // The Content-Type field for multipart entities requires one parameter, "boundary". // The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) // followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF. // Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens. let partBoundaryPrefix = "--\(boundary)\(MultipartBody.lineEnd)" for part in parts { // build header of part-entity data.append(string: partBoundaryPrefix) data.append(string: part.dispositionString) data.append(string: MultipartBody.lineEnd) if let contentTypeString = part.contentTypeString { data.append(string: contentTypeString) data.append(string: "\(MultipartBody.lineEnd)") } // build body of part-entity data.append(string: "\(MultipartBody.lineEnd)") data.append(part.data) data.append(string: "\(MultipartBody.lineEnd)") } // See RFC 2046 5.1: // The boundary delimiter line following the last body part is a distinguished delimiter that indicates // that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, // with the addition of two more hyphens after the boundary parameter value. data.append(string: "--\(boundary)--") return data } } private extension Data { mutating func append(string: String) { append(string.data(using: .utf8)!) } }
mit
5cb2faca95c2983247584f3f2e729a07
38.678161
160
0.64803
4.868829
false
false
false
false
designatednerd/iOS10NotificationSample
ParrotKit/Models/GreatestCommonDenominator.swift
1
1522
// // GreatestCommonDenominator.swift // NotificationSample // // Created by Ellen Shapiro (Work) on 9/1/16. // Copyright © 2016 Designated Nerd Software. All rights reserved. // import Foundation struct GreatestCommonDenominator { static func of(_ a: Int?, _ b: Int?) -> Int { guard let first = a else { //If b is also nil, return 0 return b ?? 0 } guard let second = b else { return first } //Compare things in a semi-sensible fashion var larger: Int var smaller: Int if first > second { larger = first smaller = second } else { larger = second smaller = first } var remainder: Int = Int.max while remainder > 0 { remainder = larger % smaller if remainder == 0 { return smaller } else { larger = smaller smaller = remainder } } //We don't have any kind of common divisor. return 1 } static func `in`(array:[Int]) -> Int { if array.isEmpty { //Nothing to divide. return 1 } let greatestCommonDenominator = array.reduce(array[0]) { item, currentGCD in return GreatestCommonDenominator.of(item, currentGCD) } return greatestCommonDenominator } }
mit
b6760195c337f74fbfa814912ab7353e
23.142857
67
0.495726
4.970588
false
true
false
false
slavapestov/swift
test/Parse/foreach.swift
1
1080
// RUN: %target-parse-verify-swift struct IntRange<Int> : SequenceType, GeneratorType { typealias Element = (Int, Int) func next() -> (Int, Int)? {} typealias Generator = IntRange<Int> func generate() -> IntRange<Int> { return self } } func for_each(r: Range<Int>, iir: IntRange<Int>) { var sum = 0 // Simple foreach loop, using the variable in the body for i in r { sum = sum + i } // Check scoping of variable introduced with foreach loop i = 0 // expected-error{{use of unresolved identifier 'i'}} // For-each loops with two variables and varying degrees of typedness for (i, j) in iir { sum = sum + i + j } for (i, j) in iir { sum = sum + i + j } for (i, j) : (Int, Int) in iir { sum = sum + i + j } // Parse errors for i r { // expected-error 2{{expected ';' in 'for' statement}} expected-error {{use of unresolved identifier 'i'}} expected-error {{type 'Range<Int>' does not conform to protocol 'BooleanType'}} } for i in r sum = sum + i; // expected-error{{expected '{' to start the body of for-each loop}} }
apache-2.0
bb52b60638c760bfda5ae3e422884edf
29
198
0.628704
3.450479
false
false
false
false
sarah-j-smith/Quest
Common/AdventureModel/GameObject.swift
1
1841
//// // GameObject.swift // SwiftQuest // // Created by Sarah Smith on 24/12/2014. // Copyright (c) 2014 Sarah Smith. All rights reserved. // import Foundation class GameObject : NSObject, NSCoding, Printable { /** System name, must be unique; must have no spaces and be URL fragment safe */ var objectKey : String { didSet { NSLog("objectKey: \(objectKey)") } } /** User visible descriptive name */ var objectName : String { didSet { NSLog("objectName: \(objectName)") } } var parentName : String? override var description : String { get { return "Object: [\(objectKey)] \(objectName)" } } convenience init(objectName name: String ) { let allNameChars = NSRange(location: 0, length: countElements(name)) let validCharsRegex = NSRegularExpression(pattern: "[\\P{L}]", options: nil, error: nil)! let key = validCharsRegex.stringByReplacingMatchesInString(name, options: nil, range: allNameChars, withTemplate: "-") self.init(objectKey:name.keySafe(), objectName:name) } init(objectKey key: String, objectName name: String ) { self.objectKey = key self.objectName = name } required init(coder aDecoder: NSCoder) { objectKey = aDecoder.decodeObjectForKey("objectKey") as String! objectName = aDecoder.decodeObjectForKey("objectName") as String! parentName = aDecoder.decodeObjectForKey("parentName") as String! super.init() } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(objectKey, forKey: "objectKey") aCoder.encodeObject(objectName, forKey: "objectName") aCoder.encodeObject(parentName, forKey: "parentName") } }
mit
e4d627c0804eda50a12493784e37c61a
27.765625
126
0.620858
4.63728
false
false
false
false
Bersaelor/SwiftyHYGDB
Sources/SwiftyHYGDB/Star3D+Codable.swift
1
1452
// // Star3D+Codable.swift // SwiftyHYGDB // // Created by Konrad Feiler on 15.09.17. // import Foundation extension Star3D: Codable { private enum CodingKeys: String, CodingKey { case dbID = "d" case x = "x" case y = "y" case z = "z" case starData = "s" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) dbID = try container.decode(Int32.self, forKey: .dbID) x = try container.decode(Float.self, forKey: .x) y = try container.decode(Float.self, forKey: .y) z = try container.decode(Float.self, forKey: .z) let starValue: StarData = try container.decode(StarData.self, forKey: .starData) starData = Box(starValue) } public func encode(to encoder: Encoder) throws { guard let value = starData?.value else { print("Failed to decode starData's value for star \(dbID)") return } var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(dbID, forKey: .dbID) try container.encode(x, forKey: .x) try container.encode(y, forKey: .y) try container.encode(z, forKey: .z) try container.encode(value, forKey: .starData) } }
mit
30bc885389c405b5665e2a45d3dd9d3e
34.414634
89
0.552342
3.913747
false
false
false
false
pmwiseman/PWInfiniteScroll
PWInfiniteCollectionView/ViewController.swift
1
1355
// // ViewController.swift // PWInfiniteCollectionView // // Created by Patrick Wiseman on 8/2/17. // Copyright © 2017 Patrick Wiseman. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var collectionView: PWInfiniteCollectionView! var colors = [UIColor.blue, UIColor.black, UIColor.yellow, UIColor.cyan, UIColor.red, UIColor.purple] override func viewDidLoad() { super.viewDidLoad() pageControl.numberOfPages = colors.count collectionView.infiniteDataSource = self collectionView.infiniteDelegate = self } } extension ViewController: PWInfiniteCollectionViewDataSource { func numberOfItems(collectionView: UICollectionView) -> Int { return colors.count } func cellForItemAt(collectionView: UICollectionView, indexPath: IndexPath, dataIndexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) let color = colors[dataIndexPath.row] cell.backgroundColor = color return cell } } extension ViewController: PWInfiniteCollectionViewDelegate { func currentPageIndexDidChange(with pageIndex: Int) { pageControl.currentPage = pageIndex } }
mit
0fe07eebc9c0a058bf0edc16a3926de5
30.488372
130
0.722304
5.090226
false
false
false
false
SodiumFRP/sodium-swift
Sodium/Cell.swift
1
18116
/** # Cell Represents a value that changes over time. */ public protocol CellType { associatedtype Element var refs: MemReferences? { get } func stream() -> Stream<Element> func sample() -> Element func sampleLazy(_ trans: Transaction) -> Lazy<Element> func sampleNoTransaction() -> Element func value(_ trans: Transaction) -> Stream<Element> } public struct AnyCell<T>: CellType { fileprivate let _refs: MemReferences? fileprivate let _stream: () -> Stream<T> fileprivate let _sample: () -> T fileprivate let _sampleLazy: (Transaction)->Lazy<T> fileprivate let _sampleNoTransaction: () -> T fileprivate let _value: (Transaction) -> Stream<T> public init<Base: CellType>(_ base: Base) where T == Base.Element { _refs = base.refs _stream = base.stream _sample = base.sample _sampleLazy = base.sampleLazy _sampleNoTransaction = base.sampleNoTransaction _value = base.value } public var refs: MemReferences? { return self._refs } public func stream() -> Stream<T> { return _stream() } public func sample() -> T { return _sample() } public func sampleLazy(_ trans: Transaction) -> Lazy<T> { return _sampleLazy(trans) } public func sampleNoTransaction() -> T { return _sampleNoTransaction() } public func value(_ trans: Transaction) -> Stream<T> { return _value(trans) } } /** Represents a value that changes over time. - Parameter T: The type of the value. */ open class CellBase<T> : CellType { internal let _stream: Stream<T> fileprivate var _value: T fileprivate var _valueUpdate: T? open var refs: MemReferences? /** Creates a cell with a constant value. - Parameters: - T: The type of the value of the cell. - value: The value of the cell. - Returns: A cell with a constant value. */ open static func constant<T>(_ value: T, refs: MemReferences? = nil) -> Cell<T> { return Cell<T>(value: value, refs: refs) } /** Creates a cell with a lazily computed constant value. - Parameter TResult: The type of the value of the cell. - Parameter value: The lazily computed value of the cell. - Returns: A cell with a lazily computed constant value. */ open static func constantLazy<TResult>( _ value: @autoclosure @escaping () -> TResult) -> AnyCell<TResult> { return Stream<TResult>.never().holdLazy(value) } /** Creates a cell with a constant value. - Parameter value: The constant value of the cell. */ internal init(value: T, refs: MemReferences? = nil) { self.refs = refs if let r = self.refs { r.addRef() } self._stream = Stream<T>() self._value = value } internal init(stream: Stream<T>, initialValue: T, refs: MemReferences? = nil) { self.refs = refs if let r = self.refs { r.addRef() } self._stream = stream self._value = initialValue } deinit { if let r = self.refs { r.release() } } internal var keepListenersAlive: IKeepListenersAlive { return self._stream.keepListenersAlive } var ValueProperty: T { get { return _value } set(value) { self._value = value } } /** Sample the current value of the cell. - Returns: the current value of the cell. - Remarks: This method may be used inside the functions passed to primitives that apply them to streams, including `Stream<T>.map<TResult>(Func<T, TResult>)` in which case it is equivalent to snapshotting the cell, `Stream<T>.snapshot<T2, TResult>(Cell<T2>, Func<T, T2, TResult>)`, `Stream<T>.filter(Func{T, bool})`, and 'Stream<T>.merge(Stream<T>, Func{T, T, T})` It should generally be avoided in favor of `Listen(Action<T>)` so updates aren't missed, but in many circumstances it makes sense. It can be best to use this method inside an explicit transaction (using `Transaction.run<T>(Func<T>)` or `Transaction.runVoid(Action)`). For example, a b.Sample() inside an explicit transaction along with a b.Updates().Listen(...) will capture the current value and any updates without risk of missing any in between. */ open func sample() -> T { return Transaction.apply{ trans in self.sampleNoTransaction() } } open func stream() -> Stream<T> { return self._stream } /** Sample the current value of the cell. - Returns: A lazy which may be used to get the current value of the cell. - Remarks: This is a variant of `sample` that works with the `CellLoop<T>` class when the cell loop has not yet been looped. It should be used in any code that is general enough that it may be passed a `CellLoop<T>`. - SeeAlso: `Stream<T>.HoldLazy(Lazy<T>)` */ open func sampleLazy(_ trans: Transaction) -> Lazy<T> { let s = LazySample(cell: self) trans.last( { s.value = self._valueUpdate ?? self.sampleNoTransaction() //s.cell = nil }) return Lazy(f: { s.value ?? s.cell.sample() }) } open func sampleNoTransaction() -> T { let t = self.ValueProperty return t } internal func updates(_ trans: Transaction?) -> Stream<T> { return self.stream() } /** Listen for updates to the value of this cell. The returned `Listener` may be disposed to stop listening, or it will automatically stop listening when it is garbage collected. - Note: This is an OPERATIONAL mechanism for interfacing between the world of I/O and FRP. - Parameter handler: The handler to execute for each value. - Returns: An `Listener` which may be disposed to stop listening. - Remarks: No assumptions should be made about what thread the handler is called on and it should not block. Neither `StreamSink<T>.send` nor `CellSink<T>.send` may be called from the handler. They will throw an exception because this method is not meant to be used to create new primitives. If the `Listener` is not disposed, it will continue to listen until this cell is either disposed or garbage collected or the listener itself is garbage collected. */ open func listenWeak(_ handler: @escaping (T) -> Void) -> Listener { return Transaction.apply { trans in self.value(trans).listenWeak(handler)} } /* /* * Return a cell whose stream only receives events which have a different value than the previous event. */ - Returns:A cell whose stream only receives events which have a different value than the previous event. public func calm() -> Cell<T> { return self.Calm(EqualityComparer<T>.Default) } /* * Return a cell whose stream only receives events which have a different value than the previous event. */ - Parameter comparer: The equality comparer to use to determine if two items are equal. - Returns:A cell whose stream only receives events which have a different value than the previous event. public func calm(comparer: IEqualityComparer<T>) -> Cell<T> { let initA = self.SampleLazy() let mInitA = initA.Map(Maybe.Just) return Transaction.Apply { trans in self.Updates(trans).Calm(mInitA, comparer).HoldLazy(initA) } } */ } private class LazySample<C:CellType> { let cell: C var value: C.Element? init(cell: C) { self.cell = cell } } /** The class hierarchy comes because you can create a closure that uses an uninitialized self. CellBase<> has all the data, and we just have the cleanup closure to take care of. */ open class Cell<T>: CellBase<T> { fileprivate var cleanup: Listener = Listener(unlisten: nop, refs: nil) public override init(value: T, refs: MemReferences? = nil) { super.init (value: value, refs: refs) self.cleanup = doListen(refs) } public override init(stream: Stream<T>, initialValue: T, refs: MemReferences? = nil) { super.init(stream: stream, initialValue: initialValue, refs: refs) self.cleanup = doListen(refs) } fileprivate func doListen(_ refs: MemReferences?) -> Listener { return Transaction.apply { trans1 in self.stream().listen(Node<Element>.Null, trans: trans1, action: { [weak self] (trans2, a) in if self!._valueUpdate == nil { trans2.last({ self!._value = self!._valueUpdate! self!._valueUpdate = nil }) } self!._valueUpdate = a }, suppressEarlierFirings: false, refs: refs) } } deinit { print("Cell<> deinit") self.cleanup.unlisten() } } extension CellType { public typealias Handler = (Element) -> Void /** Lift a binary function into cells, so the returned Cell always reflects the specified function applied to the input cells' values. - Parameter C: The type of second cell. - Parameter TResult: The type of the result. - Parameter f: The binary function to lift into the cells. - Parameter c2: The second cell. - Returns: A cell containing values resulting from the binary function applied to the input cells' values. */ public func lift<C:CellType, TResult>(_ c2: C, f: @escaping (Element,C.Element) -> TResult) -> AnyCell<TResult> { let ffa = { a in { b in f(a,b) }} return c2.apply(self.map(ffa)) } /** Lift a ternary function into cells, so the returned cell always reflects the specified function applied to the input cells' values. - Parameter C2: The type of second cell. - Parameter C3: The type of third cell. - Parameter TResult: The type of the result. - Parameter f: The binary function to lift into the cells. - Parameter c2: The second cell. - Parameter c3: The third cell. - Returns: A cell containing values resulting from the ternary function applied to the input cells' values. */ public func lift<C2:CellType, C3: CellType, TResult>(_ c2: C2, c3: C3, f: @escaping (Element,C2.Element,C3.Element) -> TResult) -> AnyCell<TResult> { let ffa = { a in { b in { c in f(a,b,c) }}} return c3.apply(c2.apply(self.map(ffa))) } /** Lift a quaternary function into cells, so the returned cell always reflects the specified function applied to the input cells' values. - Parameter C2: The type of second cell. - Parameter C3: The type of third cell. - Parameter C4: The type of fourth cell. - Parameter TResult: The type of the result. - Parameter f: The binary function to lift into the cells. - Parameter c2: The second cell. - Parameter c3: The third cell. - Parameter c4: The fourth cell. - Returns: A cell containing values resulting from the quaternary function applied to the input cells' values. */ public func lift<C2:CellType, C3:CellType, C4:CellType, TResult>(_ c2: C2, c3: C3, c4: C4, f: @escaping (Element,C2.Element,C3.Element,C4.Element) -> TResult) -> AnyCell<TResult> { let ffa = { a in { b in { c in { d in f(a,b,c,d) }}}} return c4.apply(c3.apply(c2.apply(self.map(ffa)))) } /** Lift a 5-argument function into cells, so the returned cell always reflects the specified function applied to the input cells' values. - Parameter C2: The type of second cell. - Parameter C3: The type of third cell. - Parameter C4: The type of fourth cell. - Parameter C5: The type of fifth cell. - Parameter TResult: The type of the result. - Parameter f: The binary function to lift into the cells. - Parameter c2: The second cell. - Parameter c3: The third cell. - Parameter c4: The fourth cell. - Parameter c5: The fifth cell. - Returns: A cell containing values resulting from the 5-argument function applied to the input cells' values. */ public func lift<C2:CellType, C3:CellType, C4:CellType, C5:CellType, TResult>(_ c2: C2, c3: C3, c4: C4, c5: C5, f: @escaping (Element,C2.Element,C3.Element,C4.Element,C5.Element)->TResult) -> AnyCell<TResult> { let ffa = { a in { b in { c in { d in { e in f(a,b,c,d,e) }}}}} return c5.apply(c4.apply(c3.apply(c2.apply(self.map(ffa))))) } /** Lift a 6-argument function into cells, so the returned cell always reflects the specified function applied to the input cells' values. - Parameter C2: The type of second cell. - Parameter C3: The type of third cell. - Parameter C4: The type of fourth cell. - Parameter C5: The type of fifth cell. - Parameter C6: The type of sixth cell. - Parameter TResult: The type of the result. - Parameter f: The binary function to lift into the cells. - Parameter c2: The second cell. - Parameter c3: The third cell. - Parameter c4: The fourth cell. - Parameter c5: The fifth cell. - Parameter c6: The sixth cell. - Returns: A cell containing values resulting from the 6-argument function applied to the input cells' values. */ public func lift<C2:CellType, C3:CellType, C4:CellType, C5:CellType, C6:CellType, TResult>(_ c2: C2, c3: C3, c4: C4, c5: C5, c6: C6, f: @escaping (Element,C2.Element,C3.Element,C4.Element,C5.Element,C6.Element)->TResult) -> AnyCell<TResult> { let ffa = { a in { b in { c in { d in { e in { _f in f(a,b,c,d,e,_f) }}}}}} return c6.apply(c5.apply(c4.apply(c3.apply(c2.apply(self.map(ffa)))))) } /** Apply a value inside a cell to a function inside a cell. This is the primitive for all function lifting. - Parameter TResult: The type of the result. - Parameter C: The current CellType. - Parameter bf: The cell containing the function to apply the value to. - Returns: A cell whose value is the result of applying the current function in cell `bf` to this cell's current value. */ public func apply<TResult, C:CellType>(_ bf: C) -> AnyCell<TResult> where C.Element == (Element)->TResult { return Transaction.apply{ trans0 in let out = Stream<TResult>(keepListenersAlive: self.stream().keepListenersAlive) let outTarget = out.node let inTarget = Node<TResult>(rank: 0) let nodeTarget = inTarget.link({ _,_ in }, target: outTarget).1 var f: ((Element)->TResult)? var a: Element? let h = { (trans1: Transaction) -> Void in trans1.prioritized(out.node as INode) { trans2 throws -> Void in out.send(trans2, a: f!(a!))}} let l1 = bf.value(trans0).listen(inTarget, action: {(trans1, ff) in f = ff if a != nil { h(trans1) } }) let l2 = self.value(trans0).listen(inTarget, action: { (trans1, aa) in a = aa if f != nil { h(trans1) } }) return out.lastFiringOnly(trans0).unsafeAddCleanup([l1,l2, Listener(unlisten: { inTarget.unlink(nodeTarget) }, refs: self.refs)]).holdLazy({ bf.sampleNoTransaction()(self.sampleNoTransaction()) }) } } /** Listen for updates to the value of this cell. The returned Listener may be disposed to stop listening. - Note: This is an **OPERATIONAL** mechanism for interfacing between the world of I/O and FRP. - Parameter handler: The handler to execute for each value. - Returns: `Listener` which may be disposed to stop listening. - Remarks: No assumptions should be made about what thread the handler is called on and it should not block. Neither StreamSink<T>.send nor CellSink<T>.send may be called from the handler. They will throw an exception because this method is not meant to be used to create new primitives. If the Listener is not disposed, it will continue to listen until this cell is disposed. */ public func listen(_ handler: @escaping Handler) -> Listener { return Transaction.apply{trans in self.value(trans).listen(self.refs, handler: handler)}! } /** Transform the cell values according to the supplied function, so the returned cell's values reflect the value of the function applied to the input cell's values. - Parameter TResult: The type of values fired by the returned cell. - Parameter f: Function to apply to convert the values. It must be a pure function. - Returns: An cell which fires values transformed by f() for each value fired by this cell. */ public func map<TResult>(_ f: @escaping (Element) -> TResult) -> Cell<TResult> { let rt = Transaction.apply{ (trans: Transaction) in self.stream().map(f).hold(f(self.sample())) } return rt } public func value(_ trans1: Transaction) -> Stream<Element> { let spark = Stream<Unit>(keepListenersAlive: self.stream().keepListenersAlive) trans1.prioritized(spark.node) { trans2 in spark.send(trans2, a: Unit.value)} let initial = spark.snapshot(self) //return initial.merge(self.updates(trans1), f: { $1 }) return initial.merge(self.stream(), f: { $1 }) } } extension CellType where Element : Equatable { public func calm() -> AnyCell<Element> { let a = self.sampleNoTransaction() return AnyCell(self.stream().calm(a).hold(a)) } }
bsd-3-clause
06eea362086865f6ec7a04367ae8babe
37.875536
294
0.619728
4.017742
false
false
false
false
easyui/Alamofire
Source/SessionDelegate.swift
10
15362
// // SessionDelegate.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // 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 /// Class which implements the various `URLSessionDelegate` methods to connect various Alamofire features. open class SessionDelegate: NSObject { private let fileManager: FileManager weak var stateProvider: SessionStateProvider? var eventMonitor: EventMonitor? /// Creates an instance from the given `FileManager`. /// /// - Parameter fileManager: `FileManager` to use for underlying file management, such as moving downloaded files. /// `.default` by default. public init(fileManager: FileManager = .default) { self.fileManager = fileManager } /// Internal method to find and cast requests while maintaining some integrity checking. /// /// - Parameters: /// - task: The `URLSessionTask` for which to find the associated `Request`. /// - type: The `Request` subclass type to cast any `Request` associate with `task`. func request<R: Request>(for task: URLSessionTask, as type: R.Type) -> R? { guard let provider = stateProvider else { assertionFailure("StateProvider is nil.") return nil } return provider.request(for: task) as? R } } /// Type which provides various `Session` state values. protocol SessionStateProvider: AnyObject { var serverTrustManager: ServerTrustManager? { get } var redirectHandler: RedirectHandler? { get } var cachedResponseHandler: CachedResponseHandler? { get } func request(for task: URLSessionTask) -> Request? func didGatherMetricsForTask(_ task: URLSessionTask) func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? func cancelRequestsForSessionInvalidation(with error: Error?) } // MARK: URLSessionDelegate extension SessionDelegate: URLSessionDelegate { open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { eventMonitor?.urlSession(session, didBecomeInvalidWithError: error) stateProvider?.cancelRequestsForSessionInvalidation(with: error) } } // MARK: URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Result of a `URLAuthenticationChallenge` evaluation. typealias ChallengeEvaluation = (disposition: URLSession.AuthChallengeDisposition, credential: URLCredential?, error: AFError?) open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { eventMonitor?.urlSession(session, task: task, didReceive: challenge) let evaluation: ChallengeEvaluation switch challenge.protectionSpace.authenticationMethod { case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest, NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate: evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) #if !(os(Linux) || os(Windows)) case NSURLAuthenticationMethodServerTrust: evaluation = attemptServerTrustAuthentication(with: challenge) case NSURLAuthenticationMethodClientCertificate: evaluation = attemptCredentialAuthentication(for: challenge, belongingTo: task) #endif default: evaluation = (.performDefaultHandling, nil, nil) } if let error = evaluation.error { stateProvider?.request(for: task)?.didFailTask(task, earlyWithError: error) } completionHandler(evaluation.disposition, evaluation.credential) } #if !(os(Linux) || os(Windows)) /// Evaluates the server trust `URLAuthenticationChallenge` received. /// /// - Parameter challenge: The `URLAuthenticationChallenge`. /// /// - Returns: The `ChallengeEvaluation`. func attemptServerTrustAuthentication(with challenge: URLAuthenticationChallenge) -> ChallengeEvaluation { let host = challenge.protectionSpace.host guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, let trust = challenge.protectionSpace.serverTrust else { return (.performDefaultHandling, nil, nil) } do { guard let evaluator = try stateProvider?.serverTrustManager?.serverTrustEvaluator(forHost: host) else { return (.performDefaultHandling, nil, nil) } try evaluator.evaluate(trust, forHost: host) return (.useCredential, URLCredential(trust: trust), nil) } catch { return (.cancelAuthenticationChallenge, nil, error.asAFError(or: .serverTrustEvaluationFailed(reason: .customEvaluationFailed(error: error)))) } } #endif /// Evaluates the credential-based authentication `URLAuthenticationChallenge` received for `task`. /// /// - Parameters: /// - challenge: The `URLAuthenticationChallenge`. /// - task: The `URLSessionTask` which received the challenge. /// /// - Returns: The `ChallengeEvaluation`. func attemptCredentialAuthentication(for challenge: URLAuthenticationChallenge, belongingTo task: URLSessionTask) -> ChallengeEvaluation { guard challenge.previousFailureCount == 0 else { return (.rejectProtectionSpace, nil, nil) } guard let credential = stateProvider?.credential(for: task, in: challenge.protectionSpace) else { return (.performDefaultHandling, nil, nil) } return (.useCredential, credential, nil) } open func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { eventMonitor?.urlSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend) stateProvider?.request(for: task)?.updateUploadProgress(totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend) } open func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { eventMonitor?.urlSession(session, taskNeedsNewBodyStream: task) guard let request = request(for: task, as: UploadRequest.self) else { assertionFailure("needNewBodyStream did not find UploadRequest.") completionHandler(nil) return } completionHandler(request.inputStream()) } open func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { eventMonitor?.urlSession(session, task: task, willPerformHTTPRedirection: response, newRequest: request) if let redirectHandler = stateProvider?.request(for: task)?.redirectHandler ?? stateProvider?.redirectHandler { redirectHandler.task(task, willBeRedirectedTo: request, for: response, completion: completionHandler) } else { completionHandler(request) } } open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { eventMonitor?.urlSession(session, task: task, didFinishCollecting: metrics) stateProvider?.request(for: task)?.didGatherMetrics(metrics) stateProvider?.didGatherMetricsForTask(task) } open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { eventMonitor?.urlSession(session, task: task, didCompleteWithError: error) let request = stateProvider?.request(for: task) stateProvider?.didCompleteTask(task) { request?.didCompleteTask(task, with: error.map { $0.asAFError(or: .sessionTaskFailed(error: $0)) }) } } @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *) open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) { eventMonitor?.urlSession(session, taskIsWaitingForConnectivity: task) } } // MARK: URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { eventMonitor?.urlSession(session, dataTask: dataTask, didReceive: data) if let request = request(for: dataTask, as: DataRequest.self) { request.didReceive(data: data) } else if let request = request(for: dataTask, as: DataStreamRequest.self) { request.didReceive(data: data) } else { assertionFailure("dataTask did not find DataRequest or DataStreamRequest in didReceive") return } } open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { eventMonitor?.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) if let handler = stateProvider?.request(for: dataTask)?.cachedResponseHandler ?? stateProvider?.cachedResponseHandler { handler.dataTask(dataTask, willCacheResponse: proposedResponse, completion: completionHandler) } else { completionHandler(proposedResponse) } } } // MARK: URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes) guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } downloadRequest.updateDownloadProgress(bytesWritten: fileOffset, totalBytesExpectedToWrite: expectedTotalBytes) } open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) guard let downloadRequest = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } downloadRequest.updateDownloadProgress(bytesWritten: bytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { eventMonitor?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) guard let request = request(for: downloadTask, as: DownloadRequest.self) else { assertionFailure("downloadTask did not find DownloadRequest.") return } let (destination, options): (URL, DownloadRequest.Options) if let response = request.response { (destination, options) = request.destination(location, response) } else { // If there's no response this is likely a local file download, so generate the temporary URL directly. (destination, options) = (DownloadRequest.defaultDestinationURL(location), []) } eventMonitor?.request(request, didCreateDestinationURL: destination) do { if options.contains(.removePreviousFile), fileManager.fileExists(atPath: destination.path) { try fileManager.removeItem(at: destination) } if options.contains(.createIntermediateDirectories) { let directory = destination.deletingLastPathComponent() try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) } try fileManager.moveItem(at: location, to: destination) request.didFinishDownloading(using: downloadTask, with: .success(destination)) } catch { request.didFinishDownloading(using: downloadTask, with: .failure(.downloadedFileMoveFailed(error: error, source: location, destination: destination))) } } }
mit
f67a806f5ed64cedd51e03d0cee55b3e
44.720238
154
0.650827
6.010172
false
false
false
false
GMSLabs/Hyber-SDK-iOS
Hyber/Classes/Helpers/Network/Headers.swift
1
920
// // Headers.swift // Pods // // Created by Taras Markevych on 2/28/17. // // import UIKit import RealmSwift class Headers: NSObject { static func getHeaders() -> [String:String] { let realm = try! Realm() let date = NSDate() let timestamp = UInt64(floor(date.timeIntervalSince1970 * 1000)) let token: String? = realm.objects(Session.self).last!.mToken! let kUUID: String? = realm.objects(Session.self).first!.mSessionToken let timeString = String(timestamp) let shaPass = token! + ":" + timeString let crytped = shaPass.sha256() let headers = [ "Content-Type": "application/json", "X-Hyber-Session-Id": "\(kUUID!)", "X-Hyber-Auth-Token": "\(crytped)", "X-Hyber-Timestamp": "\(timeString)" ] HyberLogger.debug(headers) return headers } }
apache-2.0
009e3095663d690d1c6f7e6b7f9653c4
27.75
78
0.568478
3.881857
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/Extension/Date+JChat.swift
1
4673
// // CCDataExtension.swift // JChat // // Created by JIGUANG on 2017/2/16. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit let FORMAT_PAST_SHORT:String = "yyyy/MM/dd" let FORMAT_PAST_TIME:String = "ahh:mm" let FORMAT_THIS_WEEK:String = "eee ahh:mm" let FORMAT_THIS_WEEK_SHORT:String = "eee" let FORMAT_YESTERDAY:String = "ahh:mm" let FORMAT_TODAY:String = "ahh:mm" let D_MINUTE = 60.0 let D_HOUR = 3600.0 let D_DAY = 86400.0 let D_WEEK = 604800.0 let D_YEAR = 31556926.0 internal let componentFlags: NSCalendar.Unit = [.year, .month, .day, .weekday, .hour, .minute, .second, .weekdayOrdinal] extension Date { static func currentCalendar() -> Calendar{ let calendar = Calendar.autoupdatingCurrent return calendar } func isEqualToDateIgnoringTime(_ date:Date) -> Bool{ let components1:DateComponents = (Date.currentCalendar() as NSCalendar).components(componentFlags, from: self) let components2:DateComponents = (Date.currentCalendar() as NSCalendar).components(componentFlags, from: date) return (components1.year == components2.year) && (components1.month == components2.month) && ((components1).day == components2.day) } func dateByAddingDays(_ days:Int) -> Date { var dateComponents = DateComponents() dateComponents.day = days let newDate:Date = (Calendar.current as NSCalendar).date(byAdding: dateComponents, to: self, options:NSCalendar.Options(rawValue: 0))! return newDate } func dateBySubtractingDays(_ days:Int) -> Date { return self.dateByAddingDays(days * -1) } static func dateWithDaysFromNow(_ days:Int) -> Date { return Date().dateByAddingDays(days) } static func dateWithDaysBeforeNow(_ days:Int) -> Date { return Date().dateBySubtractingDays(days) } static func dateTomorrow() -> Date{ return Date.dateWithDaysFromNow(1) } static func dateYesterday() -> Date { return Date.dateWithDaysBeforeNow(1) } func isToday() -> Bool { return self.isEqualToDateIgnoringTime(Date()) } func isTomorrow() -> Bool { return self.isEqualToDateIgnoringTime(Date.dateTomorrow()) } func isYesterday() -> Bool { return self.isEqualToDateIgnoringTime(Date.dateYesterday()) } func isSameWeekAsDate(_ date:Date) -> Bool { let components1:DateComponents = (Date.currentCalendar() as NSCalendar).components(componentFlags, from: self) let components2:DateComponents = (Date.currentCalendar() as NSCalendar).components(componentFlags, from: date) if components1.weekOfYear != components2.weekOfYear { return false } return (fabs(self.timeIntervalSince(date)) < D_WEEK) } func isThisWeek() -> Bool { return self.isSameWeekAsDate(Date()) } func isThisYear() -> Bool { let calendar = NSCalendar.current let year1 = calendar.component(.year, from: Date()) let year2 = calendar.component(.year, from: self) return year1 == year2 } func conversationDate() -> String { // yy-MM-dd hh:mm // MM-dd hh:mm // 星期一 hh:mm - 7 * 24小时内 // 昨天 hh:mm - 2 * 24小时内 // 今天 hh:mm - 24小时内 let s1 = TimeInterval(self.timeIntervalSince1970) let s2 = TimeInterval(time(nil)) let dz = TimeInterval(TimeZone.current.secondsFromGMT()) let formatter = DateFormatter() // let format1 = DateFormatter.dateFormat(fromTemplate: "hh:mm", options: 0, locale: nil) ?? "hh:mm" let days1 = Int64(s1 + dz) / (24 * 60 * 60) let days2 = Int64(s2 + dz) / (24 * 60 * 60) switch days1 - days2 { case +0: // Today // formatter.dateFormat = "\(format1)" formatter.dateFormat = "hh:mm" case +1: // Tomorrow formatter.dateFormat = "'明天'" case +2 ... +7: // 2 - 7 day later formatter.dateFormat = "EEEE" case -1: formatter.dateFormat = "'昨天'" case -2: formatter.dateFormat = "'前天'" case -7 ... -2: // 2 - 7 day ago formatter.dateFormat = "EEEE" default: // Distant if self.isThisYear() { formatter.dateFormat = "MM-dd" } else { formatter.dateFormat = "yy-MM-dd" } } return formatter.string(from: self) } }
mit
ac7f45246f9dfa2b9c74e3c66a87ee72
31.125
142
0.593818
4.082966
false
false
false
false
grpc/grpc-swift
Performance/QPSBenchmark/Sources/QPSBenchmark/Runtime/Async/AsyncPingPongRequestMaker.swift
1
3355
/* * Copyright 2022, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Atomics import Foundation import GRPC import Logging import NIOCore /// Makes streaming requests and listens to responses ping-pong style. /// Iterations can be limited by config. /// Class is marked as `@unchecked Sendable` because `ManagedAtomic<Bool>` doesn't conform /// to `Sendable`, but we know it's safe. final class AsyncPingPongRequestMaker: AsyncRequestMaker, @unchecked Sendable { private let client: Grpc_Testing_BenchmarkServiceAsyncClient private let requestMessage: Grpc_Testing_SimpleRequest private let logger: Logger private let stats: StatsWithLock /// If greater than zero gives a limit to how many messages are exchanged before termination. private let messagesPerStream: Int /// Stops more requests being made after stop is requested. private let stopRequested = ManagedAtomic<Bool>(false) /// Initialiser to gather requirements. /// - Parameters: /// - config: config from the driver describing what to do. /// - client: client interface to the server. /// - requestMessage: Pre-made request message to use possibly repeatedly. /// - logger: Where to log useful diagnostics. /// - stats: Where to record statistics on latency. init( config: Grpc_Testing_ClientConfig, client: Grpc_Testing_BenchmarkServiceAsyncClient, requestMessage: Grpc_Testing_SimpleRequest, logger: Logger, stats: StatsWithLock ) { self.client = client self.requestMessage = requestMessage self.logger = logger self.stats = stats self.messagesPerStream = Int(config.messagesPerStream) } /// Initiate a request sequence to the server - in this case the sequence is streaming requests to the server and waiting /// to see responses before repeating ping-pong style. The number of iterations can be limited by config. func makeRequest() async throws { var startTime = grpcTimeNow() var messagesSent = 0 let streamingCall = self.client.makeStreamingCallCall() var responseStream = streamingCall.responseStream.makeAsyncIterator() while !self.stopRequested.load(ordering: .relaxed), self.messagesPerStream == 0 || messagesSent < self.messagesPerStream { try await streamingCall.requestStream.send(self.requestMessage) let _ = try await responseStream.next() let endTime = grpcTimeNow() self.stats.add(latency: endTime - startTime) messagesSent += 1 startTime = endTime } } /// Request termination of the request-response sequence. func requestStop() { self.logger.info("AsyncPingPongRequestMaker stop requested") // Flag stop as requested - this will prevent any more requests being made. self.stopRequested.store(true, ordering: .relaxed) } }
apache-2.0
acd01cb206bb6a6741e12711f2d7ce4d
38.470588
123
0.734128
4.491299
false
true
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/Custom/EmptyDataSetView.swift
1
2931
// // EmptyDataSetView.swift // Inbbbox // // Created by Peter Bruz on 23/03/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit class EmptyDataSetView: UIView { fileprivate let descriptionLabel = UILabel.newAutoLayout() fileprivate let imageView = UIImageView.newAutoLayout() fileprivate var didUpdateConstraints = false override init(frame: CGRect) { super.init(frame: frame) imageView.image = UIImage(named: "logo-empty") imageView.contentMode = .scaleAspectFit addSubview(imageView) descriptionLabel.numberOfLines = 0 descriptionLabel.textAlignment = .center addSubview(descriptionLabel) } @available(*, unavailable, message: "Use init(frame:) instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { if !didUpdateConstraints { didUpdateConstraints = true imageView.autoAlignAxis(toSuperviewAxis: .vertical) imageView.autoAlignAxis(.horizontal, toSameAxisOf: imageView.superview!, withOffset: -90) imageView.autoSetDimensions(to: CGSize(width: 140, height: 140)) descriptionLabel.autoAlignAxis(toSuperviewAxis: .vertical) descriptionLabel.autoPinEdge(.top, to: .bottom, of: imageView, withOffset: 40) descriptionLabel.autoPinEdge(toSuperviewMargin: .leading) descriptionLabel.autoPinEdge(toSuperviewMargin: .trailing) } super.updateConstraints() } func setDescriptionText(firstLocalizedString: String, attachmentImage: UIImage?, imageOffset: CGPoint, lastLocalizedString: String) { descriptionLabel.attributedText = { let compoundAttributedString = NSMutableAttributedString.emptyDataSetStyledString(firstLocalizedString) let textAttachment: NSTextAttachment = NSTextAttachment() textAttachment.image = attachmentImage if let image = textAttachment.image { textAttachment.bounds = CGRect(origin: imageOffset, size: image.size) } let attributedStringWithImage: NSAttributedString = NSAttributedString(attachment: textAttachment) compoundAttributedString.append(attributedStringWithImage) let lastAttributedString = NSMutableAttributedString.emptyDataSetStyledString(lastLocalizedString) compoundAttributedString.append(lastAttributedString) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center compoundAttributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: compoundAttributedString.length)) return compoundAttributedString }() } }
gpl-3.0
a2ba4451b4e286cff85afc3711a6ea34
37.552632
115
0.690444
5.790514
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Models/Ingredient.swift
1
533
// // Ingredient.swift // WeeklyFoodPlan // // Created by vulgur on 2016/12/17. // Copyright © 2016年 MAD. All rights reserved. // import UIKit import RealmSwift class Ingredient: Object { // dynamic var id = UUID().uuidString dynamic var name: String = "" dynamic var neededCount = 0 dynamic var remainedCount = 0 dynamic var freshDays = 0 let nutritions = List<Nutrition>() dynamic var imagePath: String? override static func primaryKey() -> String? { return "name" } }
mit
1680a49f1e2871d9d17290d3207217b7
20.2
50
0.64717
4.015152
false
false
false
false