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
toshiapp/toshi-ios-client
Toshi/Views/PushedSearchHeaderView.swift
1
7445
// Copyright (c) 2018 Token Browser, Inc // // 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 protocol PushedSearchHeaderDelegate: class { func searchHeaderWillBeginEditing(_ headerView: PushedSearchHeaderView) func searchHeaderWillEndEditing(_ headerView: PushedSearchHeaderView) func searchHeaderDidReceiveRightButtonEvent(_ headerView: PushedSearchHeaderView) func searchHeaderViewDidReceiveBackEvent(_ headerView: PushedSearchHeaderView) func searchHeaderViewDidUpdateSearchText(_ headerView: PushedSearchHeaderView, _ searchText: String) } final class PushedSearchHeaderView: UIView { static let headerHeight: CGFloat = 56 weak var delegate: PushedSearchHeaderDelegate? var rightButtonTitle: String = Localized.cancel_action_title { didSet { rightButton.setTitle(rightButtonTitle, for: .normal) } } var hidesBackButtonOnSearch: Bool = true private let searchTextFieldBackgroundViewHeight: CGFloat = 36 var searchPlaceholder: String? { didSet { searchTextField.placeholder = searchPlaceholder } } func setButtonEnabled(_ enabled: Bool) { rightButton.isEnabled = enabled } private lazy var backButton: UIButton = { let view = UIButton() view.setTitleColor(Theme.tintColor, for: .normal) view.size(CGSize(width: .defaultButtonHeight, height: .defaultButtonHeight)) view.setImage(ImageAsset.web_back.withRenderingMode(.alwaysTemplate), for: .normal) view.tintColor = Theme.tintColor view.addTarget(self, action: #selector(self.didTapBackButton), for: .touchUpInside) view.contentHorizontalAlignment = .left return view }() private(set) lazy var searchTextField: UITextField = { let textField = UITextField() textField.borderStyle = .none textField.delegate = self textField.layer.cornerRadius = 5 textField.tintColor = Theme.tintColor textField.returnKeyType = .go textField.leftView = magnifyingGlassImageView textField.leftViewMode = .always return textField }() private lazy var magnifyingGlassImageView: UIImageView = { let magnifyingGlassImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: searchTextFieldBackgroundViewHeight, height: searchTextFieldBackgroundViewHeight)) magnifyingGlassImageView.image = ImageAsset.search_users magnifyingGlassImageView.contentMode = .center return magnifyingGlassImageView }() private lazy var searchTextFieldBackgroundView: UIView = { let backgroundView = UIView() backgroundView.backgroundColor = Theme.searchBarColor backgroundView.layer.cornerRadius = 5 return backgroundView }() private lazy var rightButton: UIButton = { let rightButton = UIButton() rightButton.setTitleColor(Theme.tintColor, for: .normal) rightButton.setTitleColor(Theme.greyTextColor, for: .disabled) rightButton.addTarget(self, action: #selector(didTapCancelButton), for: .touchUpInside) rightButton.setContentCompressionResistancePriority(.required, for: .horizontal) rightButton.setContentHuggingPriority(.required, for: .horizontal) return rightButton }() private lazy var stackView: UIStackView = { let stackView = UIStackView() stackView.axis = .horizontal stackView.distribution = .fillProportionally return stackView }() required init?(coder _: NSCoder) { fatalError("init(coder:) is not implemented") } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = Theme.viewBackgroundColor addSubviewsAndConstraints() } @discardableResult override func becomeFirstResponder() -> Bool { return searchTextField.becomeFirstResponder() } private func addSubviewsAndConstraints() { addSubview(stackView) stackView.left(to: self) stackView.right(to: self) stackView.bottom(to: self) stackView.height(PushedSearchHeaderView.headerHeight) stackView.alignment = .center stackView.addSpacerView(with: .defaultMargin) stackView.addArrangedSubview(backButton) stackView.addArrangedSubview(searchTextFieldBackgroundView) searchTextFieldBackgroundView.height(searchTextFieldBackgroundViewHeight) searchTextFieldBackgroundView.addSubview(searchTextField) searchTextField.leftToSuperview() searchTextField.topToSuperview() searchTextField.bottomToSuperview() searchTextField.right(to: searchTextFieldBackgroundView, offset: -.smallInterItemSpacing) stackView.addSpacing(.smallInterItemSpacing, after: searchTextFieldBackgroundView) stackView.addArrangedSubview(rightButton) stackView.addSpacerView(with: .defaultMargin) let separator = BorderView() addSubview(separator) separator.leftToSuperview() separator.rightToSuperview() separator.bottomToSuperview() separator.addHeightConstraint() rightButton.isHidden = true } private func adjustToSearching(isSearching: Bool) { layoutIfNeeded() rightButton.isHidden = !isSearching guard hidesBackButtonOnSearch else { return } backButton.isHidden = isSearching UIView.animate(withDuration: 0.3) { self.backButton.alpha = isSearching ? 0 : 1 self.layoutIfNeeded() } } @objc private func didTapCancelButton() { searchTextField.resignFirstResponder() searchTextField.text = nil delegate?.searchHeaderDidReceiveRightButtonEvent(self) } @objc private func didTapBackButton() { delegate?.searchHeaderViewDidReceiveBackEvent(self) } } extension PushedSearchHeaderView: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { adjustToSearching(isSearching: true) delegate?.searchHeaderWillBeginEditing(self) return true } func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { adjustToSearching(isSearching: false) delegate?.searchHeaderWillEndEditing(self) return true } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let text = textField.text, let textRange = Range(range, in: text) { let updatedText = text.replacingCharacters(in: textRange, with: string) delegate?.searchHeaderViewDidUpdateSearchText(self, updatedText) } return true } }
gpl-3.0
7dc39cb28772b1bd0f808c2ec9435923
34.117925
166
0.700067
5.406681
false
false
false
false
guillermo-ag-95/App-Development-with-Swift-for-Students
4 - Tables and Persistence/6 - Intermediate Table Views/lab/FavoriteBook/FavoriteBook/Book.swift
1
1488
import Foundation class Book: NSObject, NSCoding { struct PropertyKeys { static let title = "title" static let author = "author" static let genre = "genre" static let length = "length" } let title: String let author: String let genre: String let length: String override var description: String { return "\(title) is written by \(author) in the \(genre) genre and is \(length) pages long" } init(title: String, author: String, genre: String, length: String) { self.title = title self.author = author self.genre = genre self.length = length } required convenience init?(coder aDecoder: NSCoder) { guard let title = aDecoder.decodeObject(forKey: PropertyKeys.title) as? String, let author = aDecoder.decodeObject(forKey: PropertyKeys.author) as? String, let genre = aDecoder.decodeObject(forKey: PropertyKeys.genre) as? String, let length = aDecoder.decodeObject(forKey: PropertyKeys.length) as? String else {return nil} self.init(title: title, author: author, genre: genre, length: length) } func encode(with aCoder: NSCoder) { aCoder.encode(title, forKey: PropertyKeys.title) aCoder.encode(author, forKey: PropertyKeys.author) aCoder.encode(genre, forKey: PropertyKeys.genre) aCoder.encode(length, forKey: PropertyKeys.length) } }
mit
55490948f31c2ca91311350f79b8227b
32.066667
104
0.633065
4.522796
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/System/FancyAlertViewController+NotificationPrimer.swift
1
6375
extension FancyAlertViewController { private struct Strings { static let firstAlertTitleText = NSLocalizedString("Stay in the loop", comment: "Title of the first alert preparing users to grant permission for us to send them push notifications.") static let firstAlertBodyText = NSLocalizedString("We'll notify you when you get new followers, comments, and likes. Would you like to allow push notifications?", comment: "Body text of the first alert preparing users to grant permission for us to send them push notifications.") static let firstAllowButtonText = NSLocalizedString("Allow notifications", comment: "Allow button title shown in alert preparing users to grant permission for us to send them push notifications.") static let secondAlertTitleText = NSLocalizedString("Get your notifications faster", comment: "Title of the second alert preparing users to grant permission for us to send them push notifications.") static let secondAlertBodyText = NSLocalizedString("Learn about new comments, likes, and follows in seconds.", comment: "Body text of the first alert preparing users to grant permission for us to send them push notifications.") static let secondAllowButtonText = NSLocalizedString("Allow push notifications", comment: "Allow button title shown in alert preparing users to grant permission for us to send them push notifications.") static let notNowText = NSLocalizedString("Not now", comment: "Not now button title shown in alert preparing users to grant permission for us to send them push notifications.") } private struct Analytics { static let locationKey = "location" static let alertKey = "alert" } /// Create the fancy alert controller for the notification primer /// /// - Parameter approveAction: block to call when approve is tapped /// - Returns: FancyAlertViewController of the primer static func makeNotificationAlertController(titleText: String?, bodyText: String?, allowButtonText: String, seenEvent: WPAnalyticsEvent, allowEvent: WPAnalyticsEvent, noEvent: WPAnalyticsEvent, approveAction: @escaping ((_ controller: FancyAlertViewController) -> Void)) -> FancyAlertViewController { let allowButton = ButtonConfig(allowButtonText) { controller, _ in approveAction(controller) WPAnalytics.track(allowEvent, properties: [Analytics.locationKey: Analytics.alertKey]) } let dismissButton = ButtonConfig(Strings.notNowText) { controller, _ in defer { WPAnalytics.track(noEvent, properties: [Analytics.locationKey: Analytics.alertKey]) } controller.dismiss(animated: true) } let image = UIImage(named: "wp-illustration-stay-in-the-loop") let config = FancyAlertViewController.Config(titleText: titleText, bodyText: bodyText, headerImage: image, dividerPosition: .bottom, defaultButton: allowButton, cancelButton: dismissButton, appearAction: { WPAnalytics.track(seenEvent, properties: [Analytics.locationKey: Analytics.alertKey]) }, dismissAction: {}) let controller = FancyAlertViewController.controllerWithConfiguration(configuration: config) return controller } static func makeNotificationPrimerAlertController(approveAction: @escaping ((_ controller: FancyAlertViewController) -> Void)) -> FancyAlertViewController { return makeNotificationAlertController(titleText: Strings.firstAlertTitleText, bodyText: Strings.firstAlertBodyText, allowButtonText: Strings.firstAllowButtonText, seenEvent: .pushNotificationsPrimerSeen, allowEvent: .pushNotificationsPrimerAllowTapped, noEvent: .pushNotificationsPrimerNoTapped, approveAction: approveAction) } static func makeNotificationSecondAlertController(approveAction: @escaping ((_ controller: FancyAlertViewController) -> Void)) -> FancyAlertViewController { return makeNotificationAlertController(titleText: Strings.secondAlertTitleText, bodyText: Strings.secondAlertBodyText, allowButtonText: Strings.secondAllowButtonText, seenEvent: .secondNotificationsAlertSeen, allowEvent: .secondNotificationsAlertAllowTapped, noEvent: .secondNotificationsAlertNoTapped, approveAction: approveAction) } } // MARK: - User Defaults @objc extension UserDefaults { private enum Keys: String { case notificationPrimerAlertWasDisplayed = "NotificationPrimerAlertWasDisplayed" case notificationsTabAccessCount = "NotificationsTabAccessCount" } var notificationPrimerAlertWasDisplayed: Bool { get { bool(forKey: Keys.notificationPrimerAlertWasDisplayed.rawValue) } set { set(newValue, forKey: Keys.notificationPrimerAlertWasDisplayed.rawValue) } } var notificationsTabAccessCount: Int { get { integer(forKey: Keys.notificationsTabAccessCount.rawValue) } set { set(newValue, forKey: Keys.notificationsTabAccessCount.rawValue) } } }
gpl-2.0
9d829587246a82c6f25f7648f6e948f1
59.141509
287
0.592627
6.781915
false
true
false
false
xxxAIRINxxx/Cmg
Sources/Gradient.swift
1
4527
// // Gradient.swift // Cmg // // Created by xxxAIRINxxx on 2016/02/20. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import Foundation import UIKit import CoreImage public struct GaussianGradient: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputRadiusAvailable, InputColor0Available, InputColor1Available { public let filter: CIFilter = CIFilter(name: "CIGaussianGradient")! public let inputCenter: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public let inputRadius: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputRadius = ScalarInput(filter: self.filter, key: kCIInputRadiusKey) self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor0, self.inputColor1, self.inputRadius ] } } public struct LinearGradient: InputImageUnusable, FilterInputCollectionType, InputPoint0Available, InputPoint1Available, InputColor0Available, InputColor1Available { public let filter: CIFilter = CIFilter(name: "CILinearGradient")! public var inputPoint0: VectorInput public var inputPoint1: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public init(imageSize: CGSize) { self.inputPoint0 = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputPoint0") self.inputPoint1 = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputPoint1") self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") } public func inputs() -> [FilterInputable] { return [ self.inputPoint0, self.inputPoint1, self.inputColor0, self.inputColor1 ] } } public struct RadialGradient: InputImageUnusable, FilterInputCollectionType, InputCenterAvailable, InputRadius0Available, InputRadius1Available, InputColor0Available, InputColor1Available { public let filter: CIFilter = CIFilter(name: "CIRadialGradient")! public let inputCenter: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public let inputRadius0: ScalarInput public let inputRadius1: ScalarInput public init(imageSize: CGSize) { self.inputCenter = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, kCIInputCenterKey) self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") self.inputRadius0 = ScalarInput(filter: self.filter, key: "inputRadius0") self.inputRadius1 = ScalarInput(filter: self.filter, key: "inputRadius1") } public func inputs() -> [FilterInputable] { return [ self.inputCenter, self.inputColor0, self.inputColor1, self.inputRadius0, self.inputRadius1 ] } } public struct SmoothLinearGradient: InputImageUnusable, FilterInputCollectionType, InputPoint0Available, InputPoint1Available, InputColor0Available, InputColor1Available { public let filter: CIFilter = CIFilter(name: "CISmoothLinearGradient")! public var inputPoint0: VectorInput public var inputPoint1: VectorInput public let inputColor0: ColorInput public let inputColor1: ColorInput public init(imageSize: CGSize) { self.inputPoint0 = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputPoint0") self.inputPoint1 = VectorInput(.position(maximumSize: Vector2(size: imageSize)), self.filter, "inputPoint1") self.inputColor0 = ColorInput(filter: self.filter, key: "inputColor0") self.inputColor1 = ColorInput(filter: self.filter, key: "inputColor1") } public func inputs() -> [FilterInputable] { return [ self.inputPoint0, self.inputPoint1, self.inputColor0, self.inputColor1 ] } }
mit
553385957f5a77af296812d507245416
34.920635
120
0.693548
4.739267
false
false
false
false
YauheniYarotski/APOD
APOD/AnimationControllers/ModalDismissAnimationController.swift
1
2514
// // ModalDismissAnimationController.swift // APOD // // Created by Yauheni Yarotski on 6/7/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit class ModalDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return ModalPresentAnimationController.kTransitionDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let apodDescriptionVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? ApodDescriptionVC, let apodVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? ApodVC else {return} let containerView = transitionContext.containerView let topLayoutHight = apodDescriptionVC.topLayoutGuide.length let dateBarHight = apodDescriptionVC.apodDateBar.frame.height let apodTitleBarHight = apodDescriptionVC.titleView.frame.height // if let topFadeView = containerView.viewWithTag(ModalPresentAnimationController.kTopFadeViewTag) { // topFadeView.removeFromSuperview() // } UIView.animate( withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: [.allowUserInteraction, .curveEaseOut], animations: { if let alphaView = containerView.viewWithTag(ModalPresentAnimationController.kAlphaViewTag) { alphaView.alpha = 0 } apodDescriptionVC.view.frame.origin.y = containerView.bounds.size.height - topLayoutHight - dateBarHight - apodTitleBarHight apodVC.dateView.shareButton.alpha = 1 apodVC.dateView.infoButton.alpha = 1 apodDescriptionVC.titleView.likesView.alpha = 1 }, completion: {_ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) if transitionContext.transitionWasCancelled { apodVC.dateView.shareButton.alpha = 0 apodVC.dateView.infoButton.alpha = 0 apodDescriptionVC.titleView.likesView.alpha = 0 } else { apodVC.titleView.isHidden = false } }) } }
mit
ed4620651dd08cc62bb3777206300c9a
41.59322
142
0.664544
5.381156
false
false
false
false
apple/swift
test/SILGen/newtype.swift
5
5899
// RUN: %empty-directory(%t) // RUN: %build-silgen-test-overlays // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk -I %t) -module-name newtype -I %S/Inputs -I %S/Inputs -I %S/../IDE/Inputs/custom-modules -enable-objc-interop -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-RAW // RUN: %target-swift-emit-sil(mock-sdk: %clang-importer-sdk -I %t) -module-name newtype -I %S/Inputs -I %S/Inputs -I %S/../IDE/Inputs/custom-modules -enable-objc-interop -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-CANONICAL // REQUIRES: objc_interop import Newtype // CHECK-CANONICAL-LABEL: sil hidden @$s7newtype17createErrorDomain{{[_0-9a-zA-Z]*}}F // CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String) func createErrorDomain(str: String) -> ErrorDomain { // CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]]) // CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString) return ErrorDomain(rawValue: str) } // CHECK-RAW-LABEL: sil shared [transparent] [serialized] [ossa] @$sSo14SNTErrorDomaina8rawValueABSS_tcfC // CHECK-RAW: bb0([[STR:%[0-9]+]] : @owned $String, // CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain } // CHECK-RAW: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK-RAW: [[SELF_BOX_LIFETIME:%[0-9]+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]] // CHECK-RAW: [[PB_BOX:%[0-9]+]] = project_box [[SELF_BOX_LIFETIME]] // CHECK-RAW: [[BORROWED_STR:%.*]] = begin_borrow [lexical] [[STR]] // CHECK-RAW: [[COPIED_STR:%.*]] = copy_value [[BORROWED_STR]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-RAW: [[BORROWED_COPIED_STR:%.*]] = begin_borrow [[COPIED_STR]] // CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[BORROWED_COPIED_STR]]) // CHECK-RAW: end_borrow [[BORROWED_COPIED_STR]] // CHECK-RAW: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[WRITE]] // CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]] // CHECK-RAW: end_borrow [[BORROWED_STR]] func getRawValue(ed: ErrorDomain) -> String { return ed.rawValue } // CHECK-RAW-LABEL: sil shared [serialized] [ossa] @$sSo14SNTErrorDomaina8rawValueSSvg // CHECK-RAW: bb0([[SELF:%[0-9]+]] : @guaranteed $ErrorDomain): // CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue // CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // CHECK-RAW: [[OPT_STORED_VALUE_COPY:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[STORED_VALUE_COPY]] // CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thin String.Type // CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OPT_STORED_VALUE_COPY]], [[STRING_META]]) // CHECK-RAW: return [[STRING_RESULT]] class ObjCTest { // CHECK-RAW-LABEL: sil hidden [ossa] @$s7newtype8ObjCTestC19optionalPassThroughySo14SNTErrorDomainaSgAGF : $@convention(method) (@guaranteed Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> { // CHECK-RAW: sil private [thunk] [ossa] @$s7newtype8ObjCTestC19optionalPassThroughySo14SNTErrorDomainaSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> @autoreleased Optional<ErrorDomain> { @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { return ed } // CHECK-RAW-LABEL: sil hidden [ossa] @$s7newtype8ObjCTestC18integerPassThroughySo5MyIntaAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt { // CHECK-RAW: sil private [thunk] [ossa] @$s7newtype8ObjCTestC18integerPassThroughySo5MyIntaAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt { @objc func integerPassThrough(_ ed: MyInt) -> MyInt { return ed } } // These use a bridging conversion with a specialization of a generic witness. // CHECK-RAW-LABEL: sil hidden [ossa] @$s7newtype15bridgeToNewtypeSo8MyStringayF func bridgeToNewtype() -> MyString { // CHECK-RAW: [[STRING:%.*]] = apply // CHECK-RAW: [[TO_NS:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-RAW: [[BORROW:%.*]] = begin_borrow [[STRING]] // CHECK-RAW: [[NS:%.*]] = apply [[TO_NS]]([[BORROW]]) // CHECK-RAW: [[TO_MY:%.*]] = function_ref @$ss20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE026_unconditionallyBridgeFromD1CyxAD_01_D5CTypeQZSgFZ : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@guaranteed Optional<τ_0_0.RawValue._ObjectiveCType>, @thick τ_0_0.Type) // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[NS]] // CHECK-RAW: [[META:%.*]] = metatype $@thick MyString.Type // CHECK-RAW: apply [[TO_MY]]<MyString>({{.*}}, [[OPTNS]], [[META]]) return "foo" as NSString as MyString } // CHECK-RAW-LABEL: sil hidden [ossa] @$s7newtype17bridgeFromNewtype6stringSSSo8MyStringa_tF func bridgeFromNewtype(string: MyString) -> String { // CHECK-RAW: [[FROM_MY:%.*]] = function_ref @$ss20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE09_bridgeToD1CAD_01_D5CTypeQZyF : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@in_guaranteed τ_0_0) -> @owned τ_0_0.RawValue._ObjectiveCType // CHECK-RAW: [[NS:%.*]] = apply [[FROM_MY]]<MyString>( // CHECK-RAW: [[FROM_NS:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt, [[NS]] // CHECK-RAW: [[META:%.*]] = metatype $@thin String.Type // CHECK-RAW: apply [[FROM_NS]]([[OPTNS]], [[META]]) return string as NSString as String }
apache-2.0
c7d03ea4d91b1f63c6d6fe4b5ac96da9
66.689655
343
0.69044
3.374785
false
true
false
false
lorentey/swift
test/stdlib/Accelerate_Quadrature.swift
8
13761
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var AccelerateQuadratureTests = TestSuite("Accelerate_Quadrature") //===----------------------------------------------------------------------===// // // Quadrature Tests // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { func vectorExp(x: UnsafeBufferPointer<Double>, y: UnsafeMutableBufferPointer<Double>) { let radius: Double = 12.5 for i in 0 ..< x.count { y[i] = sqrt(radius * radius - pow(x[i] - radius, 2)) } } AccelerateQuadratureTests.test("Quadrature/QNG") { var diameter: Double = 25 // New API: Scalar let quadrature = Quadrature(integrator: .nonAdaptive, absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .nonAdaptive, absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QNG, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 0, max_intervals: 0) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError: Double = 0 let legacyResult = quadrature_integrate(&integrateFunction, 0.0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized non-adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Non-adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/QAGS") { var diameter: Double = 25 // New API let quadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .adaptiveWithSingularities(maxIntervals: 11), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAGS, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 0, max_intervals: 11) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError = Double(0) let legacyResult = quadrature_integrate(&integrateFunction, 0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized adaptive with singularities integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Adaptive with singularities integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/QAG") { var diameter: Double = 25 // New API let quadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, maxIntervals: 7), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let result = quadrature.integrate(over: 0.0 ... diameter) { x in let radius: Double = diameter * 0.5 return sqrt(radius * radius - pow(x - radius, 2)) } // New API: Vectorized let vQuadrature = Quadrature(integrator: .adaptive(pointsPerInterval: .sixtyOne, maxIntervals: 7), absoluteTolerance: 1.0e-8, relativeTolerance: 1.0e-2) let vRresult = vQuadrature.integrate(over: 0.0 ... diameter, integrand: vectorExp) // Legacy API var integrateFunction: quadrature_integrate_function = { return quadrature_integrate_function( fun: { (arg: UnsafeMutableRawPointer?, n: Int, x: UnsafePointer<Double>, y: UnsafeMutablePointer<Double> ) in guard let diameter = arg?.load(as: Double.self) else { return } let r = diameter * 0.5 (0 ..< n).forEach { i in y[i] = sqrt(r * r - pow(x[i] - r, 2)) } }, fun_arg: &diameter) }() var options = quadrature_integrate_options(integrator: QUADRATURE_INTEGRATE_QAG, abs_tolerance: 1.0e-8, rel_tolerance: 1.0e-2, qag_points_per_interval: 61, max_intervals: 7) var status = QUADRATURE_SUCCESS var legacyEstimatedAbsoluteError = Double(0) let legacyResult = quadrature_integrate(&integrateFunction, 0, diameter, &options, &status, &legacyEstimatedAbsoluteError, 0, nil) switch result { case .success(let integralResult, let estimatedAbsoluteError): expectEqual(integralResult, legacyResult) expectEqual(estimatedAbsoluteError, legacyEstimatedAbsoluteError) switch vRresult { case .success(let vIntegralResult, let vEstimatedAbsoluteError): expectEqual(integralResult, vIntegralResult) expectEqual(estimatedAbsoluteError, vEstimatedAbsoluteError) case .failure(_): expectationFailure("Vectorized adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } case .failure( _): expectationFailure("Adaptive integration failed.", trace: "", stackTrace: SourceLocStack()) } } AccelerateQuadratureTests.test("Quadrature/ToleranceProperties") { var quadrature = Quadrature(integrator: .qng, absoluteTolerance: 1, relativeTolerance: 2) expectEqual(quadrature.absoluteTolerance, 1) expectEqual(quadrature.relativeTolerance, 2) quadrature.absoluteTolerance = 101 quadrature.relativeTolerance = 102 expectEqual(quadrature.absoluteTolerance, 101) expectEqual(quadrature.relativeTolerance, 102) } AccelerateQuadratureTests.test("Quadrature/QAGPointsPerInterval") { expectEqual(Quadrature.QAGPointsPerInterval.fifteen.points, 15) expectEqual(Quadrature.QAGPointsPerInterval.twentyOne.points, 21) expectEqual(Quadrature.QAGPointsPerInterval.thirtyOne.points, 31) expectEqual(Quadrature.QAGPointsPerInterval.fortyOne.points, 41) expectEqual(Quadrature.QAGPointsPerInterval.fiftyOne.points, 51) expectEqual(Quadrature.QAGPointsPerInterval.sixtyOne.points, 61) } AccelerateQuadratureTests.test("Quadrature/ErrorDescription") { let a = Quadrature.Error(quadratureStatus: QUADRATURE_ERROR) expectEqual(a.errorDescription, "Generic error.") let b = Quadrature.Error(quadratureStatus: QUADRATURE_INVALID_ARG_ERROR) expectEqual(b.errorDescription, "Invalid Argument.") let c = Quadrature.Error(quadratureStatus: QUADRATURE_INTERNAL_ERROR) expectEqual(c.errorDescription, "This is a bug in the Quadrature code, please file a bug report.") let d = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_MAX_EVAL_ERROR) expectEqual(d.errorDescription, "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions.") let e = Quadrature.Error(quadratureStatus: QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR) expectEqual(e.errorDescription, "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval.") } } runAllTests()
apache-2.0
599c8541b134cf89eca71325cc7e51c3
43.390323
156
0.477291
5.562247
false
true
false
false
orta/Swift-at-Artsy
Beginners/Lesson Two/Lesson Two.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
1
12630
import Foundation /*: Alright, lesson 2! Note that most of the examples in this lesson come from [real code](https://github.com/artsy/eigen/blob/41b00f6fe497de9e902315104089370dea417017/Artsy/Views/Artwork/ARArtworkActionsView.m#L325) we use in Artsy's app. Neat! ### Overview of last week * Any lines beginning with `//` are not classed as code, they're _comments_, and are ignored by the computer. * We can make a named reference to a number, or a collection of characters - these are called variables. In swift we write that as `var something = 1`. * We can do logic on these variables by using `if` statements. They let us execute code inside some brackets only when the code inside the `if` is true. * We looked at using `print("thing")` to send text to a user of the program. * Then we looked at `for in` loops, as a way of running code within brackets multiple times. So the main topics we're going to cover today are arrays and logic, and then we'll look at types. ### Arrays Think about the things we learned last week: things in Swift can be integer numbers like `13` or `42`, they can be decimal numbers like `0.5` or `3.14159`, and they can be strings like `"Hello, Artsy!"`. These are called _types_. The next type we're going to cover is the `Array` type. An array is a special kind of type because it's a _container_ for other things. An array is a list. It can be a list of numbers, or a list of strings, it can be a list of other lists! Let's see what an array of the numbers one through five looks like. */ [1, 2, 3, 4, 5] /*: Cool! This is a list of integers. We can make a list of strings, too: */ ["Ash", "Eloy", "Maxim", "Orta", "Sarah"] /*: That's an array of the Artsy mobile team members' names. Cool! And just like the other types we learned about last week, arrays can be stored in variables. */ let names = ["Ash", "Eloy", "Maxim", "Orta", "Sarah"] /*: Arrays can be used to store anything; in Artsy, we store things like an artist's artworks in an array. And remember `for in` loops? Where we had `for in 0..<10`? Well we can do `for in` loops with arrays, too: */ for number in [1, 2, 3, 4, 5] { print(number) } /*: We can combine variables and loops together; remember that a variable can be used anywhere a regular value can be. If we wanted to say "hello" to everyone on Artsy's mobile team, we could write the following: */ for name in names { print("Hello, \(name)!") } /*: When Artsy shows users the Artist page, we have the artist's artworks stored in a variable. We use `for in` loops to loop over the array containing the those artworks in order to show them to the user. To recap: arrays are a special kind of type because they can contain multiple values. But they can be used in variables like normal types, and they can also be used in `for in` loops. Cool! ### Bools When we think of how to store data, we can think about how many values can be stored in a type. There are infinite combinations of letters, so a string variable could contain _anything_. Similar with numbers – the value of a number could be anything! But what about other types, are there any that you can think of that have a _limited_ number of values? There is such a type, called a bool (or "boolean"). Bool values are pretty easy to work with because they can only be either `true` or `false`. */ var isArtworkForSale = true var isArtworkOnHold = false /*: Swift knows that a bool can only be true or false, unlike with numbers or strings or arrays, which could be anything. If we tried to store the string `"maybe"` in a bool, Swift wouldn't let us. ### Iffy Logic Ok, we have two variables. Variables work really nicely with `if` statements. */ if isArtworkForSale { // Show the "Inquire" button print("Click to Inquire") } /*: This will check if `isArtworkForSale` is true, and if so it would show the inquire button. We can see if an artwork is _not_ for sale, too: */ if isArtworkForSale == false { print("Artwork is not inquirable") } /*: `if` statements can be powerful. We've been using only the simplest part so far – next we're going to look at `else`, which bolts on to an `if` and provides a way of running some code when the `if` fails. */ if isArtworkForSale { print("Click to Inquire") } else { print("Artwork is not inquirable") } /*: So what we're looking at, in plain English: _if the artwork is for sale, present the inquire button, otherwise say the artwork isn't for sale_. We can use an `if` and an ` else` statement to represent very complicated logic, but `if`s can do one more thing. Let's introduce a third variable into our mix. It's possible that an artwork can be on hold, too: */ isArtworkOnHold = false /*: Let's update our `if` statements. */ if isArtworkForSale { print("Click to Inquire") } else if isArtworkOnHold { print("Artwork is on hold, try asking nicely") } else { print("Artwork is not inquirable") } /*: This is an `else if` statement. It allows programmers to keep some of the logic in `if` statements manageable. Let's try say this in English: * If the artwork is for sale, show the inquire button. * Else if it's on hold, tell the user it's on hold. * Otherwise, tell the user it's not inquirable. These few key words give us enough options to map out a lot of really complicated cases. However, it's not the only tool in our belt. We'll talk about Boolean Logic after the break. ### Gates Anyone know why we call a `true`/`false` switch a `Bool`? They're named after a 19th century mathematician who was totally into Algebra. Anyone who has touched electronics will have heard of logic gates. Bools operate on the same principal. We want to represent the case when the artwork is for sale _and_ the artwork price is known. To do this we want to use the AND operator, named after the AND gate, and symbolized as `&&`. */ var isArtworkPriceKnown = true var showPriceLabel = isArtworkForSale && isArtworkPriceKnown /*: So now we have a new `Bool` that is only true when the artwork is both for sale _and_ we know its price. Let's try to integrate this into our `if` statements. */ if isArtworkForSale { print("Click to Inquire") } else if showPriceLabel { print("The artwork costs a million dollars") } else if isArtworkOnHold { print("Artwork is on hold, try asking nicely") } else { print("Artwork is not inquirable") } /*: You might notice that the code above prints "Click to Inquire" instead of the artwork's price. Why? Well, let's interpret our code in English: * If the artwork is for sale, show the inquire button. * Else if we have a price, show the price label. * Else if it's on hold, tell the user it's on hold. * Otherwise, tell the user it's not inquirable. OK. So the first `if` is not letting our first `else` get through. This is a good time as any to have a think about something as fungible as _code quality_. Programmers spend much more time _reading_ code than _writing_ code. So it's worth taking the time to make sure it reads really nicely. */ if isArtworkForSale { print("Click to Inquire") if showPriceLabel { print("The artwork costs a million dollars") } else if isArtworkOnHold { print("Artwork is on hold, try asking nicely") } } else { print("Artwork is not inquirable") } /*: We can also have code that checks if something _or_ something else is true. */ var unlikelyToBuyThis = isArtworkOnHold || (isArtworkForSale == false) /*: `||` is the OR operator, and it's true if either the left or right side are true. You can see how we combine it with comparing to `false`, too. ### Multiple States of Mind We have a `Bool` and it can represent one of two states. We have numbers and strings that can represent an infinite number of states. What we're looking for is something that can be a switch between a finite number of states. When we modelled our artwork variables above to represent the for sale availability, we used `Bool`s. This makes sense because it's pretty intuitive that an artwork is either sold or not (`true` or `false`). */ // Representing Artwork Availability isArtworkForSale = true /*: However, then someone tells you that the artwork is on hold. You think, "ok, lets add a 'isArtworkOnHold'" */ isArtworkOnHold = true /*: Well now you can have an Artwork that is on hold, and for sale. This is possible, but feels weird. Think about this: using two bools, we could have a situation like this: */ isArtworkOnHold = true isArtworkForSale = false /*: That doesn't make a lot of sense, how can it be on hold _and_ for sale? Wait, an artwork can also be _sold_. Ouch, another `Bool`: */ var isArtworkSold = true /*: OK, now we can end up in a _really_ strange place. With all these bools, we could end up with competing logic, e.g.: artwork is for sale and it's on hold and it's sold. Not cool. The reason this feels weird is because these different states of the artwork are mutually exclusive. Remember how strings and numbers can be any value, but bools can only be `true` or `false`? Just two values. It would be ideal, then, to have some way to represent a finite number of mutually exclusive values. For that, we'll use an enumeration, or `enum`. */ enum ArtworkAvailablility { case NotForSale case ForSale case OnHold case Sold } /*: This acts like a `Bool` in that it _must_ be exactly one of these four states. For example, it cannot be both for sale and on hold just like a bool can't be both true and false. This is the actual code we use in the [Artsy iOS app](https://github.com/artsy/eigen/blob/master/Artsy/Models/API_Models/Partner_Metadata/Artwork.h#L13-L18), albeit in Objective-C. Same, same. So let's set it. */ var artworkAvailability = ArtworkAvailablility.NotForSale /*: Then dig into it a bit in an `if` statement. */ if artworkAvailability == .NotForSale { print("Not for you.") } /*: We use an `enum` to represent a variable that can be one of a few different states. This comes in handy most when trying to model abstractions that have exclusive states. With that, I think we have all we need to try and represent an `Artwork`. ### Construction An `Artwork` is a _reallllly_ complicated thing that we are going to try and model. So let's handle a subset of it's information. An `Artwork` should have a name, an availability and a medium. This is the 21st century, having an Artist is so last century. We're going to use a concept called a `struct` to represent this. A `struct` is a way of collecting some language primitives into a single model. By primitives I mean things like `Bool`s, `Int`s and `String`s, things the language gives us to build on top of. */ // Constructing a model of reality struct Artwork { var name: String var medium: String var availability: ArtworkAvailablility } /*: Let's create one. If you write `var something = Artwork(` it will offer to auto-fill in the details. */ var ortasGIF = Artwork(name: "Orta's GIF", medium: "Graphics Interchange Format", availability: .ForSale) /*: We can access any of the variables inside the `ortasGIF` by using the `.` character. So if we wanted the name, we could do `ortasGIF.name`, if we wanted the medium, `ortasGIF.medium`. Let's combine what we know by checking if an artwork is a GIF. */ if ortasGIF.medium == "Graphics Interchange Format" { print("Text is such a boring medium for GIFs") } /*: Nice. OK. Let's wrap up. ### Overview In lesson one, we learned about some of the primitives that Swift gives us. Mainly `Int`s and `String`s, and how to use an `if` and `for` to run different code paths. In lesson two we have: * Expanded our knowledge of primitives to include a `Bool`. Which represents one of two states, on or off, `true` or `false`. * Built on `if` to include `else if` and `else` statements. These let us represent a lot of common code flows. * Done some boolean algebra via and (`&&`) and or (`||`). * Found a way to represent exclusive states using an `enum` * Talked about how we can model a concept like an `Artwork` via a `struct`. We built on the swift primitives to create a model that represents something important to our hearts. If you're keen, try to apply some of the things we learned last week with bools, `if` statements, logic, and `structs`. Here are some questions: - How might an artwork have an artist? How would you model an `Artist` struct? - We saw that enums and bools are similar. Do you think that bools could be built using an enum? Why or why not? - What if an artwork had to have multiple artists? How would that work? */
cc0-1.0
393e85441e62a408770d633b7bc034a0
38.583072
514
0.727863
3.723385
false
false
false
false
yannickl/SnappingStepper
Sources/UIBuilder.swift
1
1631
/* * SnappingStepper * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.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 UIKit final class UIBuilder { static func defaultLabel() -> UILabel { let label = UILabel() label.textAlignment = .center label.isUserInteractionEnabled = true return label } static func defaultStyledLabel() -> StyledLabel { let label = StyledLabel() label.textAlignment = .center label.text = "" return label } }
mit
01558281bb8ef5aa9a1030f1b6b34194
34.456522
80
0.697731
4.755102
false
false
false
false
jegumhon/URWeatherView
URWeatherView/Filter/UIBezierPath+Interpolation.swift
1
3911
// // UIBezierPath+Interpolation.swift // URWeatherView // // Created by DongSoo Lee on 2017. 5. 11.. // Copyright © 2017년 zigbang. All rights reserved. // import UIKit extension UIBezierPath { /// not consider the closed path class func interpolateCGPointsWithHermite(_ points: [CGPoint]) -> UIBezierPath? { guard points.count >= 2 else { return nil } let numberOfCurves: Int = points.count - 1 let path: UIBezierPath = UIBezierPath() var curPoint: CGPoint = .zero var prevPoint: CGPoint = .zero var nextPoint: CGPoint = .zero var endPoint: CGPoint = .zero for (index, _) in points.enumerated() { curPoint = points[index] if index == 0 { path.move(to: curPoint) } var nextIndex: Int = (index+1) % points.count var prevIndex: Int = (index - 1 < 0 ? points.count - 1 : index - 1) prevPoint = points[prevIndex] nextPoint = points[nextIndex] endPoint = nextPoint let controlPoint1: CGPoint = controlPoint(curPoint, prev: prevPoint, next: nextPoint, at: 1, when: index > 0) curPoint = points[nextIndex] nextIndex = (nextIndex + 1) % points.count prevIndex = index prevPoint = points[prevIndex] nextPoint = points[nextIndex] let controlPoint2: CGPoint = controlPoint(curPoint, prev: prevPoint, next: nextPoint, at: 2, when: index < (numberOfCurves - 1)) path.addCurve(to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2) if (index + 1) >= numberOfCurves { break } } return path } class func controlPoint(_ curPoint: CGPoint, prev prevPoint: CGPoint, next nextPoint: CGPoint, at index: Int, when condition: Bool) -> CGPoint { var mx: CGFloat = 0.0 var my: CGFloat = 0.0 switch index { case 1: if condition { mx = (nextPoint.x - curPoint.x) * 0.5 + (curPoint.x - prevPoint.x) * 0.5 my = (nextPoint.y - curPoint.y) * 0.5 + (curPoint.y - prevPoint.y) * 0.5 } else { mx = (nextPoint.x - curPoint.x) * 0.5 my = (nextPoint.y - curPoint.y) * 0.5 } return CGPoint(x: curPoint.x + mx / 3.0, y: curPoint.y + my / 3.0) case 2: if condition { mx = (nextPoint.x - curPoint.x) * 0.5 + (curPoint.x - prevPoint.x) * 0.5 my = (nextPoint.y - curPoint.y) * 0.5 + (curPoint.y - prevPoint.y) * 0.5 } else { mx = (curPoint.x - prevPoint.x) * 0.5 my = (curPoint.y - prevPoint.y) * 0.5 } return CGPoint(x: curPoint.x - mx / 3.0, y: curPoint.y - my / 3.0) default: return .zero } } } extension CGPath { func intersectBounds(with other: CGRect) -> CGRect { var rawBoundingBox: CGRect = self.boundingBox if rawBoundingBox.width == 0.0 { rawBoundingBox.size.width = 1.0 } if rawBoundingBox.height == 0.0 { rawBoundingBox.size.height = 1.0 } var intersectionRect: CGRect = rawBoundingBox.intersection(other) if intersectionRect == .null { return .zero } if intersectionRect.width == 0.0 { intersectionRect.size.width = 1.0 } if intersectionRect.height == 0.0 { intersectionRect.size.height = 1.0 } return intersectionRect } func isIntersectedRect(with other: CGRect) -> Bool { let intersecttionBounds = self.intersectBounds(with: other) if intersecttionBounds == .zero { return false } else { return true } } }
mit
b43bd15fdbd59f264bd3707da4ac86b5
31.032787
148
0.544268
4.079332
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
Pods/Kanna/Sources/Kanna.swift
1
10756
/**@file Kanna.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 /* ParseOption */ public enum ParseOption { // libxml2 case xmlParseUseLibxml(Libxml2XMLParserOptions) case htmlParseUseLibxml(Libxml2HTMLParserOptions) } private let kDefaultXmlParseOption = ParseOption.xmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) private let kDefaultHtmlParseOption = ParseOption.htmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) /** Parse XML @param xml an XML string @param url the base URL to use for the document @param encoding the document encoding @param options a ParserOption */ public func XML(xml: String, url: String?, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { switch option { case .xmlParseUseLibxml(let opt): return libxmlXMLDocument(xml: xml, url: url, encoding: encoding, option: opt.rawValue) default: return nil } } public func XML(xml: String, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { return XML(xml: xml, url: nil, encoding: encoding, option: option) } // NSData public func XML(xml: Data, url: String?, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { if let xmlStr = NSString(data: xml, encoding: encoding.rawValue) as? String { return XML(xml: xmlStr, url: url, encoding: encoding, option: option) } return nil } public func XML(xml: Data, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { return XML(xml: xml, url: nil, encoding: encoding, option: option) } // NSURL public func XML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { if let data = try? Data(contentsOf: url) { return XML(xml: data, url: url.absoluteString, encoding: encoding, option: option) } return nil } /** Parse HTML @param html an HTML string @param url the base URL to use for the document @param encoding the document encoding @param options a ParserOption */ public func HTML(html: String, url: String?, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) -> HTMLDocument? { switch option { case .htmlParseUseLibxml(let opt): return libxmlHTMLDocument(html: html, url: url, encoding: encoding, option: opt.rawValue) default: return nil } } public func HTML(html: String, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) -> HTMLDocument? { return HTML(html: html, url: nil, encoding: encoding, option: option) } // NSData public func HTML(html: Data, url: String?, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) -> HTMLDocument? { if let htmlStr = NSString(data: html, encoding: encoding.rawValue) as? String { return HTML(html: htmlStr, url: url, encoding: encoding, option: option) } return nil } public func HTML(html: Data, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) -> HTMLDocument? { return HTML(html: html, url: nil, encoding: encoding, option: option) } // NSURL public func HTML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) -> HTMLDocument? { if let data = try? Data(contentsOf: url) { return HTML(html: data, url: url.absoluteString, encoding: encoding, option: option) } return nil } /** Searchable */ public protocol Searchable { /** Search for node from current node by XPath. @param xpath */ func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject func xpath(_ xpath: String) -> XPathObject func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? func at_xpath(_ xpath: String) -> XMLElement? /** Search for node from current node by CSS selector. @param selector a CSS selector */ func css(_ selector: String, namespaces: [String:String]?) -> XPathObject func css(_ selector: String) -> XPathObject func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? func at_css(_ selector: String) -> XMLElement? } /** SearchableNode */ public protocol SearchableNode: Searchable { var text: String? { get } var toHTML: String? { get } var toXML: String? { get } var innerHTML: String? { get } var className: String? { get } var tagName: String? { get set } var content: String? { get set } } /** XMLElement */ public protocol XMLElement: SearchableNode { var parent: XMLElement? { get set } subscript(attr: String) -> String? { get set } func addPrevSibling(_ node: XMLElement) func addNextSibling(_ node: XMLElement) func removeChild(_ node: XMLElement) } /** XMLDocument */ public protocol XMLDocument: SearchableNode { } /** HTMLDocument */ public protocol HTMLDocument: XMLDocument { var title: String? { get } var head: XMLElement? { get } var body: XMLElement? { get } } /** XMLNodeSet */ public final class XMLNodeSet { fileprivate var nodes: [XMLElement] = [] public var toHTML: String? { let html = nodes.reduce("") { if let text = $1.toHTML { return $0 + text } return $0 } return html.isEmpty == false ? html : nil } public var innerHTML: String? { let html = nodes.reduce("") { if let text = $1.innerHTML { return $0 + text } return $0 } return html.isEmpty == false ? html : nil } public var text: String? { let html = nodes.reduce("") { if let text = $1.text { return $0 + text } return $0 } return html } public subscript(index: Int) -> XMLElement { return nodes[index] } public var count: Int { return nodes.count } internal init() { } internal init(nodes: [XMLElement]) { self.nodes = nodes } public func at(_ index: Int) -> XMLElement? { return count > index ? nodes[index] : nil } public var first: XMLElement? { return at(0) } public var last: XMLElement? { return at(count-1) } } extension XMLNodeSet: Sequence { public typealias Iterator = AnyIterator<XMLElement> public func makeIterator() -> Iterator { var index = 0 return AnyIterator { if index < self.nodes.count { let n = self.nodes[index] index += 1 return n } return nil } } } /** XPathObject */ public enum XPathObject { case none case NodeSet(nodeset: XMLNodeSet) case Bool(bool: Swift.Bool) case Number(num: Double) case String(text: Swift.String) } extension XPathObject { internal init(docPtr: xmlDocPtr, object: xmlXPathObject) { switch object.type { case XPATH_NODESET: let nodeSet = object.nodesetval if nodeSet == nil || nodeSet?.pointee.nodeNr == 0 || nodeSet?.pointee.nodeTab == nil { self = .none return } var nodes : [XMLElement] = [] let size = Int((nodeSet?.pointee.nodeNr)!) for i in 0 ..< size { let node: xmlNodePtr = nodeSet!.pointee.nodeTab[i]! let htmlNode = libxmlHTMLNode(docPtr: docPtr, node: node) nodes.append(htmlNode) } self = .NodeSet(nodeset: XMLNodeSet(nodes: nodes)) return case XPATH_BOOLEAN: self = .Bool(bool: object.boolval != 0) return case XPATH_NUMBER: self = .Number(num: object.floatval) case XPATH_STRING: guard let str = UnsafeRawPointer(object.stringval)?.assumingMemoryBound(to: CChar.self) else { self = .String(text: "") return } self = .String(text: Swift.String(cString: str)) return default: self = .none return } } public subscript(index: Int) -> XMLElement { return nodeSet![index] } public var first: XMLElement? { return nodeSet?.first } var nodeSet: XMLNodeSet? { if case let .NodeSet(nodeset) = self { return nodeset } return nil } var bool: Swift.Bool? { if case let .Bool(value) = self { return value } return nil } var number: Double? { if case let .Number(value) = self { return value } return nil } var string: Swift.String? { if case let .String(value) = self { return value } return nil } var nodeSetValue: XMLNodeSet { return nodeSet ?? XMLNodeSet() } var boolValue: Swift.Bool { return bool ?? false } var numberValue: Double { return number ?? 0.0 } var stringValue: Swift.String { return string ?? "" } } extension XPathObject: Sequence { public typealias Iterator = AnyIterator<XMLElement> public func makeIterator() -> Iterator { var index = 0 return AnyIterator { if index < self.nodeSetValue.count { let obj = self.nodeSetValue[index] index += 1 return obj } return nil } } }
mit
7fffad265e4412cfd1ed5f343b86fe1c
27.305263
137
0.62077
4.234646
false
false
false
false
nerdishbynature/TanukiKit
TanukiKitTests/ConfigurationTests.swift
1
2366
import XCTest import Foundation import TanukiKit private let enterpriseURL = "https://gitlab.example.com/api/v3" class ConfigurationTests: XCTestCase { func testTokenConfiguration() { let subject = TokenConfiguration("12345") XCTAssertEqual(subject.accessToken!, "12345") XCTAssertEqual(subject.apiEndpoint, "https://gitlab.com/api/v3/") } func testEnterpriseTokenConfiguration() { let subject = TokenConfiguration("12345", url: enterpriseURL) XCTAssertEqual(subject.accessToken!, "12345") XCTAssertEqual(subject.apiEndpoint, enterpriseURL) } func testEnterprisePrivateTokenConfiguration() { let subject = PrivateTokenConfiguration("12345", url: enterpriseURL) XCTAssertEqual(subject.accessToken!, "12345") XCTAssertEqual(subject.apiEndpoint, enterpriseURL) XCTAssertEqual(subject.accessTokenFieldName, "private_token") } func testOAuthConfiguration() { let subject = OAuthConfiguration(token: "12345", secret: "6789", redirectURI: "https://oauth.example.com/gitlab_oauth") XCTAssertEqual(subject.token, "12345") XCTAssertEqual(subject.secret, "6789") XCTAssertEqual(subject.apiEndpoint, "https://gitlab.com/api/v3/") } func testOAuthTokenConfiguration() { let subject = OAuthConfiguration(enterpriseURL, token: "12345", secret: "6789", redirectURI: "https://oauth.example.com/gitlab_oauth") XCTAssertEqual(subject.token, "12345") XCTAssertEqual(subject.secret, "6789") XCTAssertEqual(subject.apiEndpoint, enterpriseURL) } func testHandleOpenURL() { let config = OAuthConfiguration(token: "12345", secret: "6789", redirectURI: "https://oauth.example.com/gitlab_oauth") let json = "{\"access_token\": \"017ec60f4a182\", \"token_type\": \"bearer\"}" let session = TanukiKitURLTestSession(expectedURL: "https://gitlab.com/oauth/token", expectedHTTPMethod: "POST", response: json, statusCode: 200) let url = URL(string: "https://oauth.example.com/gitlab_oauth?code=dhfjgh23493")! var token: TokenConfiguration? config.handleOpenURL(session, url: url) { resultingConfig in token = resultingConfig } XCTAssertEqual(token?.accessToken, "017ec60f4a182") XCTAssertTrue(session.wasCalled) } }
mit
b915e37778c819ffc01f9a426e318363
43.641509
153
0.693998
4.515267
false
true
false
false
neoneye/SwiftyFORM
Source/Util/Logging.swift
1
540
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import Foundation /// `Print` with additional info such as linenumber, filename /// /// http://stackoverflow.com/questions/24114288/macros-in-swift #if DEBUG func SwiftyFormLog(_ message: String, function: String = #function, file: String = #file, line: Int = #line) { print("[\(file):\(line)] \(function) - \(message)") } #else func SwiftyFormLog(_ message: String, function: String = #function, file: String = #file, line: Int = #line) { // do nothing } #endif
mit
64875d40e5c82106d9f4c03220f36526
35
111
0.687037
3.417722
false
false
false
false
natecook1000/swift
test/SILGen/sil_locations.swift
1
10860
// RUN: %target-swift-emit-silgen -module-name sil_locations -Xllvm -sil-print-debuginfo -emit-verbose-sil -enable-sil-ownership %s | %FileCheck %s // FIXME: Not sure if this an ideal source info for the branch - // it points to if, not the last instruction in the block. func ifexpr() -> Int { var x : Int = 0 if true { x+=1 } return x // CHECK-LABEL: sil hidden @$S13sil_locations6ifexprSiyF // CHECK: apply {{.*}}, loc "{{.*}}":[[@LINE-5]]:6 // CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]], loc "{{.*}}":[[@LINE-6]]:6 // CHECK: br [[FALSE_BB]], loc "{{.*}}":[[@LINE-5]]:3 // CHECK: return {{.*}}, loc "{{.*}}":[[@LINE-5]]:3, {{.*}}:return } func ifelseexpr() -> Int { var x : Int = 0 if true { x+=1 } else { x-=1 } return x // CHECK-LABEL: sil hidden @$S13sil_locations10ifelseexprSiyF // CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]], loc "{{.*}}":[[@LINE-7]]:6 // CHECK: [[TRUE_BB]]: // CHECK: br bb{{[0-9]+}}, loc "{{.*}}":[[@LINE-7]]:3 // CHECK: [[FALSE_BB]]: // CHECK: br bb{{[0-9]+}}, loc "{{.*}}":[[@LINE-7]]:3 // CHECK: return {{.*}}, loc "{{.*}}":[[@LINE-7]]:3, {{.*}}:return } // The source locations are handled differently here - since // the return is unified, we keep the location of the return(not the if) // in the branch. func ifexpr_return() -> Int { if true { return 5 } return 6 // CHECK-LABEL: sil hidden @$S13sil_locations13ifexpr_returnSiyF // CHECK: apply {{.*}}, loc "{{.*}}":[[@LINE-5]]:6 // CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]], loc "{{.*}}":[[@LINE-6]]:6 // CHECK: [[TRUE_BB]]: // CHECK: br bb{{[0-9]+}}({{%.*}}), loc "{{.*}}":[[@LINE-7]]:5, {{.*}}:return // CHECK: [[FALSE_BB]]: // CHECK: br bb{{[0-9]+}}({{%.*}}), loc "{{.*}}":[[@LINE-7]]:3, {{.*}}:return // CHECK: return {{.*}}, loc "{{.*}}":[[@LINE+1]]:1, {{.*}}:cleanup } func ifexpr_rval() -> Int { var x = true ? 5 : 6 return x // CHECK-LABEL: sil hidden @$S13sil_locations11ifexpr_rvalSiyF // CHECK: apply {{.*}}, loc "{{.*}}":[[@LINE-3]]:11 // CHECK: cond_br {{%.*}}, [[TRUE_BB:bb[0-9]+]], [[FALSE_BB:bb[0-9]+]], loc "{{.*}}":[[@LINE-4]]:11 // CHECK: [[TRUE_BB]]: // CHECK: br bb{{[0-9]+}}({{%.*}}), loc "{{.*}}":[[@LINE-6]]:18 // CHECK: [[FALSE_BB]]: // CHECK: br bb{{[0-9]+}}({{%.*}}), loc "{{.*}}":[[@LINE-8]]:22 } // --- Test function calls. func simpleDirectCallTest(_ i: Int) -> Int { return simpleDirectCallTest(i) // CHECK-LABEL: sil hidden @$S13sil_locations20simpleDirectCallTestyS2iF // CHECK: function_ref @$S13sil_locations20simpleDirectCallTestyS2iF : {{.*}}, loc "{{.*}}":[[@LINE-2]]:10 // CHECK: {{%.*}} apply {{%.*}} line:[[@LINE-3]]:10 } func templateTest<T>(_ value: T) -> T { return value } func useTemplateTest() -> Int { return templateTest(5); // CHECK-LABEL: sil hidden @$S13sil_locations15useTemplateTestSiyF // CHECK: function_ref @$SSi2{{[_0-9a-zA-Z]*}}fC :{{.*}}, loc "{{.*}}":78 } func foo(_ x: Int) -> Int { func bar(_ y: Int) -> Int { return x + y } return bar(1) // CHECK-LABEL: sil hidden @$S13sil_locations3foo{{[_0-9a-zA-Z]*}}F // CHECK: [[CLOSURE:%[0-9]+]] = function_ref {{.*}}, loc "{{.*}}":[[@LINE-2]]:10 // CHECK: apply [[CLOSURE:%[0-9]+]] } class LocationClass { func mem() {} } func testMethodCall() { var l: LocationClass l.mem(); // CHECK-LABEL: sil hidden @$S13sil_locations14testMethodCallyyF // CHECK: class_method {{.[0-9]+}} : $LocationClass, #LocationClass.mem!1 {{.*}}, loc "{{.*}}":[[@LINE-3]]:5 } func multipleReturnsImplicitAndExplicit() { var x = 5+3 if x > 10 { return } x += 1 // CHECK-LABEL: sil hidden @$S13sil_locations34multipleReturnsImplicitAndExplicityyF // CHECK: cond_br // CHECK: br bb{{[0-9]+}}, loc "{{.*}}":[[@LINE-5]]:5, {{.*}}:return // CHECK: br bb{{[0-9]+}}, loc "{{.*}}":[[@LINE+2]]:1, {{.*}}:imp_return // CHECK: return {{.*}}, loc "{{.*}}":[[@LINE+1]]:1, {{.*}}:cleanup } func simplifiedImplicitReturn() -> () { var y = 0 // CHECK-LABEL: sil hidden @$S13sil_locations24simplifiedImplicitReturnyyF // CHECK: return {{.*}}, loc "{{.*}}":[[@LINE+1]]:1, {{.*}}:imp_return } func switchfoo() -> Int { return 0 } func switchbar() -> Int { return 0 } // CHECK-LABEL: sil hidden @$S13sil_locations10testSwitchyyF func testSwitch() { var x:Int x = 0 switch (switchfoo(), switchbar()) { // CHECK: store {{.*}}, loc "{{.*}}":[[@LINE-1]] case (1,2): // CHECK: integer_literal $Builtin.Int2048, 2, loc "{{.*}}":[[@LINE-3]]:10 // FIXME: Location info is missing. // CHECK: cond_br // var z: Int = 200 // CHECK: [[VAR_Z:%[0-9]+]] = alloc_box ${ var Int }, var, name "z"{{.*}}line:[[@LINE-1]]:9 // CHECK: integer_literal $Builtin.Int2048, 200, loc "{{.*}}":[[@LINE-2]]:18 x = z // CHECK: destroy_value [[VAR_Z]]{{.*}}, loc "{{.*}}":[[@LINE-1]]:9, {{.*}}:cleanup case (3, let y): x += 1 default: () } } func testIf() { if true { var y:Int } else { var x:Int } // CHECK-LABEL: sil hidden @$S13sil_locations6testIfyyF // // FIXME: Missing location info here. // CHECK: function_ref // CHECK: apply // // // // CHECK: br {{.*}}, loc "{{.*}}":[[@LINE-13]]:6 } func testFor() { for i in 0..<10 { var y: Int = 300 y+=1 if true { break } y-=1 continue } // CHECK-LABEL: sil hidden @$S13sil_locations7testForyyF // CHECK: [[VAR_Y_IN_FOR:%[0-9]+]] = alloc_box ${ var Int }, var, name "y", loc "{{.*}}":[[@LINE-10]]:9 // CHECK: integer_literal $Builtin.Int2048, 300, loc "{{.*}}":[[@LINE-11]]:18 // CHECK: destroy_value [[VAR_Y_IN_FOR]] : ${ var Int } // CHECK: br bb{{.*}}, loc "{{.*}}":[[@LINE-10]]:7 // CHECK: destroy_value [[VAR_Y_IN_FOR]] : ${ var Int } // CHECK: br bb{{.*}}, loc "{{.*}}":[[@LINE-9]]:5 } func testTuples() { var t = (2,3) var tt = (2, (4,5)) var d = "foo" // CHECK-LABEL: sil hidden @$S13sil_locations10testTuplesyyF // CHECK: tuple_element_addr {{.*}}, loc "{{.*}}":[[@LINE-4]]:11 // CHECK: integer_literal $Builtin.Int2048, 2, loc "{{.*}}":[[@LINE-5]]:12 // CHECK: integer_literal $Builtin.Int2048, 3, loc "{{.*}}":[[@LINE-6]]:14 // CHECK: tuple_element_addr {{.*}}, loc "{{.*}}":[[@LINE-6]]:12 // CHECK: tuple_element_addr {{.*}}, loc "{{.*}}":[[@LINE-7]]:16 } // Test tuple imploding/exploding. protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(_ seq: T) -> (Int) -> Int { return {i in i + seq.ord() } } func captures_tuple<T, U>(x: (T, U)) -> () -> (T, U) { return {x} // CHECK-LABEL: sil hidden @$S13sil_locations14captures_tuple{{[_0-9a-zA-Z]*}}F // CHECK: tuple_element_addr {{.*}}, loc "{{.*}}":[[@LINE-3]]:27 // CHECK: copy_addr {{.*}}, loc "{{.*}}":[[@LINE-4]]:27 // CHECK: function_ref {{.*}}, loc "{{.*}}":[[@LINE-4]]:10 // CHECK-LABEL: sil private @$S13sil_locations14captures_tuple{{.*}}fU_ // CHECK: copy_addr {{.*}}, loc "{{.*}}":[[@LINE-7]]:11 } func interpolated_string(_ x: Int, y: String) -> String { return "The \(x) Million Dollar \(y)" // CHECK-LABEL: sil hidden @$S13sil_locations19interpolated_string{{[_0-9a-zA-Z]*}}F // CHECK: copy_value{{.*}}, loc "{{.*}}":[[@LINE-2]]:37 } func int(_ x: Int) {} func tuple() -> (Int, Float) { return (1, 1.0) } func tuple_element(_ x: (Int, Float)) { int(tuple().0) // CHECK-LABEL: sil hidden @$S13sil_locations13tuple_element{{[_0-9a-zA-Z]*}}F // CHECK: apply {{.*}} line:[[@LINE-3]]:7 // CHECK: destructure_tuple {{.*}}line:[[@LINE-4]]:7 // CHECK: apply {{.*}} line:[[@LINE-5]]:3 } func containers() -> ([Int], Dictionary<String, Int>) { return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3]) // CHECK-LABEL: sil hidden @$S13sil_locations10containers{{[_0-9a-zA-Z]*}}F // CHECK: apply {{%.*}}<(String, Int)>({{%.*}}), loc "{{.*}}":[[@LINE-2]]:22 // CHECK: string_literal utf8 "Ankeny", loc "{{.*}}":[[@LINE-4]]:23 // CHECK: integer_literal $Builtin.Int2048, 1, loc "{{.*}}":[[@LINE-6]]:33 // CHECK: integer_literal $Builtin.Int2048, 2, loc "{{.*}}":[[@LINE-7]]:48 } func a() {} func b() -> Int { return 0 } protocol P { func p() } struct X : P { func p() {} } func test_isa_2(_ p: P) { switch (p, b()) { case (is X, b()): a() case _: a() } // CHECK-LABEL: sil hidden @$S13sil_locations10test_isa_2{{[_0-9a-zA-Z]*}}F // CHECK: alloc_stack $(P, Int), loc "{{.*}}":[[@LINE-10]]:10 // CHECK: tuple_element_addr{{.*}} $*(P, Int), 0, loc "{{.*}}":[[@LINE-11]]:10 // CHECK: tuple_element_addr{{.*}} $*(P, Int), 1, loc "{{.*}}":[[@LINE-12]]:10 // CHECK: load {{.*}}, loc "{{.*}}":[[@LINE-12]]:8 // // CHECK: checked_cast_addr_br {{.*}}, loc "{{.*}}":[[@LINE-14]]:9 // CHECK: load {{.*}}, loc "{{.*}}":[[@LINE-15]]:9 } func runcibleWhy() {} protocol Runcible { func runce() } enum SinglePayloadAddressOnly { case x(Runcible) case y } func printSinglePayloadAddressOnly(_ v:SinglePayloadAddressOnly) { switch v { case .x(let runcible): runcible.runce() case .y: runcibleWhy() } // CHECK_LABEL: sil hidden @$S13sil_locations29printSinglePayloadAddressOnly{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK: switch_enum_addr {{.*}} [[FALSE_BB:bb[0-9]+]], {{.*}}line:[[@LINE-10]]:3 // CHECK: [[FALSE_BB]]: } func testStringForEachStmt() { var i = 0 for index in 1..<20 { i += 1 if i == 15 { break } } // CHECK-LABEL: sil hidden @$S13sil_locations21testStringForEachStmtyyF // CHECK: br {{.*}} line:[[@LINE-8]]:3 // CHECK: switch_enum {{.*}} line:[[@LINE-9]]:3 // CHECK: cond_br {{.*}} line:[[@LINE-8]]:8 // Break branch: // CHECK: br {{.*}} line:[[@LINE-9]]:7 // Looping back branch: // CHECK: br {{.*}} line:[[@LINE-9]]:3 // Condition is false branch: // CHECK: br {{.*}} line:[[@LINE-16]]:3 } func testForStmt() { var m = 0 for i in 0..<10 { m += 1 if m == 15 { break } else { continue } } } func testRepeatWhile() { var m = 0 repeat { m += 1 } while (m < 200) // CHECK-LABEL: sil hidden @$S13sil_locations15testRepeatWhileyyF // CHECK: br {{.*}} line:[[@LINE-6]]:3 // CHECK: cond_br {{.*}} line:[[@LINE-5]]:11 // Loop back branch: // CHECK: br {{.*}} line:[[@LINE-7]]:11 } func testWhile() { var m = 0 while m < 100 { m += 1 if m > 5 { break } m += 1 } // CHECK-LABEL: sil hidden @$S13sil_locations9testWhileyyF // CHECK: br {{.*}} line:[[@LINE-9]]:3 // While loop conditional branch: // CHECK: cond_br {{.*}} line:[[@LINE-11]]:9 // If stmt condition branch: // CHECK: cond_br {{.*}} line:[[@LINE-11]]:8 // Break branch: // CHECK: br {{.*}} line:[[@LINE-12]]:7 // Looping back branch: // CHECK: br {{.*}} line:[[@LINE-11]]:3 }
apache-2.0
b88717ff1736926c38b4b1889b90d7ff
26.218045
147
0.526059
3.134199
false
true
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/SplashScreenViewController.swift
1
4209
import UIKit /// Matches the appearance of the launch xib and shows while we do any setup or migrations that need to block user interaction. /// If this VC is shown for longer than `maximumNonInteractiveTimeInterval`, the view transitions to a loading animation. @objc (WMFSplashScreenViewController) class SplashScreenViewController: ThemeableViewController { // MARK: Object Lifecycle deinit { // Should be canceled on willDisappear, but this is extra insurance NSObject.cancelPreviousPerformRequests(withTarget: self) } // MARK: View Lifecycle override func viewDidLoad() { super.viewDidLoad() setupSplashView() } func triggerMigratingAnimation() { perform(#selector(showLoadingAnimation), with: nil, afterDelay: SplashScreenViewController.maximumNonInteractiveTimeInterval) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(showLoadingAnimation), object: nil) } /// Ensure we show the busy animation for some minimum amount of time, otherwise the transition can be jarring @objc func ensureMinimumShowDuration(completion: @escaping () -> Void) { guard loadingAnimationShowTime != 0 else { completion() return } let now = CFAbsoluteTimeGetCurrent() let busyAnimationVisibleTimeInterval = now - loadingAnimationShowTime guard busyAnimationVisibleTimeInterval < SplashScreenViewController.minimumBusyAnimationVisibleTimeInterval else { completion() return } let delay = SplashScreenViewController.minimumBusyAnimationVisibleTimeInterval - busyAnimationVisibleTimeInterval dispatchOnMainQueueAfterDelayInSeconds(delay, completion) } // MARK: Constants static let maximumNonInteractiveTimeInterval: TimeInterval = 4 static let minimumBusyAnimationVisibleTimeInterval: TimeInterval = 0.6 static let crossFadeAnimationDuration: TimeInterval = 0.3 // MARK: Splash View func setupSplashView() { view.wmf_addSubviewWithConstraintsToEdges(splashView) let wordmark = UIImage(named: "splashscreen-wordmark") let wordmarkView = UIImageView(image: wordmark) wordmarkView.translatesAutoresizingMaskIntoConstraints = false splashView.addSubview(wordmarkView) let centerXConstraint = splashView.centerXAnchor.constraint(equalTo: wordmarkView.centerXAnchor) let centerYConstraint = splashView.centerYAnchor.constraint(equalTo: wordmarkView.centerYAnchor, constant: 12) splashView.addConstraints([centerXConstraint, centerYConstraint]) } /// Matches launch xib lazy var splashView: UIImageView = { let splashView = UIImageView() splashView.translatesAutoresizingMaskIntoConstraints = false splashView.contentMode = .center if UIDevice.current.userInterfaceIdiom != .pad { splashView.image = UIImage(named: "splashscreen-background") } splashView.backgroundColor = UIColor.systemBackground return splashView }() // MARK: Loading Animation var loadingAnimationShowTime: CFAbsoluteTime = 0 lazy var loadingAnimationViewController: LoadingAnimationViewController = { return LoadingAnimationViewController(nibName: "LoadingAnimationViewController", bundle: nil) }() @objc private func showLoadingAnimation() { loadingAnimationShowTime = CFAbsoluteTimeGetCurrent() wmf_add(childController: loadingAnimationViewController, andConstrainToEdgesOfContainerView: view, belowSubview: splashView) UIView.animate(withDuration: SplashScreenViewController.crossFadeAnimationDuration) { self.splashView.alpha = 0 } } // MARK: Themable override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } loadingAnimationViewController.apply(theme: theme) } }
mit
3add8e77c999629e4c01b1555493acbc
38.707547
133
0.707769
5.757866
false
false
false
false
delbert06/DYZB
DYZB/DYZB/RecommendViewModel.swift
1
3738
// // RecommendViewModel.swift // DYZB // // Created by 胡迪 on 2016/12/9. // Copyright © 2016年 D.Huhu. All rights reserved. // import UIKit class RecommendViewModel: NSObject { // MARK: - 懒加载属性 lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]() lazy var cycleModels : [CycleModel] = [CycleModel]() fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup() fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup() } // MARK: - 发送网络请求 extension RecommendViewModel { func requestData(finishCallback:@escaping ()->()) { let parameters = ["limit" : "4","offset" : "0","time" : Date.getCurrentTime()] let dGroup = DispatchGroup() // 1. 请求第一部分推荐数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: parameters) { (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} self.bigDataGroup.tag_name = "热门" self.bigDataGroup.icon_name = "home_header_hot" for dict in dataArray{ let group = AnChorModel(dict: dict) self.bigDataGroup.anchors.append(group) } dGroup.leave() } // 2. 请求第二部分颜值数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in guard let resultDict = result as? [String : NSObject] else {return} guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return} self.prettyGroup.tag_name = "颜值" self.prettyGroup.icon_name = "home_header_phone" for dict in dataArray{ let anchor = AnChorModel(dict: dict) self.prettyGroup.anchors.append(anchor) } dGroup.leave() } // 3. 请求第三部分游戏数据 dGroup.enter() NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) {(result) in // 1. 将result转成字典 guard let resultDic = result as? [String : NSObject] else {return} // 2. 根据data的key获取数组 // resultDic["data"] 就是字典的key guard let dataArray = resultDic["data"] as? [[String :NSObject]] else {return} // 3. 便利数组,获取字典,并将字典转化成模型数组 for dict in dataArray{ let group = AnchorGroup(dict: dict) self.anchorGroups.append(group) } dGroup.leave() } dGroup.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyGroup, at: 0) self.anchorGroups.insert(self.bigDataGroup, at: 0) finishCallback() } } func requstCycleData(finishCallback: @escaping ()->()){ NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version":"2.300"]) { (result) in guard let resultDic = result as? [String : NSObject] else { return } guard let dataArray = resultDic["data"] as? [[String :NSObject]] else {return} for dict in dataArray{ self.cycleModels.append(CycleModel(dict: dict)) } // print(result) finishCallback() } } }
mit
dd6ede06e307a679d1a8b1c9033af2fe
37.75
137
0.574194
4.478643
false
false
false
false
lacklock/ReactiveCocoaExtension
Pods/ReactiveSwift/Sources/SignalProducer.swift
1
81135
import Dispatch import Foundation import Result /// A SignalProducer creates Signals that can produce values of type `Value` /// and/or fail with errors of type `Error`. If no failure should be possible, /// `NoError` can be specified for `Error`. /// /// SignalProducers can be used to represent operations or tasks, like network /// requests, where each invocation of `start()` will create a new underlying /// operation. This ensures that consumers will receive the results, versus a /// plain Signal, where the results might be sent before any observers are /// attached. /// /// Because of the behavior of `start()`, different Signals created from the /// producer may see a different version of Events. The Events may arrive in a /// different order between Signals, or the stream might be completely /// different! public struct SignalProducer<Value, Error: Swift.Error> { public typealias ProducedSignal = Signal<Value, Error> private let startHandler: (Signal<Value, Error>.Observer, CompositeDisposable) -> Void /// Initializes a `SignalProducer` that will emit the same events as the /// given signal. /// /// If the Disposable returned from `start()` is disposed or a terminating /// event is sent to the observer, the given signal will be disposed. /// /// - parameters: /// - signal: A signal to observe after starting the producer. public init<S: SignalProtocol>(_ signal: S) where S.Value == Value, S.Error == Error { self.init { observer, disposable in disposable += signal.observe(observer) } } /// Initializes a SignalProducer that will invoke the given closure once for /// each invocation of `start()`. /// /// The events that the closure puts into the given observer will become /// the events sent by the started `Signal` to its observers. /// /// - note: If the `Disposable` returned from `start()` is disposed or a /// terminating event is sent to the observer, the given /// `CompositeDisposable` will be disposed, at which point work /// should be interrupted and any temporary resources cleaned up. /// /// - parameters: /// - startHandler: A closure that accepts observer and a disposable. public init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void) { self.startHandler = startHandler } /// Creates a producer for a `Signal` that will immediately send one value /// then complete. /// /// - parameters: /// - value: A value that should be sent by the `Signal` in a `value` /// event. public init(value: Value) { self.init { observer, disposable in observer.send(value: value) observer.sendCompleted() } } /// Creates a producer for a `Signal` that will immediately fail with the /// given error. /// /// - parameters: /// - error: An error that should be sent by the `Signal` in a `failed` /// event. public init(error: Error) { self.init { observer, disposable in observer.send(error: error) } } /// Creates a producer for a Signal that will immediately send one value /// then complete, or immediately fail, depending on the given Result. /// /// - parameters: /// - result: A `Result` instance that will send either `value` event if /// `result` is `success`ful or `failed` event if `result` is a /// `failure`. public init(result: Result<Value, Error>) { switch result { case let .success(value): self.init(value: value) case let .failure(error): self.init(error: error) } } /// Creates a producer for a Signal that will immediately send the values /// from the given sequence, then complete. /// /// - parameters: /// - values: A sequence of values that a `Signal` will send as separate /// `value` events and then complete. public init<S: Sequence>(_ values: S) where S.Iterator.Element == Value { self.init { observer, disposable in for value in values { observer.send(value: value) if disposable.isDisposed { break } } observer.sendCompleted() } } /// Creates a producer for a Signal that will immediately send the values /// from the given sequence, then complete. /// /// - parameters: /// - first: First value for the `Signal` to send. /// - second: Second value for the `Signal` to send. /// - tail: Rest of the values to be sent by the `Signal`. public init(values first: Value, _ second: Value, _ tail: Value...) { self.init([ first, second ] + tail) } /// A producer for a Signal that will immediately complete without sending /// any values. public static var empty: SignalProducer { return self.init { observer, disposable in observer.sendCompleted() } } /// A producer for a Signal that never sends any events to its observers. public static var never: SignalProducer { return self.init { _ in return } } /// Create a Signal from the producer, pass it into the given closure, /// then start sending events on the Signal when the closure has returned. /// /// The closure will also receive a disposable which can be used to /// interrupt the work associated with the signal and immediately send an /// `interrupted` event. /// /// - parameters: /// - setUp: A closure that accepts a `signal` and `interrupter`. public func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void) { // Disposes of the work associated with the SignalProducer and any // upstream producers. let producerDisposable = CompositeDisposable() let (signal, observer) = Signal<Value, Error>.pipe(disposable: producerDisposable) // Directly disposed of when `start()` or `startWithSignal()` is // disposed. let cancelDisposable = ActionDisposable(action: observer.sendInterrupted) setup(signal, cancelDisposable) if cancelDisposable.isDisposed { return } startHandler(observer, producerDisposable) } } public protocol SignalProducerProtocol { /// The type of values being sent on the producer associatedtype Value /// The type of error that can occur on the producer. If errors aren't possible /// then `NoError` can be used. associatedtype Error: Swift.Error /// Extracts a signal producer from the receiver. var producer: SignalProducer<Value, Error> { get } /// Initialize a signal init(_ startHandler: @escaping (Signal<Value, Error>.Observer, CompositeDisposable) -> Void) /// Creates a Signal from the producer, passes it into the given closure, /// then starts sending events on the Signal when the closure has returned. func startWithSignal(_ setup: (_ signal: Signal<Value, Error>, _ interrupter: Disposable) -> Void) } extension SignalProducer: SignalProducerProtocol { public var producer: SignalProducer { return self } } extension SignalProducerProtocol { /// Create a Signal from the producer, then attach the given observer to /// the `Signal` as an observer. /// /// - parameters: /// - observer: An observer to attach to produced signal. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the signal and immediately send an /// `interrupted` event. @discardableResult public func start(_ observer: Signal<Value, Error>.Observer = .init()) -> Disposable { var disposable: Disposable! startWithSignal { signal, innerDisposable in signal.observe(observer) disposable = innerDisposable } return disposable } /// Convenience override for start(_:) to allow trailing-closure style /// invocations. /// /// - parameters: /// - observerAction: A closure that accepts `Event` sent by the produced /// signal. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the signal and immediately send an /// `interrupted` event. @discardableResult public func start(_ observerAction: @escaping Signal<Value, Error>.Observer.Action) -> Disposable { return start(Observer(observerAction)) } /// Create a Signal from the producer, then add an observer to the `Signal`, /// which will invoke the given callback when `value` or `failed` events are /// received. /// /// - parameters: /// - result: A closure that accepts a `result` that contains a `.success` /// case for `value` events or `.failure` case for `failed` event. /// /// - returns: A Disposable which can be used to interrupt the work /// associated with the Signal, and prevent any future callbacks /// from being invoked. @discardableResult public func startWithResult(_ result: @escaping (Result<Value, Error>) -> Void) -> Disposable { return start( Observer( value: { result(.success($0)) }, failed: { result(.failure($0)) } ) ) } /// Create a Signal from the producer, then add exactly one observer to the /// Signal, which will invoke the given callback when a `completed` event is /// received. /// /// - parameters: /// - completed: A closure that will be envoked when produced signal sends /// `completed` event. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the signal. @discardableResult public func startWithCompleted(_ completed: @escaping () -> Void) -> Disposable { return start(Observer(completed: completed)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when a `failed` event /// is received. /// /// - parameters: /// - failed: A closure that accepts an error object. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the signal. @discardableResult public func startWithFailed(_ failed: @escaping (Error) -> Void) -> Disposable { return start(Observer(failed: failed)) } /// Creates a Signal from the producer, then adds exactly one observer to /// the Signal, which will invoke the given callback when an `interrupted` /// event is received. /// /// - parameters: /// - interrupted: A closure that is invoked when `interrupted` event is /// received. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the signal. @discardableResult public func startWithInterrupted(_ interrupted: @escaping () -> Void) -> Disposable { return start(Observer(interrupted: interrupted)) } /// Creates a `Signal` from the producer. /// /// This is equivalent to `SignalProducer.startWithSignal`, but it has /// the downside that any values emitted synchronously upon starting will /// be missed by the observer, because it won't be able to subscribe in time. /// That's why we don't want this method to be exposed as `public`, /// but it's useful internally. internal func startAndRetrieveSignal() -> Signal<Value, Error> { var result: Signal<Value, Error>! self.startWithSignal { signal, _ in result = signal } return result } } extension SignalProducerProtocol where Error == NoError { /// Create a Signal from the producer, then add exactly one observer to /// the Signal, which will invoke the given callback when `value` events are /// received. /// /// - parameters: /// - value: A closure that accepts a value carried by `value` event. /// /// - returns: A `Disposable` which can be used to interrupt the work /// associated with the Signal, and prevent any future callbacks /// from being invoked. @discardableResult public func startWithValues(_ value: @escaping (Value) -> Void) -> Disposable { return start(Observer(value: value)) } } extension SignalProducerProtocol { /// Lift an unary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new `SignalProducer` which will apply /// the given `Signal` operator to _every_ created `Signal`, just as if the /// operator had been applied to each `Signal` yielded from `start()`. /// /// - parameters: /// - transform: An unary operator to lift. /// /// - returns: A signal producer that applies signal's operator to every /// created signal. public func lift<U, F>(_ transform: @escaping (Signal<Value, Error>) -> Signal<U, F>) -> SignalProducer<U, F> { return SignalProducer { observer, outerDisposable in self.startWithSignal { signal, innerDisposable in outerDisposable += innerDisposable transform(signal).observe(observer) } } } /// Lift a binary Signal operator to operate upon SignalProducers instead. /// /// In other words, this will create a new `SignalProducer` which will apply /// the given `Signal` operator to _every_ `Signal` created from the two /// producers, just as if the operator had been applied to each `Signal` /// yielded from `start()`. /// /// - note: starting the returned producer will start the receiver of the /// operator, which may not be adviseable for some operators. /// /// - parameters: /// - transform: A binary operator to lift. /// /// - returns: A binary operator that operates on two signal producers. public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> { return liftRight(transform) } /// Right-associative lifting of a binary signal operator over producers. /// That is, the argument producer will be started before the receiver. When /// both producers are synchronous this order can be important depending on /// the operator to generate correct results. private func liftRight<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> { return { otherProducer in return SignalProducer { observer, outerDisposable in self.startWithSignal { signal, disposable in outerDisposable.add(disposable) otherProducer.startWithSignal { otherSignal, otherDisposable in outerDisposable += otherDisposable transform(signal)(otherSignal).observe(observer) } } } } } /// Left-associative lifting of a binary signal operator over producers. /// That is, the receiver will be started before the argument producer. When /// both producers are synchronous this order can be important depending on /// the operator to generate correct results. private func liftLeft<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (SignalProducer<U, F>) -> SignalProducer<V, G> { return { otherProducer in return SignalProducer { observer, outerDisposable in otherProducer.startWithSignal { otherSignal, otherDisposable in outerDisposable += otherDisposable self.startWithSignal { signal, disposable in outerDisposable.add(disposable) transform(signal)(otherSignal).observe(observer) } } } } } /// Lift a binary Signal operator to operate upon a Signal and a /// SignalProducer instead. /// /// In other words, this will create a new `SignalProducer` which will apply /// the given `Signal` operator to _every_ `Signal` created from the two /// producers, just as if the operator had been applied to each `Signal` /// yielded from `start()`. /// /// - parameters: /// - transform: A binary operator to lift. /// /// - returns: A binary operator that works on `Signal` and returns /// `SignalProducer`. public func lift<U, F, V, G>(_ transform: @escaping (Signal<Value, Error>) -> (Signal<U, F>) -> Signal<V, G>) -> (Signal<U, F>) -> SignalProducer<V, G> { return { otherSignal in return self.liftRight(transform)(SignalProducer(otherSignal)) } } /// Map each value in the producer to a new value. /// /// - parameters: /// - transform: A closure that accepts a value and returns a different /// value. /// /// - returns: A signal producer that, when started, will send a mapped /// value of `self.` public func map<U>(_ transform: @escaping (Value) -> U) -> SignalProducer<U, Error> { return lift { $0.map(transform) } } /// Map errors in the producer to a new error. /// /// - parameters: /// - transform: A closure that accepts an error object and returns a /// different error. /// /// - returns: A producer that emits errors of new type. public func mapError<F>(_ transform: @escaping (Error) -> F) -> SignalProducer<Value, F> { return lift { $0.mapError(transform) } } /// Preserve only the values of the producer that pass the given predicate. /// /// - parameters: /// - predicate: A closure that accepts value and returns `Bool` denoting /// whether value has passed the test. /// /// - returns: A producer that, when started, will send only the values /// passing the given predicate. public func filter(_ predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> { return lift { $0.filter(predicate) } } /// Yield the first `count` values from the input producer. /// /// - precondition: `count` must be non-negative number. /// /// - parameters: /// - count: A number of values to take from the signal. /// /// - returns: A producer that, when started, will yield the first `count` /// values from `self`. public func take(first count: Int) -> SignalProducer<Value, Error> { return lift { $0.take(first: count) } } /// Yield an array of values when `self` completes. /// /// - note: When `self` completes without collecting any value, it will send /// an empty array of values. /// /// - returns: A producer that, when started, will yield an array of values /// when `self` completes. public func collect() -> SignalProducer<[Value], Error> { return lift { $0.collect() } } /// Yield an array of values until it reaches a certain count. /// /// - precondition: `count` should be greater than zero. /// /// - note: When the count is reached the array is sent and the signal /// starts over yielding a new array of values. /// /// - note: When `self` completes any remaining values will be sent, the /// last array may not have `count` values. Alternatively, if were /// not collected any values will sent an empty array of values. /// /// - returns: A producer that, when started, collects at most `count` /// values from `self`, forwards them as a single array and /// completes. public func collect(count: Int) -> SignalProducer<[Value], Error> { precondition(count > 0) return lift { $0.collect(count: count) } } /// Yield an array of values based on a predicate which matches the values /// collected. /// /// - note: When `self` completes any remaining values will be sent, the /// last array may not match `predicate`. Alternatively, if were not /// collected any values will sent an empty array of values. /// /// ```` /// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1) /// /// producer /// .collect { values in values.reduce(0, combine: +) == 8 } /// .startWithValues { print($0) } /// /// observer.send(value: 1) /// observer.send(value: 3) /// observer.send(value: 4) /// observer.send(value: 7) /// observer.send(value: 1) /// observer.send(value: 5) /// observer.send(value: 6) /// observer.sendCompleted() /// /// // Output: /// // [1, 3, 4] /// // [7, 1] /// // [5, 6] /// ```` /// /// - parameters: /// - predicate: Predicate to match when values should be sent (returning /// `true`) or alternatively when they should be collected /// (where it should return `false`). The most recent value /// (`value`) is included in `values` and will be the end of /// the current array of values if the predicate returns /// `true`. /// /// - returns: A producer that, when started, collects values passing the /// predicate and, when `self` completes, forwards them as a /// single array and complets. public func collect(_ predicate: @escaping (_ values: [Value]) -> Bool) -> SignalProducer<[Value], Error> { return lift { $0.collect(predicate) } } /// Yield an array of values based on a predicate which matches the values /// collected and the next value. /// /// - note: When `self` completes any remaining values will be sent, the /// last array may not match `predicate`. Alternatively, if no /// values were collected an empty array will be sent. /// /// ```` /// let (producer, observer) = SignalProducer<Int, NoError>.buffer(1) /// /// producer /// .collect { values, value in value == 7 } /// .startWithValues { print($0) } /// /// observer.send(value: 1) /// observer.send(value: 1) /// observer.send(value: 7) /// observer.send(value: 7) /// observer.send(value: 5) /// observer.send(value: 6) /// observer.sendCompleted() /// /// // Output: /// // [1, 1] /// // [7] /// // [7, 5, 6] /// ```` /// /// - parameters: /// - predicate: Predicate to match when values should be sent (returning /// `true`) or alternatively when they should be collected /// (where it should return `false`). The most recent value /// (`vaule`) is not included in `values` and will be the /// start of the next array of values if the predicate /// returns `true`. /// /// - returns: A signal that will yield an array of values based on a /// predicate which matches the values collected and the next /// value. public func collect(_ predicate: @escaping (_ values: [Value], _ value: Value) -> Bool) -> SignalProducer<[Value], Error> { return lift { $0.collect(predicate) } } /// Forward all events onto the given scheduler, instead of whichever /// scheduler they originally arrived upon. /// /// - parameters: /// - scheduler: A scheduler to deliver events on. /// /// - returns: A producer that, when started, will yield `self` values on /// provided scheduler. public func observe(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> { return lift { $0.observe(on: scheduler) } } /// Combine the latest value of the receiver with the latest value from the /// given producer. /// /// - note: The returned producer will not send a value until both inputs /// have sent at least one value each. /// /// - note: If either producer is interrupted, the returned producer will /// also be interrupted. /// /// - parameters: /// - other: A producer to combine `self`'s value with. /// /// - returns: A producer that, when started, will yield a tuple containing /// values of `self` and given producer. public func combineLatest<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> { return liftLeft(Signal.combineLatest)(other) } /// Combine the latest value of the receiver with the latest value from /// the given signal. /// /// - note: The returned producer will not send a value until both inputs /// have sent at least one value each. /// /// - note: If either input is interrupted, the returned producer will also /// be interrupted. /// /// - parameters: /// - other: A signal to combine `self`'s value with. /// /// - returns: A producer that, when started, will yield a tuple containing /// values of `self` and given signal. public func combineLatest<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> { return lift(Signal.combineLatest(with:))(other) } /// Delay `value` and `completed` events by the given interval, forwarding /// them on the given scheduler. /// /// - note: `failed` and `interrupted` events are always scheduled /// immediately. /// /// - parameters: /// - interval: Interval to delay `value` and `completed` events by. /// - scheduler: A scheduler to deliver delayed events on. /// /// - returns: A producer that, when started, will delay `value` and /// `completed` events and will yield them on given scheduler. public func delay(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> { return lift { $0.delay(interval, on: scheduler) } } /// Skip the first `count` values, then forward everything afterward. /// /// - parameters: /// - count: A number of values to skip. /// /// - returns: A producer that, when started, will skip the first `count` /// values, then forward everything afterward. public func skip(first count: Int) -> SignalProducer<Value, Error> { return lift { $0.skip(first: count) } } /// Treats all Events from the input producer as plain values, allowing them /// to be manipulated just like any other value. /// /// In other words, this brings Events “into the monad.” /// /// - note: When a Completed or Failed event is received, the resulting /// producer will send the Event itself and then complete. When an /// `interrupted` event is received, the resulting producer will /// send the `Event` itself and then interrupt. /// /// - returns: A producer that sends events as its values. public func materialize() -> SignalProducer<Event<Value, Error>, NoError> { return lift { $0.materialize() } } /// Forward the latest value from `self` with the value from `sampler` as a /// tuple, only when `sampler` sends a `value` event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - sampler: A producer that will trigger the delivery of `value` event /// from `self`. /// /// - returns: A producer that will send values from `self` and `sampler`, /// sampled (possibly multiple times) by `sampler`, then complete /// once both input producers have completed, or interrupt if /// either input producer is interrupted. public func sample<T>(with sampler: SignalProducer<T, NoError>) -> SignalProducer<(Value, T), Error> { return liftLeft(Signal.sample(with:))(sampler) } /// Forward the latest value from `self` with the value from `sampler` as a /// tuple, only when `sampler` sends a `value` event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - sampler: A signal that will trigger the delivery of `value` event /// from `self`. /// /// - returns: A producer that, when started, will send values from `self` /// and `sampler`, sampled (possibly multiple times) by /// `sampler`, then complete once both input producers have /// completed, or interrupt if either input producer is /// interrupted. public func sample<T>(with sampler: Signal<T, NoError>) -> SignalProducer<(Value, T), Error> { return lift(Signal.sample(with:))(sampler) } /// Forward the latest value from `self` whenever `sampler` sends a `value` /// event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - sampler: A producer that will trigger the delivery of `value` event /// from `self`. /// /// - returns: A producer that, when started, will send values from `self`, /// sampled (possibly multiple times) by `sampler`, then complete /// once both input producers have completed, or interrupt if /// either input producer is interrupted. public func sample(on sampler: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftLeft(Signal.sample(on:))(sampler) } /// Forward the latest value from `self` whenever `sampler` sends a `value` /// event. /// /// - note: If `sampler` fires before a value has been observed on `self`, /// nothing happens. /// /// - parameters: /// - trigger: A signal whose `value` or `completed` events will start the /// deliver of events on `self`. /// /// - returns: A producer that will send values from `self`, sampled /// (possibly multiple times) by `sampler`, then complete once /// both inputs have completed, or interrupt if either input is /// interrupted. public func sample(on sampler: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.sample(on:))(sampler) } /// Forward the latest value from `samplee` with the value from `self` as a /// tuple, only when `self` sends a `value` event. /// This is like a flipped version of `sample(with:)`, but `samplee`'s /// terminal events are completely ignored. /// /// - note: If `self` fires before a value has been observed on `samplee`, /// nothing happens. /// /// - parameters: /// - samplee: A producer whose latest value is sampled by `self`. /// /// - returns: A signal that will send values from `self` and `samplee`, /// sampled (possibly multiple times) by `self`, then terminate /// once `self` has terminated. **`samplee`'s terminated events /// are ignored**. public func withLatest<U>(from samplee: SignalProducer<U, NoError>) -> SignalProducer<(Value, U), Error> { return liftRight(Signal.withLatest)(samplee) } /// Forward the latest value from `samplee` with the value from `self` as a /// tuple, only when `self` sends a `value` event. /// This is like a flipped version of `sample(with:)`, but `samplee`'s /// terminal events are completely ignored. /// /// - note: If `self` fires before a value has been observed on `samplee`, /// nothing happens. /// /// - parameters: /// - samplee: A signal whose latest value is sampled by `self`. /// /// - returns: A signal that will send values from `self` and `samplee`, /// sampled (possibly multiple times) by `self`, then terminate /// once `self` has terminated. **`samplee`'s terminated events /// are ignored**. public func withLatest<U>(from samplee: Signal<U, NoError>) -> SignalProducer<(Value, U), Error> { return lift(Signal.withLatest)(samplee) } /// Forwards events from `self` until `lifetime` ends, at which point the /// returned producer will complete. /// /// - parameters: /// - lifetime: A lifetime whose `ended` signal will cause the returned /// producer to complete. /// /// - returns: A producer that will deliver events until `lifetime` ends. public func take(during lifetime: Lifetime) -> SignalProducer<Value, Error> { return take(until: lifetime.ended) } /// Forward events from `self` until `trigger` sends a `value` or `completed` /// event, at which point the returned producer will complete. /// /// - parameters: /// - trigger: A producer whose `value` or `completed` events will stop the /// delivery of `value` events from `self`. /// /// - returns: A producer that will deliver events until `trigger` sends /// `value` or `completed` events. public func take(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftRight(Signal.take(until:))(trigger) } /// Forward events from `self` until `trigger` sends a `value` or /// `completed` event, at which point the returned producer will complete. /// /// - parameters: /// - trigger: A signal whose `value` or `completed` events will stop the /// delivery of `value` events from `self`. /// /// - returns: A producer that will deliver events until `trigger` sends /// `value` or `completed` events. public func take(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.take(until:))(trigger) } /// Do not forward any values from `self` until `trigger` sends a `value` /// or `completed`, at which point the returned producer behaves exactly /// like `producer`. /// /// - parameters: /// - trigger: A producer whose `value` or `completed` events will start /// the deliver of events on `self`. /// /// - returns: A producer that will deliver events once the `trigger` sends /// `value` or `completed` events. public func skip(until trigger: SignalProducer<(), NoError>) -> SignalProducer<Value, Error> { return liftRight(Signal.skip(until:))(trigger) } /// Do not forward any values from `self` until `trigger` sends a `value` /// or `completed`, at which point the returned signal behaves exactly like /// `signal`. /// /// - parameters: /// - trigger: A signal whose `value` or `completed` events will start the /// deliver of events on `self`. /// /// - returns: A producer that will deliver events once the `trigger` sends /// `value` or `completed` events. public func skip(until trigger: Signal<(), NoError>) -> SignalProducer<Value, Error> { return lift(Signal.skip(until:))(trigger) } /// Forward events from `self` with history: values of the returned producer /// are a tuple whose first member is the previous value and whose second /// member is the current value. `initial` is supplied as the first member /// when `self` sends its first value. /// /// - parameters: /// - initial: A value that will be combined with the first value sent by /// `self`. /// /// - returns: A producer that sends tuples that contain previous and /// current sent values of `self`. public func combinePrevious(_ initial: Value) -> SignalProducer<(Value, Value), Error> { return lift { $0.combinePrevious(initial) } } /// Send only the final value and then immediately completes. /// /// - parameters: /// - initial: Initial value for the accumulator. /// - combine: A closure that accepts accumulator and sent value of /// `self`. /// /// - returns: A producer that sends accumulated value after `self` /// completes. public func reduce<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> { return lift { $0.reduce(initial, combine) } } /// Aggregate `self`'s values into a single combined value. When `self` /// emits its first value, `combine` is invoked with `initial` as the first /// argument and that emitted value as the second argument. The result is /// emitted from the producer returned from `scan`. That result is then /// passed to `combine` as the first argument when the next value is /// emitted, and so on. /// /// - parameters: /// - initial: Initial value for the accumulator. /// - combine: A closure that accepts accumulator and sent value of /// `self`. /// /// - returns: A producer that sends accumulated value each time `self` /// emits own value. public func scan<U>(_ initial: U, _ combine: @escaping (U, Value) -> U) -> SignalProducer<U, Error> { return lift { $0.scan(initial, combine) } } /// Forward only those values from `self` which do not pass `isRepeat` with /// respect to the previous value. /// /// - note: The first value is always forwarded. /// /// - returns: A producer that does not send two equal values sequentially. public func skipRepeats(_ isRepeat: @escaping (Value, Value) -> Bool) -> SignalProducer<Value, Error> { return lift { $0.skipRepeats(isRepeat) } } /// Do not forward any values from `self` until `predicate` returns false, /// at which point the returned producer behaves exactly like `self`. /// /// - parameters: /// - predicate: A closure that accepts a value and returns whether `self` /// should still not forward that value to a `producer`. /// /// - returns: A producer that sends only forwarded values from `self`. public func skip(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> { return lift { $0.skip(while: predicate) } } /// Forward events from `self` until `replacement` begins sending events. /// /// - parameters: /// - replacement: A producer to wait to wait for values from and start /// sending them as a replacement to `self`'s values. /// /// - returns: A producer which passes through `value`, `failed`, and /// `interrupted` events from `self` until `replacement` sends an /// event, at which point the returned producer will send that /// event and switch to passing through events from `replacement` /// instead, regardless of whether `self` has sent events /// already. public func take(untilReplacement signal: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> { return liftRight(Signal.take(untilReplacement:))(signal) } /// Forwards events from `self` until `replacement` begins sending events. /// /// - parameters: /// - replacement: A signal to wait to wait for values from and start /// sending them as a replacement to `self`'s values. /// /// - returns: A producer which passes through `value`, `failed`, and /// `interrupted` events from `self` until `replacement` sends an /// event, at which point the returned producer will send that /// event and switch to passing through events from `replacement` /// instead, regardless of whether `self` has sent events /// already. public func take(untilReplacement signal: Signal<Value, Error>) -> SignalProducer<Value, Error> { return lift(Signal.take(untilReplacement:))(signal) } /// Wait until `self` completes and then forward the final `count` values /// on the returned producer. /// /// - parameters: /// - count: Number of last events to send after `self` completes. /// /// - returns: A producer that receives up to `count` values from `self` /// after `self` completes. public func take(last count: Int) -> SignalProducer<Value, Error> { return lift { $0.take(last: count) } } /// Forward any values from `self` until `predicate` returns false, at which /// point the returned producer will complete. /// /// - parameters: /// - predicate: A closure that accepts value and returns `Bool` value /// whether `self` should forward it to `signal` and continue /// sending other events. /// /// - returns: A producer that sends events until the values sent by `self` /// pass the given `predicate`. public func take(while predicate: @escaping (Value) -> Bool) -> SignalProducer<Value, Error> { return lift { $0.take(while: predicate) } } /// Zip elements of two producers into pairs. The elements of any Nth pair /// are the Nth elements of the two input producers. /// /// - parameters: /// - other: A producer to zip values with. /// /// - returns: A producer that sends tuples of `self` and `otherProducer`. public func zip<U>(with other: SignalProducer<U, Error>) -> SignalProducer<(Value, U), Error> { return liftLeft(Signal.zip(with:))(other) } /// Zip elements of this producer and a signal into pairs. The elements of /// any Nth pair are the Nth elements of the two. /// /// - parameters: /// - other: A signal to zip values with. /// /// - returns: A producer that sends tuples of `self` and `otherSignal`. public func zip<U>(with other: Signal<U, Error>) -> SignalProducer<(Value, U), Error> { return lift(Signal.zip(with:))(other) } /// Apply `operation` to values from `self` with `success`ful results /// forwarded on the returned producer and `failure`s sent as `failed` /// events. /// /// - parameters: /// - operation: A closure that accepts a value and returns a `Result`. /// /// - returns: A producer that receives `success`ful `Result` as `value` /// event and `failure` as `failed` event. public func attempt(operation: @escaping (Value) -> Result<(), Error>) -> SignalProducer<Value, Error> { return lift { $0.attempt(operation) } } /// Apply `operation` to values from `self` with `success`ful results /// mapped on the returned producer and `failure`s sent as `failed` events. /// /// - parameters: /// - operation: A closure that accepts a value and returns a result of /// a mapped value as `success`. /// /// - returns: A producer that sends mapped values from `self` if returned /// `Result` is `success`ful, `failed` events otherwise. public func attemptMap<U>(_ operation: @escaping (Value) -> Result<U, Error>) -> SignalProducer<U, Error> { return lift { $0.attemptMap(operation) } } /// Throttle values sent by the receiver, so that at least `interval` /// seconds pass between each, then forwards them on the given scheduler. /// /// - note: If multiple values are received before the interval has elapsed, /// the latest value is the one that will be passed on. /// /// - norw: If `self` terminates while a value is being throttled, that /// value will be discarded and the returned producer will terminate /// immediately. /// /// - parameters: /// - interval: Number of seconds to wait between sent values. /// - scheduler: A scheduler to deliver events on. /// /// - returns: A producer that sends values at least `interval` seconds /// appart on a given scheduler. public func throttle(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> { return lift { $0.throttle(interval, on: scheduler) } } /// Conditionally throttles values sent on the receiver whenever /// `shouldThrottle` is true, forwarding values on the given scheduler. /// /// - note: While `shouldThrottle` remains false, values are forwarded on the /// given scheduler. If multiple values are received while /// `shouldThrottle` is true, the latest value is the one that will /// be passed on. /// /// - note: If the input signal terminates while a value is being throttled, /// that value will be discarded and the returned signal will /// terminate immediately. /// /// - note: If `shouldThrottle` completes before the receiver, and its last /// value is `true`, the returned signal will remain in the throttled /// state, emitting no further values until it terminates. /// /// - parameters: /// - shouldThrottle: A boolean property that controls whether values /// should be throttled. /// - scheduler: A scheduler to deliver events on. /// /// - returns: A producer that sends values only while `shouldThrottle` is false. public func throttle<P: PropertyProtocol>(while shouldThrottle: P, on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> where P.Value == Bool { // Using `Property.init(_:)` avoids capturing a strong reference // to `shouldThrottle`, so that we don't extend its lifetime. let shouldThrottle = Property(shouldThrottle) return lift { $0.throttle(while: shouldThrottle, on: scheduler) } } /// Debounce values sent by the receiver, such that at least `interval` /// seconds pass after the receiver has last sent a value, then /// forward the latest value on the given scheduler. /// /// - note: If multiple values are received before the interval has elapsed, /// the latest value is the one that will be passed on. /// /// - note: If `self` terminates while a value is being debounced, /// that value will be discarded and the returned producer will /// terminate immediately. /// /// - parameters: /// - interval: A number of seconds to wait before sending a value. /// - scheduler: A scheduler to send values on. /// /// - returns: A producer that sends values that are sent from `self` at /// least `interval` seconds apart. public func debounce(_ interval: TimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> { return lift { $0.debounce(interval, on: scheduler) } } /// Forward events from `self` until `interval`. Then if producer isn't /// completed yet, fails with `error` on `scheduler`. /// /// - note: If the interval is 0, the timeout will be scheduled immediately. /// The producer must complete synchronously (or on a faster /// scheduler) to avoid the timeout. /// /// - parameters: /// - interval: Number of seconds to wait for `self` to complete. /// - error: Error to send with `failed` event if `self` is not completed /// when `interval` passes. /// - scheduler: A scheduler to deliver error on. /// /// - returns: A producer that sends events for at most `interval` seconds, /// then, if not `completed` - sends `error` with `failed` event /// on `scheduler`. public func timeout(after interval: TimeInterval, raising error: Error, on scheduler: DateSchedulerProtocol) -> SignalProducer<Value, Error> { return lift { $0.timeout(after: interval, raising: error, on: scheduler) } } } extension SignalProducerProtocol where Value: OptionalProtocol { /// Unwraps non-`nil` values and forwards them on the returned signal, `nil` /// values are dropped. /// /// - returns: A producer that sends only non-nil values. public func skipNil() -> SignalProducer<Value.Wrapped, Error> { return lift { $0.skipNil() } } } extension SignalProducerProtocol where Value: EventProtocol, Error == NoError { /// The inverse of materialize(), this will translate a producer of `Event` /// _values_ into a producer of those events themselves. /// /// - returns: A producer that sends values carried by `self` events. public func dematerialize() -> SignalProducer<Value.Value, Value.Error> { return lift { $0.dematerialize() } } } extension SignalProducerProtocol where Error == NoError { /// Promote a producer that does not generate failures into one that can. /// /// - note: This does not actually cause failers to be generated for the /// given producer, but makes it easier to combine with other /// producers that may fail; for example, with operators like /// `combineLatestWith`, `zipWith`, `flatten`, etc. /// /// - parameters: /// - _ An `ErrorType`. /// /// - returns: A producer that has an instantiatable `ErrorType`. public func promoteErrors<F: Swift.Error>(_: F.Type) -> SignalProducer<Value, F> { return lift { $0.promoteErrors(F.self) } } /// Forward events from `self` until `interval`. Then if producer isn't /// completed yet, fails with `error` on `scheduler`. /// /// - note: If the interval is 0, the timeout will be scheduled immediately. /// The producer must complete synchronously (or on a faster /// scheduler) to avoid the timeout. /// /// - parameters: /// - interval: Number of seconds to wait for `self` to complete. /// - error: Error to send with `failed` event if `self` is not completed /// when `interval` passes. /// - scheudler: A scheduler to deliver error on. /// /// - returns: A producer that sends events for at most `interval` seconds, /// then, if not `completed` - sends `error` with `failed` event /// on `scheduler`. public func timeout<NewError: Swift.Error>( after interval: TimeInterval, raising error: NewError, on scheduler: DateSchedulerProtocol ) -> SignalProducer<Value, NewError> { return lift { $0.timeout(after: interval, raising: error, on: scheduler) } } /// Wait for completion of `self`, *then* forward all events from /// `replacement`. /// /// - note: All values sent from `self` are ignored. /// /// - parameters: /// - replacement: A producer to start when `self` completes. /// /// - returns: A producer that sends events from `self` and then from /// `replacement` when `self` completes. public func then<U, NewError: Swift.Error>(_ replacement: SignalProducer<U, NewError>) -> SignalProducer<U, NewError> { return self .promoteErrors(NewError.self) .then(replacement) } /// Apply a failable `operation` to values from `self` with successful /// results forwarded on the returned producer and thrown errors sent as /// failed events. /// /// - parameters: /// - operation: A failable closure that accepts a value. /// /// - returns: A producer that forwards successes as `value` events and thrown /// errors as `failed` events. public func attempt(_ operation: @escaping (Value) throws -> Void) -> SignalProducer<Value, AnyError> { return lift { $0.attempt(operation) } } /// Apply a failable `operation` to values from `self` with successful /// results mapped on the returned producer and thrown errors sent as /// failed events. /// /// - parameters: /// - operation: A failable closure that accepts a value and attempts to /// transform it. /// /// - returns: A producer that sends successfully mapped values from `self`, /// or thrown errors as `failed` events. public func attemptMap<U>(_ operation: @escaping (Value) throws -> U) -> SignalProducer<U, AnyError> { return lift { $0.attemptMap(operation) } } } extension SignalProducer { /// Create a `SignalProducer` that will attempt the given operation once for /// each invocation of `start()`. /// /// Upon success, the started signal will send the resulting value then /// complete. Upon failure, the started signal will fail with the error that /// occurred. /// /// - parameters: /// - operation: A closure that returns instance of `Result`. /// /// - returns: A `SignalProducer` that will forward `success`ful `result` as /// `value` event and then complete or `failed` event if `result` /// is a `failure`. public static func attempt(_ operation: @escaping () -> Result<Value, Error>) -> SignalProducer { return self.init { observer, disposable in operation().analysis(ifSuccess: { value in observer.send(value: value) observer.sendCompleted() }, ifFailure: { error in observer.send(error: error) }) } } } extension SignalProducerProtocol where Error == AnyError { /// Create a `SignalProducer` that will attempt the given failable operation once for /// each invocation of `start()`. /// /// Upon success, the started producer will send the resulting value then /// complete. Upon failure, the started signal will fail with the error that /// occurred. /// /// - parameters: /// - operation: A failable closure. /// /// - returns: A `SignalProducer` that will forward a success as a `value` /// event and then complete or `failed` event if the closure throws. public static func attempt(_ operation: @escaping () throws -> Value) -> SignalProducer<Value, Error> { return .attempt { ReactiveSwift.materialize { try operation() } } } /// Apply a failable `operation` to values from `self` with successful /// results forwarded on the returned producer and thrown errors sent as /// failed events. /// /// - parameters: /// - operation: A failable closure that accepts a value. /// /// - returns: A producer that forwards successes as `value` events and thrown /// errors as `failed` events. public func attempt(_ operation: @escaping (Value) throws -> Void) -> SignalProducer<Value, AnyError> { return lift { $0.attempt(operation) } } /// Apply a failable `operation` to values from `self` with successful /// results mapped on the returned producer and thrown errors sent as /// failed events. /// /// - parameters: /// - operation: A failable closure that accepts a value and attempts to /// transform it. /// /// - returns: A producer that sends successfully mapped values from `self`, /// or thrown errors as `failed` events. public func attemptMap<U>(_ operation: @escaping (Value) throws -> U) -> SignalProducer<U, AnyError> { return lift { $0.attemptMap(operation) } } } extension SignalProducerProtocol where Value: Equatable { /// Forward only those values from `self` which are not duplicates of the /// immedately preceding value. /// /// - note: The first value is always forwarded. /// /// - returns: A producer that does not send two equal values sequentially. public func skipRepeats() -> SignalProducer<Value, Error> { return lift { $0.skipRepeats() } } } extension SignalProducerProtocol { /// Forward only those values from `self` that have unique identities across /// the set of all values that have been seen. /// /// - note: This causes the identities to be retained to check for /// uniqueness. /// /// - parameters: /// - transform: A closure that accepts a value and returns identity /// value. /// /// - returns: A producer that sends unique values during its lifetime. public func uniqueValues<Identity: Hashable>(_ transform: @escaping (Value) -> Identity) -> SignalProducer<Value, Error> { return lift { $0.uniqueValues(transform) } } } extension SignalProducerProtocol where Value: Hashable { /// Forward only those values from `self` that are unique across the set of /// all values that have been seen. /// /// - note: This causes the values to be retained to check for uniqueness. /// Providing a function that returns a unique value for each sent /// value can help you reduce the memory footprint. /// /// - returns: A producer that sends unique values during its lifetime. public func uniqueValues() -> SignalProducer<Value, Error> { return lift { $0.uniqueValues() } } } extension SignalProducerProtocol { /// Injects side effects to be performed upon the specified producer events. /// /// - note: In a composed producer, `starting` is invoked in the reverse /// direction of the flow of events. /// /// - parameters: /// - starting: A closure that is invoked before the producer is started. /// - started: A closure that is invoked after the producer is started. /// - event: A closure that accepts an event and is invoked on every /// received event. /// - failed: A closure that accepts error object and is invoked for /// `failed` event. /// - completed: A closure that is invoked for `completed` event. /// - interrupted: A closure that is invoked for `interrupted` event. /// - terminated: A closure that is invoked for any terminating event. /// - disposed: A closure added as disposable when signal completes. /// - value: A closure that accepts a value from `value` event. /// /// - returns: A producer with attached side-effects for given event cases. public func on( starting: (() -> Void)? = nil, started: (() -> Void)? = nil, event: ((Event<Value, Error>) -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, terminated: (() -> Void)? = nil, disposed: (() -> Void)? = nil, value: ((Value) -> Void)? = nil ) -> SignalProducer<Value, Error> { return SignalProducer { observer, compositeDisposable in starting?() defer { started?() } self.startWithSignal { signal, disposable in compositeDisposable += disposable signal .on( event: event, failed: failed, completed: completed, interrupted: interrupted, terminated: terminated, disposed: disposed, value: value ) .observe(observer) } } } /// Start the returned producer on the given `Scheduler`. /// /// - note: This implies that any side effects embedded in the producer will /// be performed on the given scheduler as well. /// /// - note: Events may still be sent upon other schedulers — this merely /// affects where the `start()` method is run. /// /// - parameters: /// - scheduler: A scheduler to deliver events on. /// /// - returns: A producer that will deliver events on given `scheduler` when /// started. public func start(on scheduler: SchedulerProtocol) -> SignalProducer<Value, Error> { return SignalProducer { observer, compositeDisposable in compositeDisposable += scheduler.schedule { self.startWithSignal { signal, signalDisposable in compositeDisposable += signalDisposable signal.observe(observer) } } } } } extension SignalProducerProtocol { /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> { return a.combineLatest(with: b) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> { return combineLatest(a, b) .combineLatest(with: c) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> { return combineLatest(a, b, c) .combineLatest(with: d) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> { return combineLatest(a, b, c, d) .combineLatest(with: e) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> { return combineLatest(a, b, c, d, e) .combineLatest(with: f) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E, F, G>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> { return combineLatest(a, b, c, d, e, f) .combineLatest(with: g) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> { return combineLatest(a, b, c, d, e, f, g) .combineLatest(with: h) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> { return combineLatest(a, b, c, d, e, f, g, h) .combineLatest(with: i) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. public static func combineLatest<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> { return combineLatest(a, b, c, d, e, f, g, h, i) .combineLatest(with: j) .map(repack) } /// Combines the values of all the given producers, in the manner described by /// `combineLatestWith`. Will return an empty `SignalProducer` if the sequence is empty. public static func combineLatest<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element == SignalProducer<Value, Error> { var generator = producers.makeIterator() if let first = generator.next() { let initial = first.map { [$0] } return IteratorSequence(generator).reduce(initial) { producer, next in producer.combineLatest(with: next).map { $0.0 + [$0.1] } } } return .empty } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>) -> SignalProducer<(Value, B), Error> { return a.zip(with: b) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>) -> SignalProducer<(Value, B, C), Error> { return zip(a, b) .zip(with: c) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>) -> SignalProducer<(Value, B, C, D), Error> { return zip(a, b, c) .zip(with: d) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>) -> SignalProducer<(Value, B, C, D, E), Error> { return zip(a, b, c, d) .zip(with: e) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E, F>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>) -> SignalProducer<(Value, B, C, D, E, F), Error> { return zip(a, b, c, d, e) .zip(with: f) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E, F, G>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>) -> SignalProducer<(Value, B, C, D, E, F, G), Error> { return zip(a, b, c, d, e, f) .zip(with: g) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E, F, G, H>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H), Error> { return zip(a, b, c, d, e, f, g) .zip(with: h) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E, F, G, H, I>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I), Error> { return zip(a, b, c, d, e, f, g, h) .zip(with: i) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. public static func zip<B, C, D, E, F, G, H, I, J>(_ a: SignalProducer<Value, Error>, _ b: SignalProducer<B, Error>, _ c: SignalProducer<C, Error>, _ d: SignalProducer<D, Error>, _ e: SignalProducer<E, Error>, _ f: SignalProducer<F, Error>, _ g: SignalProducer<G, Error>, _ h: SignalProducer<H, Error>, _ i: SignalProducer<I, Error>, _ j: SignalProducer<J, Error>) -> SignalProducer<(Value, B, C, D, E, F, G, H, I, J), Error> { return zip(a, b, c, d, e, f, g, h, i) .zip(with: j) .map(repack) } /// Zips the values of all the given producers, in the manner described by /// `zipWith`. Will return an empty `SignalProducer` if the sequence is empty. public static func zip<S: Sequence>(_ producers: S) -> SignalProducer<[Value], Error> where S.Iterator.Element == SignalProducer<Value, Error> { var generator = producers.makeIterator() if let first = generator.next() { let initial = first.map { [$0] } return IteratorSequence(generator).reduce(initial) { producer, next in producer.zip(with: next).map { $0.0 + [$0.1] } } } return .empty } } extension SignalProducerProtocol { /// Repeat `self` a total of `count` times. In other words, start producer /// `count` number of times, each one after previously started producer /// completes. /// /// - note: Repeating `1` time results in an equivalent signal producer. /// /// - note: Repeating `0` times results in a producer that instantly /// completes. /// /// - parameters: /// - count: Number of repetitions. /// /// - returns: A signal producer start sequentially starts `self` after /// previously started producer completes. public func `repeat`(_ count: Int) -> SignalProducer<Value, Error> { precondition(count >= 0) if count == 0 { return .empty } else if count == 1 { return producer } return SignalProducer { observer, disposable in let serialDisposable = SerialDisposable() disposable += serialDisposable func iterate(_ current: Int) { self.startWithSignal { signal, signalDisposable in serialDisposable.inner = signalDisposable signal.observe { event in if case .completed = event { let remainingTimes = current - 1 if remainingTimes > 0 { iterate(remainingTimes) } else { observer.sendCompleted() } } else { observer.action(event) } } } } iterate(count) } } /// Ignore failures up to `count` times. /// /// - precondition: `count` must be non-negative integer. /// /// - parameters: /// - count: Number of retries. /// /// - returns: A signal producer that restarts up to `count` times. public func retry(upTo count: Int) -> SignalProducer<Value, Error> { precondition(count >= 0) if count == 0 { return producer } else { return flatMapError { _ in self.retry(upTo: count - 1) } } } /// Wait for completion of `self`, *then* forward all events from /// `replacement`. Any failure or interruption sent from `self` is /// forwarded immediately, in which case `replacement` will not be started, /// and none of its events will be be forwarded. /// /// - note: All values sent from `self` are ignored. /// /// - parameters: /// - replacement: A producer to start when `self` completes. /// /// - returns: A producer that sends events from `self` and then from /// `replacement` when `self` completes. public func then<U>(_ replacement: SignalProducer<U, Error>) -> SignalProducer<U, Error> { return SignalProducer<U, Error> { observer, observerDisposable in self.startWithSignal { signal, signalDisposable in observerDisposable += signalDisposable signal.observe { event in switch event { case let .failed(error): observer.send(error: error) case .completed: observerDisposable += replacement.start(observer) case .interrupted: observer.sendInterrupted() case .value: break } } } } } /// Wait for completion of `self`, *then* forward all events from /// `replacement`. Any failure or interruption sent from `self` is /// forwarded immediately, in which case `replacement` will not be started, /// and none of its events will be be forwarded. /// /// - note: All values sent from `self` are ignored. /// /// - parameters: /// - replacement: A producer to start when `self` completes. /// /// - returns: A producer that sends events from `self` and then from /// `replacement` when `self` completes. public func then<U>(_ replacement: SignalProducer<U, NoError>) -> SignalProducer<U, Error> { return self.then(replacement.promoteErrors(Error.self)) } /// Start the producer, then block, waiting for the first value. /// /// When a single value or error is sent, the returned `Result` will /// represent those cases. However, when no values are sent, `nil` will be /// returned. /// /// - returns: Result when single `value` or `failed` event is received. /// `nil` when no events are received. public func first() -> Result<Value, Error>? { return take(first: 1).single() } /// Start the producer, then block, waiting for events: `value` and /// `completed`. /// /// When a single value or error is sent, the returned `Result` will /// represent those cases. However, when no values are sent, or when more /// than one value is sent, `nil` will be returned. /// /// - returns: Result when single `value` or `failed` event is received. /// `nil` when 0 or more than 1 events are received. public func single() -> Result<Value, Error>? { let semaphore = DispatchSemaphore(value: 0) var result: Result<Value, Error>? take(first: 2).start { event in switch event { case let .value(value): if result != nil { // Move into failure state after recieving another value. result = nil return } result = .success(value) case let .failed(error): result = .failure(error) semaphore.signal() case .completed, .interrupted: semaphore.signal() } } semaphore.wait() return result } /// Start the producer, then block, waiting for the last value. /// /// When a single value or error is sent, the returned `Result` will /// represent those cases. However, when no values are sent, `nil` will be /// returned. /// /// - returns: Result when single `value` or `failed` event is received. /// `nil` when no events are received. public func last() -> Result<Value, Error>? { return take(last: 1).single() } /// Starts the producer, then blocks, waiting for completion. /// /// When a completion or error is sent, the returned `Result` will represent /// those cases. /// /// - returns: Result when single `completion` or `failed` event is /// received. public func wait() -> Result<(), Error> { return then(SignalProducer<(), Error>(value: ())).last() ?? .success(()) } /// Creates a new `SignalProducer` that will multicast values emitted by /// the underlying producer, up to `capacity`. /// This means that all clients of this `SignalProducer` will see the same /// version of the emitted values/errors. /// /// The underlying `SignalProducer` will not be started until `self` is /// started for the first time. When subscribing to this producer, all /// previous values (up to `capacity`) will be emitted, followed by any new /// values. /// /// If you find yourself needing *the current value* (the last buffered /// value) you should consider using `PropertyType` instead, which, unlike /// this operator, will guarantee at compile time that there's always a /// buffered value. This operator is not recommended in most cases, as it /// will introduce an implicit relationship between the original client and /// the rest, so consider alternatives like `PropertyType`, or representing /// your stream using a `Signal` instead. /// /// This operator is only recommended when you absolutely need to introduce /// a layer of caching in front of another `SignalProducer`. /// /// - precondtion: `capacity` must be non-negative integer. /// /// - parameters: /// - capcity: Number of values to hold. /// /// - returns: A caching producer that will hold up to last `capacity` /// values. public func replayLazily(upTo capacity: Int) -> SignalProducer<Value, Error> { precondition(capacity >= 0, "Invalid capacity: \(capacity)") // This will go "out of scope" when the returned `SignalProducer` goes // out of scope. This lets us know when we're supposed to dispose the // underlying producer. This is necessary because `struct`s don't have // `deinit`. let lifetimeToken = Lifetime.Token() let lifetime = Lifetime(lifetimeToken) let state = Atomic(ReplayState<Value, Error>(upTo: capacity)) let start: Atomic<(() -> Void)?> = Atomic { // Start the underlying producer. self .take(during: lifetime) .start { event in let observers: Bag<Signal<Value, Error>.Observer>? = state.modify { state in defer { state.enqueue(event) } return state.observers } observers?.forEach { $0.action(event) } } } return SignalProducer { observer, disposable in // Don't dispose of the original producer until all observers // have terminated. disposable += { _ = lifetimeToken } while true { var result: Result<RemovalToken?, ReplayError<Value>>! state.modify { result = $0.observe(observer) } switch result! { case let .success(token): if let token = token { disposable += { state.modify { $0.removeObserver(using: token) } } } // Start the underlying producer if it has never been started. start.swap(nil)?() // Terminate the replay loop. return case let .failure(error): error.values.forEach(observer.send(value:)) } } } } } /// Represents a recoverable error of an observer not being ready for an /// attachment to a `ReplayState`, and the observer should replay the supplied /// values before attempting to observe again. private struct ReplayError<Value>: Error { /// The values that should be replayed by the observer. let values: [Value] } private struct ReplayState<Value, Error: Swift.Error> { let capacity: Int /// All cached values. var values: [Value] = [] /// A termination event emitted by the underlying producer. /// /// This will be nil if termination has not occurred. var terminationEvent: Event<Value, Error>? /// The observers currently attached to the caching producer, or `nil` if the /// caching producer was terminated. var observers: Bag<Signal<Value, Error>.Observer>? = Bag() /// The set of in-flight replay buffers. var replayBuffers: [ObjectIdentifier: [Value]] = [:] /// Initialize the replay state. /// /// - parameters: /// - capacity: The maximum amount of values which can be cached by the /// replay state. init(upTo capacity: Int) { self.capacity = capacity } /// Attempt to observe the replay state. /// /// - warning: Repeatedly observing the replay state with the same observer /// should be avoided. /// /// - parameters: /// - observer: The observer to be registered. /// /// - returns: /// If the observer is successfully attached, a `Result.success` with the /// corresponding removal token would be returned. Otherwise, a /// `Result.failure` with a `ReplayError` would be returned. mutating func observe(_ observer: Signal<Value, Error>.Observer) -> Result<RemovalToken?, ReplayError<Value>> { // Since the only use case is `replayLazily`, which always creates a unique // `Observer` for every produced signal, we can use the ObjectIdentifier of // the `Observer` to track them directly. let id = ObjectIdentifier(observer) switch replayBuffers[id] { case .none where !values.isEmpty: // No in-flight replay buffers was found, but the `ReplayState` has one or // more cached values in the `ReplayState`. The observer should replay // them before attempting to observe again. replayBuffers[id] = [] return .failure(ReplayError(values: values)) case let .some(buffer) where !buffer.isEmpty: // An in-flight replay buffer was found with one or more buffered values. // The observer should replay them before attempting to observe again. defer { replayBuffers[id] = [] } return .failure(ReplayError(values: buffer)) case let .some(buffer) where buffer.isEmpty: // Since an in-flight but empty replay buffer was found, the observer is // ready to be attached to the `ReplayState`. replayBuffers.removeValue(forKey: id) default: // No values has to be replayed. The observer is ready to be attached to // the `ReplayState`. break } if let event = terminationEvent { observer.action(event) } return .success(observers?.insert(observer)) } /// Enqueue the supplied event to the replay state. /// /// - parameter: /// - event: The event to be cached. mutating func enqueue(_ event: Event<Value, Error>) { switch event { case let .value(value): for key in replayBuffers.keys { replayBuffers[key]!.append(value) } switch capacity { case 0: // With a capacity of zero, `state.values` can never be filled. break case 1: values = [value] default: values.append(value) let overflow = values.count - capacity if overflow > 0 { values.removeFirst(overflow) } } case .completed, .failed, .interrupted: // Disconnect all observers and prevent future attachments. terminationEvent = event observers = nil } } /// Remove the observer represented by the supplied token. /// /// - parameters: /// - token: The token of the observer to be removed. mutating func removeObserver(using token: RemovalToken) { observers?.remove(using: token) } } /// Create a repeating timer of the given interval, with a reasonable default /// leeway, sending updates on the given scheduler. /// /// - note: This timer will never complete naturally, so all invocations of /// `start()` must be disposed to avoid leaks. /// /// - precondition: Interval must be non-negative number. /// /// - note: If you plan to specify an `interval` value greater than 200,000 /// seconds, use `timer(interval:on:leeway:)` instead /// and specify your own `leeway` value to avoid potential overflow. /// /// - parameters: /// - interval: An interval between invocations. /// - scheduler: A scheduler to deliver events on. /// /// - returns: A producer that sends `NSDate` values every `interval` seconds. public func timer(interval: DispatchTimeInterval, on scheduler: DateSchedulerProtocol) -> SignalProducer<Date, NoError> { // Apple's "Power Efficiency Guide for Mac Apps" recommends a leeway of // at least 10% of the timer interval. return timer(interval: interval, on: scheduler, leeway: interval * 0.1) } /// Creates a repeating timer of the given interval, sending updates on the /// given scheduler. /// /// - note: This timer will never complete naturally, so all invocations of /// `start()` must be disposed to avoid leaks. /// /// - precondition: Interval must be non-negative number. /// /// - precondition: Leeway must be non-negative number. /// /// - parameters: /// - interval: An interval between invocations. /// - scheduler: A scheduler to deliver events on. /// - leeway: Interval leeway. Apple's "Power Efficiency Guide for Mac Apps" /// recommends a leeway of at least 10% of the timer interval. /// /// - returns: A producer that sends `NSDate` values every `interval` seconds. public func timer(interval: DispatchTimeInterval, on scheduler: DateSchedulerProtocol, leeway: DispatchTimeInterval) -> SignalProducer<Date, NoError> { precondition(interval.timeInterval >= 0) precondition(leeway.timeInterval >= 0) return SignalProducer { observer, compositeDisposable in compositeDisposable += scheduler.schedule(after: scheduler.currentDate.addingTimeInterval(interval), interval: interval, leeway: leeway, action: { observer.send(value: scheduler.currentDate) }) } }
mit
0b62b17019b01478228c1cf38dc2aecd
38.38301
437
0.661687
3.798708
false
false
false
false
tamasoszko/sandbox-ios
ExchangeRates/ExchangeRates Widget/TodayViewController.swift
1
4956
// // TodayViewController.swift // ExchangeRates Widget // // Created by Oszkó Tamás on 21/11/15. // Copyright © 2015 Oszi. All rights reserved. // import UIKit import NotificationCenter class TodayViewController: UIViewController, NCWidgetProviding, JBLineChartViewDataSource, JBLineChartViewDelegate { @IBOutlet weak var rateLabel: UILabel! @IBOutlet weak var detailLabel: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var chartView: JBLineChartView! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var rates: [Rate]? let tintColor = UIColor(red: 178/255, green: 211/255, blue: 240/255, alpha: 1) var ratesDownloader: RatesDownloader? override func viewDidLoad() { super.viewDidLoad() chartView.dataSource = self chartView.delegate = self // chartView.minimumValue = 0 segmentedControl.setTitle("EUR", forSegmentAtIndex: 0) segmentedControl.setTitle("NOK", forSegmentAtIndex: 1) activityIndicator.color = tintColor // .tintColor = tintColor segmentedControl.tintColor = tintColor rateLabel.textColor = tintColor detailLabel.textColor = tintColor detailLabel.text = "" } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // refreshRates() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData refreshRates() completionHandler(NCUpdateResult.NewData) } func numberOfLinesInLineChartView(lineChartView: JBLineChartView!) -> UInt { return 1 } func lineChartView(lineChartView: JBLineChartView!, numberOfVerticalValuesAtLineIndex lineIndex: UInt) -> UInt { guard let rates = rates else { return 0 } return UInt(rates.count) } func lineChartView(lineChartView: JBLineChartView!, verticalValueForHorizontalIndex horizontalIndex: UInt, atLineIndex lineIndex: UInt) -> CGFloat { let index = Int(horizontalIndex) let rate = rates![index] return CGFloat(rate.value.floatValue) } func lineChartView(lineChartView: JBLineChartView!, colorForLineAtLineIndex lineIndex: UInt) -> UIColor! { return tintColor } public func lineChartView(lineChartView: JBLineChartView!, widthForLineAtLineIndex lineIndex: UInt) -> CGFloat { return 1.0 } private func refreshRates() { ratesDownloader = createRatesDownloader() rates?.removeAll() chartView.hidden = true activityIndicator.startAnimating() rateLabel.text = "" rateLabel.textColor = self.tintColor detailLabel.text = "" ratesDownloader?.getRates({ (rates: [Rate]?, updated: NSDate?, error: NSError?) -> () in self.activityIndicator.stopAnimating() if let error = error { self.detailLabel.text = "Refresh error \(error.localizedDescription)" return } self.chartView.hidden = false let df = NSDateFormatter() df.dateFormat = "MM/dd HH:mm" self.detailLabel.text = "Last updated \(df.stringFromDate(updated!))" self.rates = rates self.chartView.reloadData() if let lastRate = rates!.first { self.rateLabel.text = "\(lastRate.value)\(lastRate.currencyTo)" if rates?.count > 1 { let lastRate2 = rates![1] let cmp = lastRate.value.compare(lastRate2.value) if cmp == NSComparisonResult.OrderedDescending { self.rateLabel.textColor = UIColor.greenColor() } else if cmp == NSComparisonResult.OrderedAscending { self.rateLabel.textColor = UIColor.redColor() } else { self.rateLabel.textColor = self.tintColor } } } }) } private func createRatesDownloader() -> RatesDownloader { var currency: String? if segmentedControl.selectedSegmentIndex == 0 { currency = "EUR" } else { currency = "NOK" } return MNBRatesDownloader(currency: currency!) } @IBAction func segmentedControlChanged(sender: AnyObject) { refreshRates() } }
apache-2.0
f1d7adc77590da956b18f4d3ecb55b3f
33.158621
152
0.614375
5.472928
false
false
false
false
warchimede/CustomSegues
CustomSegues/CustomSegue.swift
2
9056
// // CustomSegue.swift // CustomSegues // // Created by William Archimede on 16/09/2014. // Copyright (c) 2014 HoodBrains. All rights reserved. // import UIKit import QuartzCore enum CustomSegueAnimation { case Push case SwipeDown case GrowScale case CornerRotate } // MARK: Segue class class CustomSegue: UIStoryboardSegue { var animationType = CustomSegueAnimation.Push override func perform() { switch animationType { case .Push: animatePush() case .SwipeDown: animateSwipeDown() case .GrowScale: animateGrowScale() case .CornerRotate: animateCornerRotate() } } private func animatePush() { let toViewController = destinationViewController let fromViewController = sourceViewController let containerView = fromViewController.view.superview let screenBounds = UIScreen.mainScreen().bounds let finalToFrame = screenBounds let finalFromFrame = CGRectOffset(finalToFrame, -screenBounds.size.width, 0) toViewController.view.frame = CGRectOffset(finalToFrame, screenBounds.size.width, 0) containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, animations: { toViewController.view.frame = finalToFrame fromViewController.view.frame = finalFromFrame }, completion: { finished in let fromVC = self.sourceViewController let toVC = self.destinationViewController fromVC.presentViewController(toVC, animated: false, completion: nil) }) } private func animateSwipeDown() { let toViewController = destinationViewController let fromViewController = sourceViewController let containerView = fromViewController.view.superview let screenBounds = UIScreen.mainScreen().bounds let finalToFrame = screenBounds let finalFromFrame = CGRectOffset(finalToFrame, 0, screenBounds.size.height) toViewController.view.frame = CGRectOffset(finalToFrame, 0, -screenBounds.size.height) containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, animations: { toViewController.view.frame = finalToFrame fromViewController.view.frame = finalFromFrame }, completion: { finished in let fromVC = self.sourceViewController let toVC = self.destinationViewController fromVC.presentViewController(toVC, animated: false, completion: nil) }) } private func animateGrowScale() { let toViewController = destinationViewController let fromViewController = sourceViewController let containerView = fromViewController.view.superview let originalCenter = fromViewController.view.center toViewController.view.transform = CGAffineTransformMakeScale(0.05, 0.05) toViewController.view.center = originalCenter containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { toViewController.view.transform = CGAffineTransformMakeScale(1.0, 1.0) }, completion: { finished in let fromVC = self.sourceViewController let toVC = self.destinationViewController fromVC.presentViewController(toVC, animated: false, completion: nil) }) } private func animateCornerRotate() { let toViewController = destinationViewController let fromViewController = sourceViewController toViewController.view.layer.anchorPoint = CGPointZero fromViewController.view.layer.anchorPoint = CGPointZero toViewController.view.layer.position = CGPointZero fromViewController.view.layer.position = CGPointZero let containerView: UIView? = fromViewController.view.superview toViewController.view.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2)) containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.TransitionNone, animations: { fromViewController.view.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_2)) toViewController.view.transform = CGAffineTransformIdentity }, completion: { finished in let fromVC: UIViewController = self.sourceViewController let toVC: UIViewController = self.destinationViewController fromVC.presentViewController(toVC, animated: false, completion: nil) }) } } // MARK: Unwind Segue class class CustomUnwindSegue: UIStoryboardSegue { var animationType: CustomSegueAnimation = .Push override func perform() { switch animationType { case .Push: animatePush() case .SwipeDown: animateSwipeDown() case .GrowScale: animateGrowScale() case .CornerRotate: animateCornerRotate() } } private func animatePush() { let toViewController = destinationViewController let fromViewController = sourceViewController let containerView = fromViewController.view.superview let screenBounds = UIScreen.mainScreen().bounds let finalToFrame = screenBounds let finalFromFrame = CGRectOffset(finalToFrame, screenBounds.size.width, 0) toViewController.view.frame = CGRectOffset(finalToFrame, -screenBounds.size.width, 0) containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, animations: { toViewController.view.frame = finalToFrame fromViewController.view.frame = finalFromFrame }, completion: { finished in let fromVC: UIViewController = self.sourceViewController fromVC.dismissViewControllerAnimated(false, completion: nil) }) } private func animateSwipeDown() { let toViewController = destinationViewController let fromViewController = sourceViewController let containerView = fromViewController.view.superview let screenBounds = UIScreen.mainScreen().bounds let finalToFrame = screenBounds let finalFromFrame = CGRectOffset(finalToFrame, 0, -screenBounds.size.height) toViewController.view.frame = CGRectOffset(finalToFrame, 0, screenBounds.size.height) containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, animations: { toViewController.view.frame = finalToFrame fromViewController.view.frame = finalFromFrame }, completion: { finished in let fromVC: UIViewController = self.sourceViewController fromVC.dismissViewControllerAnimated(false, completion: nil) }) } private func animateGrowScale() { let toViewController = destinationViewController let fromViewController = sourceViewController fromViewController.view.superview?.insertSubview(toViewController.view, atIndex: 0) UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { fromViewController.view.transform = CGAffineTransformMakeScale(0.05, 0.05) }, completion: { finished in let fromVC = self.sourceViewController fromVC.dismissViewControllerAnimated(false, completion: nil) }) } private func animateCornerRotate() { let toViewController = destinationViewController let fromViewController = sourceViewController toViewController.view.layer.anchorPoint = CGPointZero fromViewController.view.layer.anchorPoint = CGPointZero toViewController.view.layer.position = CGPointZero fromViewController.view.layer.position = CGPointZero let containerView = fromViewController.view.superview containerView?.addSubview(toViewController.view) UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.TransitionNone, animations: { fromViewController.view.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2)) toViewController.view.transform = CGAffineTransformIdentity }, completion: { finished in let fromVC = self.sourceViewController fromVC.dismissViewControllerAnimated(false, completion: nil) }) } }
mit
b46a122ac54b7c3fadbac3950920be56
38.898678
170
0.665636
6.077852
false
false
false
false
64characters/Telephone
Telephone/StoreViewController.swift
1
7364
// // StoreViewController.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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 Cocoa import UseCases final class StoreViewController: NSViewController { private var target: StoreViewEventTarget private var workspace: NSWorkspace @objc private dynamic var products: [PresentationProduct] = [] private let formatter: DateFormatter = { let f = DateFormatter() f.dateStyle = .short return f }() @IBOutlet private var productsTableView: NSTableView! @IBOutlet private var productsListView: NSView! @IBOutlet private var productsFetchErrorView: NSView! @IBOutlet private var progressView: NSView! @IBOutlet private var purchasedView: NSView! @IBOutlet private var termsOfUseField: NSTextField! @IBOutlet private var privacyPolicyField: NSTextField! @IBOutlet private var restorePurchasesButton: NSButton! @IBOutlet private var refreshReceiptButton: NSButton! @IBOutlet private var subscriptionsButton: NSButton! @IBOutlet private weak var productsContentView: NSView! @IBOutlet private weak var productsFetchErrorField: NSTextField! @IBOutlet private weak var progressIndicator: NSProgressIndicator! @IBOutlet private weak var expirationField: NSTextField! init(target: StoreViewEventTarget, workspace: NSWorkspace) { self.target = target self.workspace = workspace super.init(nibName: "StoreViewController", bundle: nil) } required init?(coder: NSCoder) { fatalError() } override func viewDidLoad() { super.viewDidLoad() makeHyperlinks() } override func viewDidAppear() { super.viewDidAppear() target.shouldReloadData() } func updateTarget(_ target: StoreViewEventTarget) { self.target = target } @IBAction func fetchProducts(_ sender: NSButton) { target.didStartProductFetch() } @IBAction func purchaseProduct(_ sender: NSButton) { target.didStartPurchasing(products[productsTableView.row(for: sender)]) } @IBAction func restorePurchases(_ sender: NSButton) { target.didStartPurchaseRestoration() } @IBAction func refreshReceipt(_ sender: NSButton) { makeReceiptRefreshAlert().beginSheetModal(for: view.window!) { response in if response == .alertFirstButtonReturn { self.target.didStartReceiptRefresh() } } } @IBAction func manageSubscriptions(_ sender: NSButton) { workspace.open(URL(string: "https://buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/manageSubscriptions")!) } private func makeHyperlinks() { makeHyperlink(from: termsOfUseField, url: URL(string: "https://www.64characters.com/terms-and-conditions/")!) makeHyperlink(from: privacyPolicyField, url: URL(string: "https://www.64characters.com/privacy/")!) } } extension StoreViewController: StoreView { func showPurchaseCheckProgress() { showProgress() } func show(_ products: [PresentationProduct]) { self.products = products showInProductsContentView(productsListView) } func showProductsFetchError(_ error: String) { productsFetchErrorField.stringValue = error showInProductsContentView(productsFetchErrorView) } func showProductsFetchProgress() { showProgress() } func showPurchaseProgress() { showProgress() } func showPurchaseError(_ error: String) { makePurchaseErrorAlert(text: error).beginSheetModal(for: view.window!, completionHandler: nil) } func showPurchaseRestorationProgress() { showProgress() } func showPurchaseRestorationError(_ error: String) { makeRestorationErrorAlert(text: error).beginSheetModal(for: view.window!, completionHandler: nil) } func disablePurchaseRestoration() { restorePurchasesButton.isEnabled = false refreshReceiptButton.isEnabled = false; } func enablePurchaseRestoration() { subscriptionsButton.isHidden = true restorePurchasesButton.isHidden = false refreshReceiptButton.isHidden = false restorePurchasesButton.isEnabled = true refreshReceiptButton.isEnabled = true } func showPurchased(until date: Date) { expirationField.stringValue = formatter.string(from: date) showInProductsContentView(purchasedView) } func showSubscriptionManagement() { restorePurchasesButton.isHidden = true refreshReceiptButton.isHidden = true subscriptionsButton.isHidden = false } private func showInProductsContentView(_ view: NSView) { productsContentView.subviews.forEach { $0.removeFromSuperview() } productsContentView.addSubview(view) } private func showProgress() { progressIndicator.startAnimation(self) showInProductsContentView(progressView) } } extension StoreViewController: NSTableViewDelegate {} private func makePurchaseErrorAlert(text: String) -> NSAlert { return makeAlert(message: NSLocalizedString("Could not make purchase.", comment: "Product purchase error."), text: text) } private func makeRestorationErrorAlert(text: String) -> NSAlert { return makeAlert(message: NSLocalizedString("Could not restore purchases.", comment: "Purchase restoration error."), text: text) } private func makeAlert(message: String, text: String) -> NSAlert { let result = NSAlert() result.messageText = message result.informativeText = text return result } private func makeReceiptRefreshAlert() -> NSAlert { let result = NSAlert() result.messageText = NSLocalizedString("Refresh receipt?", comment: "Receipt refresh alert message text.") result.informativeText = NSLocalizedString( "Telepohne will quit and the system will attempt to refresh the application receipt. " + "After that, Telephone will be started again. " + "You may be asked to enter your App Store credentials.", comment: "Receipt refresh alert informative text." ) result.addButton(withTitle: NSLocalizedString("Quit and Refresh", comment: "Receipt refresh alert button.")) result.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel button.")).keyEquivalent = "\u{1b}" return result } private func makeHyperlink(from field: NSTextField, url: URL) { field.attributedStringValue = makeHyperlink(from: field.attributedStringValue, url: url) } private func makeHyperlink(from string: NSAttributedString, url: URL) -> NSAttributedString { let result = NSMutableAttributedString(attributedString: string) result.addAttribute(.link, value: url, range: NSRange(location: 0, length: result.length)) return result }
gpl-3.0
15c7cc645895ad29076ec578c0aa8338
33.890995
132
0.710133
4.927711
false
false
false
false
HeartRateLearning/HRLApp
HRLApp/Common/Model/WorkoutIterator.swift
1
794
// // WorkoutIterator.swift // HRLApp // // Created by Enrique de la Torre (dev) on 24/01/2017. // Copyright © 2017 Enrique de la Torre. All rights reserved. // import Foundation // MARK: - Main body struct WorkoutIterator { // MARK: - Private properties fileprivate let first: Workout fileprivate var last: Workout? // MARK: - Init methods init(first: Workout) { self.first = first } } // MARK: - IteratorProtocol methods extension WorkoutIterator: IteratorProtocol { mutating func next() -> Workout? { guard last != nil else { last = first return first } let next = Workout(rawValue: last!.rawValue + 1) if next != nil { last = next } return next } }
mit
f36f99e10d255b3009204c6cefd5a728
17.022727
62
0.58512
4.218085
false
false
false
false
Lickability/PinpointKit
PinpointKit/PinpointKit/Sources/Core/FeedbackViewController.swift
2
10720
// // FeedbackViewController.swift // PinpointKit // // Created by Brian Capps on 2/5/16. // Copyright © 2016 Lickability. All rights reserved. // import UIKit import PhotosUI /// A `UITableViewController` that conforms to `FeedbackCollector` in order to display an interface that allows the user to see, change, and send feedback. public final class FeedbackViewController: UITableViewController { // MARK: - InterfaceCustomizable public var interfaceCustomization: InterfaceCustomization? { didSet { guard isViewLoaded else { return } updateInterfaceCustomization() } } // MARK: - LogSupporting public var logViewer: LogViewer? public var logCollector: LogCollector? public var editor: Editor? // MARK: - FeedbackCollector public weak var feedbackDelegate: FeedbackCollectorDelegate? public var feedbackConfiguration: FeedbackConfiguration? // MARK: - FeedbackViewController /// The screenshot the feedback describes. public var screenshot: UIImage? { didSet { guard isViewLoaded else { return } updateDataSource() } } /// The annotated screenshot the feedback describes. var annotatedScreenshot: UIImage? { didSet { guard isViewLoaded else { return } updateDataSource() } } private var dataSource: FeedbackTableViewDataSource? { didSet { guard isViewLoaded else { return } tableView.dataSource = dataSource } } fileprivate var userEnabledLogCollection = true { didSet { updateDataSource() } } public required init() { super.init(style: .grouped) } @available(*, unavailable) override init(style: UITableView.Style) { super.init(style: .grouped) } @available(*, unavailable) public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - UIViewController public override var preferredStatusBarStyle: UIStatusBarStyle { guard let interfaceCustomization = interfaceCustomization else { assertionFailure(); return .default } let appearance = interfaceCustomization.appearance return appearance.statusBarStyle } public override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 100.0 tableView.rowHeight = UITableView.automaticDimension // Helps to prevent extra spacing from appearing at the top of the table. tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: .leastNormalMagnitude)) tableView.sectionHeaderHeight = .leastNormalMagnitude editor?.delegate = self } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateInterfaceCustomization() } // MARK: - FeedbackViewController private func updateDataSource() { guard let interfaceCustomization = interfaceCustomization else { assertionFailure(); return } let screenshotToDisplay = annotatedScreenshot ?? screenshot dataSource = FeedbackTableViewDataSource(interfaceCustomization: interfaceCustomization, screenshot: screenshotToDisplay, logSupporting: self, userEnabledLogCollection: userEnabledLogCollection, delegate: self) } private func updateInterfaceCustomization() { guard let interfaceCustomization = interfaceCustomization else { assertionFailure(); return } let interfaceText = interfaceCustomization.interfaceText let appearance = interfaceCustomization.appearance title = interfaceText.feedbackCollectorTitle navigationController?.navigationBar.titleTextAttributes = [ .font: appearance.navigationTitleFont, .foregroundColor: appearance.navigationTitleColor ] let sendBarButtonItem = UIBarButtonItem(title: interfaceText.feedbackSendButtonTitle, style: .done, target: self, action: #selector(FeedbackViewController.sendButtonTapped)) sendBarButtonItem.setTitleTextAttributesForAllStates([.font: appearance.feedbackSendButtonFont]) navigationItem.rightBarButtonItem = sendBarButtonItem let backBarButtonItem = UIBarButtonItem(title: interfaceText.feedbackBackButtonTitle, style: .plain, target: nil, action: nil) backBarButtonItem.setTitleTextAttributesForAllStates([.font: appearance.feedbackBackButtonFont]) navigationItem.backBarButtonItem = backBarButtonItem let cancelBarButtonItem: UIBarButtonItem let cancelAction = #selector(FeedbackViewController.cancelButtonTapped) if let cancelButtonTitle = interfaceText.feedbackCancelButtonTitle { cancelBarButtonItem = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: cancelAction) } else { cancelBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: cancelAction) } cancelBarButtonItem.setTitleTextAttributesForAllStates([.font: appearance.feedbackCancelButtonFont]) if presentingViewController != nil { navigationItem.leftBarButtonItem = cancelBarButtonItem } else { navigationItem.leftBarButtonItem = nil } view.tintColor = appearance.tintColor updateDataSource() } @objc private func sendButtonTapped() { guard let feedbackConfiguration = feedbackConfiguration else { assertionFailure("You must set `feedbackConfiguration` before attempting to send feedback.") return } let logs = userEnabledLogCollection ? logCollector?.retrieveLogs() : nil let feedback: Feedback? if let screenshot = annotatedScreenshot { feedback = Feedback(screenshot: .annotated(image: screenshot), logs: logs, configuration: feedbackConfiguration) } else if let screenshot = screenshot { feedback = Feedback(screenshot: .original(image: screenshot), logs: logs, configuration: feedbackConfiguration) } else { feedback = nil } guard let feedbackToSend = feedback else { return assertionFailure("We must have either a screenshot or an edited screenshot!") } feedbackDelegate?.feedbackCollector(self, didCollect: feedbackToSend) } @objc private func cancelButtonTapped() { guard presentingViewController != nil else { assertionFailure("Attempting to dismiss `FeedbackViewController` in unexpected presentation context.") return } dismiss(animated: true, completion: nil) } } // MARK: - FeedbackCollector extension FeedbackViewController: FeedbackCollector { public func collectFeedback(with screenshot: UIImage?, from viewController: UIViewController) { self.screenshot = screenshot annotatedScreenshot = nil viewController.showDetailViewController(self, sender: viewController) } } // MARK: - EditorDelegate extension FeedbackViewController: EditorDelegate { public func editorWillDismiss(_ editor: Editor, with screenshot: UIImage) { annotatedScreenshot = screenshot tableView.reloadData() } } // MARK: - UITableViewDelegate extension FeedbackViewController { public override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { guard let logCollector = logCollector else { assertionFailure("No log collector exists.") return } logViewer?.viewLog(in: logCollector, from: self) } public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { userEnabledLogCollection = !userEnabledLogCollection tableView.reloadRows(at: [indexPath], with: .automatic) } public override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Only leave space under the last section. if section == tableView.numberOfSections - 1 { return tableView.sectionFooterHeight } return .leastNormalMagnitude } } // MARK: - FeedbackTableViewDataSourceDelegate extension FeedbackViewController: FeedbackTableViewDataSourceDelegate { func feedbackTableViewDataSource(feedbackTableViewDataSource: FeedbackTableViewDataSource, didTapScreenshot screenshot: UIImage) { guard let editor = editor else { return } guard let screenshotToEdit = self.screenshot else { return } editor.screenshot = screenshotToEdit let editImageViewController = NavigationController(rootViewController: editor.viewController) editImageViewController.view.tintColor = interfaceCustomization?.appearance.tintColor editImageViewController.modalPresentationStyle = feedbackConfiguration?.presentationStyle ?? .fullScreen present(editImageViewController, animated: true, completion: nil) } @available(iOS 14, *) func feedbackTableViewDataSourceDidRequestScreenshot(feedbackTableViewDataSource: FeedbackTableViewDataSource) { var configuration = PHPickerConfiguration(photoLibrary: .shared()) configuration.filter = .images let pickerController = PHPickerViewController(configuration: configuration) pickerController.delegate = self viewController.present(pickerController, animated: true, completion: nil) } } @available(iOS 14, *) extension FeedbackViewController: PHPickerViewControllerDelegate { public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { guard let result = results.first else { picker.presentingViewController?.dismiss(animated: true) return } result.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { image, _ in OperationQueue.main.addOperation { defer { picker.presentingViewController?.dismiss(animated: true) } guard let image = image as? UIImage else { return } self.screenshot = image self.tableView.reloadData() } }) } }
mit
81b6cb66fc932ba7f18f23c27a010b2b
36.479021
218
0.677768
6.062783
false
true
false
false
rvald/Wynfood.iOS
Wynfood/AuthenticationService.swift
1
2208
// // AuthenticationService.swift // Wynfood // // Created by craftman on 5/25/17. // Copyright © 2017 craftman. All rights reserved. // import Foundation import FirebaseAuth struct AuthenticationService { // MARK: - Methods func isUserLoggedIn() -> Bool { var loggedIn = false if Auth.auth().currentUser != nil { loggedIn = true } return loggedIn } func getUserName() -> String { let defaults = UserDefaults.standard let userName = defaults.object(forKey: "UserName") as! String return userName } func getUserEmail() -> String? { return Auth.auth().currentUser?.email } func logOut() { try! Auth.auth().signOut() } func validateEmail(candidate: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate) } func validatePassword(candidate: String) -> Bool { let passwordRegex = "^(?=.{8,})(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s).*$" return NSPredicate(format: "SELF MATCHES %@", passwordRegex).evaluate(with: candidate) } func isEmailAndPasswordValid(email: String, password: String) -> Bool { return validateEmail(candidate: email) && validatePassword(candidate: password) } func isEmailValid(email: String) -> Bool { return validateEmail(candidate: email) } func isPasswordValid(password: String) -> Bool { return validatePassword(candidate: password) } func isPasswordConfirmend(password: String, passwordConfirm: String) -> Bool { return password == passwordConfirm } func userNameFromEmail(email: String) -> String { var userName = "" for c in email.characters { if c != "@" { userName.append(c) } else { break } } return userName } }
apache-2.0
9d9b1fb14ca401cf74bfcc22a23493a0
23.797753
94
0.532397
4.797826
false
false
false
false
wireapp/wire-ios
WireCommonComponents/SettingsPropertyName.swift
1
3203
// // 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 Foundation /** Available settings - ChatHeadsDisabled: Disable chat heads in conversation and self profile - DisableMarkdown: Disable markdown formatter for messages - DarkMode: Dark mode for conversation - PriofileName: User name - SoundAlerts: Sound alerts level - DisableCrashAndAnalyticsSharing: Opt-Out analytics and App Center - DisableSendButton: Opt-Out of new send button - DisableLinkPreviews: Disable link previews for links you send - Disable(.*): Disable some app features (debug) */ public enum SettingsPropertyName: String, CustomStringConvertible { // User defaults case chatHeadsDisabled = "ChatHeadsDisabled" case notificationContentVisible = "NotificationContentVisible" case disableMarkdown = "Markdown" case darkMode = "DarkMode" case disableSendButton = "DisableSendButton" case disableLinkPreviews = "DisableLinkPreviews" // Profile case profileName = "ProfileName" case handle = "handle" case email = "email" case phone = "phone" case domain = "domain" case team = "team" case accentColor = "AccentColor" // AVS case soundAlerts = "SoundAlerts" case callingConstantBitRate = "constantBitRate" // Sounds case messageSoundName = "MessageSoundName" case callSoundName = "CallSoundName" case pingSoundName = "PingSoundName" // Open In case tweetOpeningOption = "TweetOpeningOption" case mapsOpeningOption = "MapsOpeningOption" case browserOpeningOption = "BrowserOpeningOption" // Persoanl Information // Analytics case disableCrashSharing = "DisableCrashSharing" case disableAnalyticsSharing = "DisableAnalyticsSharing" case receiveNewsAndOffers = "ReceiveNewsAndOffers" // Debug case disableCallKit = "DisableCallKit" case muteIncomingCallsWhileInACall = "MuteIncomingCallsWhileInACall" case callingProtocolStrategy = "CallingProtcolStrategy" case enableBatchCollections = "EnableBatchCollections" case lockApp = "lockApp" case readReceiptsEnabled = "readReceiptsEnabled" case encryptMessagesAtRest = "encryptMessagesAtRest" public var changeNotificationName: String { return self.description + "ChangeNotification" } public var notificationName: Notification.Name { return Notification.Name(changeNotificationName) } public var description: String { return self.rawValue } }
gpl-3.0
88f1f0fe5fca62441f5083f3c6726da6
31.353535
78
0.723072
4.752226
false
false
false
false
BareFeetWare/BFWControls
BFWControls/Modules/Table/Controller/StaticTableViewController.swift
1
7340
// // StaticTableViewController.swift // BFWControls // // Created by Tom Brodhurst-Hill on 29/05/2016. // Copyright © 2016 BareFeetWare. // Free to use at your own risk, with acknowledgement to BareFeetWare. // import UIKit open class StaticTableViewController: AdjustingTableViewController { /// Override in subclass, usually by connecting to an IBOutlet collection. open var excludedCells: [UITableViewCell]? { return nil } // MARK: - Functions open func indexPaths(toInsert cells: [UITableViewCell]) -> [IndexPath] { var indexPaths = [IndexPath]() for section in 0 ..< super.numberOfSections(in: tableView) { var numberOfExcludedRows = 0 for row in 0 ..< super.tableView(tableView, numberOfRowsInSection: superSection(forSection: section)) { let superIndexPath = IndexPath(row: row, section: section) let superCell = super.tableView(tableView, cellForRowAt: superIndexPath) if cells.contains(superCell) && tableView.indexPath(for: superCell) == nil { let indexPath = IndexPath(row: row - numberOfExcludedRows, section: section) indexPaths += [indexPath] } else if excludedCells?.contains(superCell) ?? false { numberOfExcludedRows += 1 } } } return indexPaths } // MARK: - Private functions private func numberOfExcludedSections(beforeSection section: Int) -> Int { var numberOfExcludedSections = 0 for superSection in 0 ..< super.numberOfSections(in: tableView) { if !shouldInclude(superSection: superSection) { numberOfExcludedSections += 1 } else if superSection - numberOfExcludedSections == section { break } } return numberOfExcludedSections } private func numberOfExcludedRowsInSuperSection(before superIndexPath: IndexPath) -> Int { var numberOfExcludedRows = 0 if let excludedCells = excludedCells, !excludedCells.isEmpty { for superRow in 0 ..< super.tableView(tableView, numberOfRowsInSection: superIndexPath.section) { let steppedSuperIndexPath = IndexPath(row: superRow, section: superIndexPath.section) let cell = super.tableView(tableView, cellForRowAt: steppedSuperIndexPath) if excludedCells.contains(cell) { numberOfExcludedRows += 1 } else if superRow - numberOfExcludedRows == superIndexPath.row { break } } } return numberOfExcludedRows } private func numberOfExcludedRows(inSuperSection superSection: Int) -> Int { let numberOfRows = super.tableView(tableView, numberOfRowsInSection: superSection) let indexPath = IndexPath(row: numberOfRows - 1, section: superSection) return numberOfExcludedRowsInSuperSection(before: indexPath) } private func shouldInclude(superSection: Int) -> Bool { guard let excludedCells = excludedCells, !excludedCells.isEmpty else { return true } let rows = 0 ..< super.tableView(tableView, numberOfRowsInSection: superSection) let firstIncludedRow = rows.first { row in let indexPath = IndexPath(row: row, section: superSection) let cell = super.tableView(tableView, cellForRowAt: indexPath) return !excludedCells.contains(cell) } return firstIncludedRow != nil } private func superSection(forSection section: Int) -> Int { guard let excludedCells = excludedCells, !excludedCells.isEmpty else { return section } return section + numberOfExcludedSections(beforeSection: section) } private func superIndexPath(for indexPath: IndexPath) -> IndexPath { guard let excludedCells = excludedCells, !excludedCells.isEmpty else { return indexPath } let superSection = self.superSection(forSection: indexPath.section) let indexPathInSuperSection = IndexPath(row: indexPath.row, section: superSection) let superIndexPath = IndexPath(row: indexPath.row + numberOfExcludedRowsInSuperSection(before: indexPathInSuperSection), section: superSection) return superIndexPath } // MARK: - UITableViewDataSource open override func numberOfSections(in tableView: UITableView) -> Int { let superNumberOfSections = super.numberOfSections(in: tableView) guard let excludedCells = excludedCells, !excludedCells.isEmpty else { return superNumberOfSections } var numberOfSections = 0 for superSection in 0 ..< superNumberOfSections { if shouldInclude(superSection: superSection) { numberOfSections += 1 } } return numberOfSections } open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return super.tableView(tableView, heightForHeaderInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return super.tableView(tableView, heightForFooterInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return super.tableView(tableView, titleForHeaderInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return super.tableView(tableView, titleForFooterInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return super.tableView(tableView, viewForHeaderInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return super.tableView(tableView, viewForFooterInSection: superSection(forSection: section)) } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let excludedCells = excludedCells, !excludedCells.isEmpty else { return super.tableView(tableView, numberOfRowsInSection: section) } let superSection = self.superSection(forSection: section) let numberOfRowsInSuperSection = super.tableView(tableView, numberOfRowsInSection: superSection) let numberOfExcludedRowsInThisSection: Int = numberOfRowsInSuperSection == 0 ? 0 : numberOfExcludedRows(inSuperSection: superSection) return numberOfRowsInSuperSection - numberOfExcludedRowsInThisSection } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: superIndexPath(for: indexPath)) cell.layoutIfNeeded() return cell } }
mit
c83010371faf8133200f03e5d682ee9d
45.157233
128
0.670119
5.468703
false
false
false
false
davidahouse/chute
chute/Notifications/ElasticSearchNotifier.swift
1
2573
// // ElasticSearchNotifier.swift // chute // // Created by David House on 6/20/18. // Copyright © 2018 David House. All rights reserved. // import Foundation class ElasticSearchNotifier { struct ElasticSearchDocument: Codable { let repository: String let platform: String let branch: String let testExecutionDate: Date } func notify(using environment: Environment, including dataCapture: DataCapture, publishedURL: String?) { guard let repository = environment.arguments.githubRepository, let platform = environment.arguments.platform, let branch = environment.arguments.branch else { print("Error missing required parameters for ElasticSearch notifier") return } let document = ElasticSearchDocument(repository: repository, platform: platform, branch: branch, testExecutionDate: dataCapture.testExecutionDate) guard let json = try? JSONEncoder().encode(document) else { print("Error: unable to encode ElasticSearchDocument") return } // Create a URL for this request let esurl = "https://admin:[email protected]:18343/" let index = "\(platform)_\(repository)" let urlString = "\(esurl)/\(index.lowercased())/chute" guard let postURL = URL(string: urlString) else { print("--- Error creating URL for posting to elastic search: \(urlString)") return } var request = URLRequest(url: postURL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = json let semaphore = DispatchSemaphore(value: 0) let dataTask = URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) { (data, _, error) in if let error = error { print("--- Error storing document into elastic search: \(error.localizedDescription)") } if let data = data { let dataString = String(data: data, encoding: .utf8) print("--- Response: \(dataString ?? "")") } semaphore.signal() } dataTask.resume() _ = semaphore.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(30)) } func notify(using environment: Environment, including difference: DataCaptureDifference, publishedURL: String?) { } }
mit
59df8e5d80c9056e1db56d5643a5a5f2
37.38806
166
0.62325
4.984496
false
false
false
false
lukesutton/hekk
Sources/Query.swift
1
1643
public struct Query { let check: Check public init(_ check: Check) { self.check = check } func run(node: Node) -> Bool { return check.run(node) } } public struct Check { let run: (Node) -> Bool } extension Check { public static func match(tag: TagName) -> Check { return Check { node in switch node { case let .regular(name, _, _, _), let .selfClosing(name, _): return name == tag.name default: return false } } } public static func has(attribute: AttributeName) -> Check { return Check { node in switch node { case let .regular(_, attrs, _, _), let .selfClosing(_, attrs): return attrs.first { $0.name.name == attribute.name } != nil default: return false } } } public static func match(attribute: Attribute) -> Check { return Check { node in switch node { case let .regular(_, attrs, _, _), let .selfClosing(_, attrs): return attrs.first { $0 == attribute } != nil default: return false } } } public static func test(_ test: @escaping (Node) -> Bool) -> Check { return Check(run: test) } public static func slot(named: String) -> Check { return Check { node in switch node { case let .slot(n) where n == named: return true default: return false } } } } public func &&(lhs: Check, rhs: Check) -> Check { return Check { node in return lhs.run(node) && rhs.run(node) } } public func ||(lhs: Check, rhs: Check) -> Check { return Check { node in return lhs.run(node) || rhs.run(node) } }
mit
215385da57d1c47b62c9689ecd642ad6
20.906667
70
0.566646
3.803241
false
false
false
false
12207480/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo2ViewController.swift
1
2742
// // iOSDemo2ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/smileyborg/PureLayout // import UIKit import PureLayout class iOSDemo2ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .blueColor() return view }() let redView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .redColor() return view }() let yellowView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .yellowColor() return view }() let greenView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .greenColor() return view }() var didSetupConstraints = false override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(greenView) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func updateViewConstraints() { if (!didSetupConstraints) { // Apply a fixed height of 50 pt to two views at once, and a fixed height of 70 pt to another two views [redView, yellowView].autoSetViewsDimension(.Height, toSize: 50.0) [blueView, greenView].autoSetViewsDimension(.Height, toSize: 70.0) let views = [redView, blueView, yellowView, greenView] // Match the widths of all the views (views as NSArray).autoMatchViewsDimension(.Width) // Pin the red view 20 pt from the top layout guide of the view controller redView.autoPinToTopLayoutGuideOfViewController(self, withInset: 20.0) // Loop over the views, attaching the left edge to the previous view's right edge, // and the top edge to the previous view's bottom edge views.first?.autoPinEdgeToSuperviewEdge(.Left) var previousView: UIView? for view in views { if let previousView = previousView { view.autoPinEdge(.Left, toEdge: .Right, ofView: previousView) view.autoPinEdge(.Top, toEdge: .Bottom, ofView: previousView) } previousView = view } views.last?.autoPinEdgeToSuperviewEdge(.Right) didSetupConstraints = true } super.updateViewConstraints() } }
mit
c56657c8e77f12b7b0af8d1430f790ff
32.851852
115
0.593727
5.345029
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Data/Realm/BusStop/BusStop.swift
1
1368
import RealmSwift import ObjectMapper class BusStop: Object, Mappable { dynamic var id = 0 dynamic var family = 0 dynamic var nameDe: String? dynamic var nameIt: String? dynamic var municDe: String? dynamic var municIt: String? dynamic var lat: Float = 0.0 dynamic var lng: Float = 0.0 required convenience init?(map: Map) { self.init() } convenience init(id: Int, name: String, munic: String, lat: Float, lng: Float, family: Int) { self.init() self.id = id nameDe = name nameIt = name municDe = munic municIt = munic self.lat = lat self.lng = lng self.family = family } override var hashValue: Int { return family } override func isEqual(_ object: Any?) -> Bool { return (object as! BusStop).family == self.family } func name(locale: String = Locales.get()) -> String { return (locale == "de" ? nameDe : nameIt)! } func munic(locale: String = Locales.get()) -> String { return (locale == "de" ? municDe : municIt)! } func mapping(map: Map) { id <- map["id"] family <- map["family"] nameDe <- map["nameDe"] nameIt <- map["nameIt"] municDe <- map["municIt"] lat <- map["lat"] lng <- map["lng"] } }
gpl-3.0
c94cb9b357bc0eb90dfe77335b778c02
21.064516
97
0.55117
3.810585
false
false
false
false
ObjColumnist/FileSystem
Source/Item.swift
1
4882
// // Item.swift // FileSystem // // Created by Spencer MacDonald on 21/09/2016. // Copyright © 2016 Square Bracket Software. All rights reserved. // import Foundation /// `Item` is the base `protocol` for all file system items that can be represented by `Path`. public protocol Item: PathRepresentable, CustomStringConvertible, CustomDebugStringConvertible { /// The path representing the instance of the conforming type. var path: Path { get set } /// Instantiates an instance of the conforming type from a path representation without validating the path. init(_ path: Path) } extension Item /* CustomStringConvertible*/ { /// A textual representation of this instance, returning the represented path's `rawValue`. public var description: String { return path.description } } extension Item /* CustomDebugStringConvertible */ { /// A textual representation of this instance. public var debugDescription: String { return "\(type(of: self)) \(path.rawValue)" } } extension Item { /// Returns if the item exists. public func exists() throws -> Bool { return FileManager.default.fileExists(atPath: path.rawValue) } /// Returns if the item's localized name. public func localizedName() throws -> String { let values = try path.url.resourceValues(forKeys: [.localizedNameKey]) return values.localizedName! } /// Returns if the item is readable. public func isReadable() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isReadableKey]) return values.isReadable! } /// Returns if the item is writebale. public func isWritable() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isWritableKey]) return values.isWritable! } /// Returns if the item is executable. public func isExecutable() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isExecutableKey]) return values.isExecutable! } /// Returns if the item is hidden. public func isHidden() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isHiddenKey]) return values.isHidden! } /// Returns if the item is a package. public func isPackage() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isPackageKey]) return values.isPackage! } /// Returns if the item is a application. @available(iOS 9.0, tvOS 9.0, watchOS 2.0, macOS 10.11, *) public func isApplication() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isApplicationKey]) return values.isApplication! } /// Returns if the item is a alias file. public func isAliasFile() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isAliasFileKey]) return values.isAliasFile! } /// Returns if the item is a symbolic link. public func isSymbolicLink() throws -> Bool { let values = try path.url.resourceValues(forKeys: [.isSymbolicLinkKey]) return values.isSymbolicLink! } /// Returns if the item's creation date. public func creationDate() throws -> Date { let values = try path.url.resourceValues(forKeys: [.creationDateKey]) return values.creationDate! } /// Returns if the item's content access date. public func contentAccessDate() throws -> Date { let values = try path.url.resourceValues(forKeys: [.contentAccessDateKey]) return values.contentAccessDate! } /// Returns if the item's content modification date. public func contentModificationDate() throws -> Date { let values = try path.url.resourceValues(forKeys: [.contentModificationDateKey]) return values.contentModificationDate! } /// Returns if the item's attribute modification date. public func attributeModificationDate() throws -> Date { let values = try path.url.resourceValues(forKeys: [.attributeModificationDateKey]) return values.attributeModificationDate! } /// Returns files attributes for the item /// /// - note: This function does not transverse symbolic links. /// /// - throws: An `Error`. /// /// - returns: attibutes public func attributes() throws -> [FileAttributeKey: Any] { return try FileManager.default.attributesOfItem(atPath: path.rawValue) } /// Returns file attributes for the item /// /// - parameter attributes: The attributes to set on the item. /// /// - throws: An `Error`. public func setAttributes(_ attributes: [FileAttributeKey: Any]) throws { return try FileManager.default.setAttributes(attributes, ofItemAtPath: path.rawValue) } }
bsd-3-clause
9914d1991c606a6cc018c280d3e4e97d
34.369565
111
0.659906
4.818361
false
false
false
false
maurovc/MyMarvel
MyMarvel/HeroComicsController.swift
1
2011
// // HeroComicsController.swift // MyMarvel // // Created by Mauro Vime Castillo on 26/10/16. // Copyright © 2016 Mauro Vime Castillo. All rights reserved. // import Foundation /// Class used to manage the CollectionView for a hero's comics. class HeroComicsController: DefaultManagerViewController { override func loadElements(indexPath: NSIndexPath?) { if state != .Idle { return } state = .Loading DataDownloader.sharedDownloader.getComicsForCharacter("\(hero?.identifier ?? -1)", offset: hero?.comics?.count ?? 0) { (succeeded, elements, error) in self.state = .Idle if succeeded { if let comics = elements as? [Comic] { self.hero?.addComics(comics) } self.collectionView?.reloadData() } else if error != nil { if let indexPath = indexPath { self.reloadErrorCell(indexPath) } else { self.collectionView?.reloadData() } } } } override func elementAtIndexPath(indexPath: NSIndexPath) -> Element? { return hero?.comics?[indexPath.item] } override func needsLoading() -> Bool { return (hero?.hasComics ?? false) } override func hasData() -> Bool { return (hero?.comics?.count ?? 0) > 0 } override func listItemsCount() -> Int { let count = hero?.comics?.count ?? 0 return (needsLoading() ? count + 1 : max(count, 1)) } override func isLoadingCell(indexPath: NSIndexPath) -> Bool { return (indexPath.item == (listItemsCount() - 1)) && needsLoading() } override func sizeForElmentAtIndexPath(indexPath: NSIndexPath) -> CGSize { let collectionSize = DeviceUtils.deviceWidth() - (20.0) return CGSizeMake(isLoadingCell(indexPath) ? 92.0 : (!hasData() ? collectionSize : 92.0), 194.0) } }
mit
30ae07670e7ca16b961e71ac9dee88fa
30.920635
158
0.573632
4.642032
false
false
false
false
kitasuke/SwiftProtobufSample
Client/Client/APIClient.swift
1
4134
// // APIClient.swift // Client // // Created by Yusuke Kita on 12/18/16. // Copyright © 2016 Yusuke Kita. All rights reserved. // import Foundation import SwiftProtobuf class APIClient { let baseURL: URL let contentType: ContentType enum ContentType: String { case protobuf = "application/protobuf" case json = "application/json" var headers: [String: String] { return [ "Accept": rawValue, "Content-Type": rawValue, ] } } init(baseURL: URL = URL(string: "http://localhost:8090")!, contentType: ContentType) { self.baseURL = baseURL self.contentType = contentType } func fetchTalks(success: @escaping ((TalkResponse) -> Void), failure: @escaping ((NetworkError) -> Void)) { get(path: "/v1/talks", success: success, failure: failure) } func like(body: LikeRequest, success: @escaping ((LikeResponse) -> Void), failure: @escaping ((NetworkError) -> Void)) { post(path: "/v1/like", body: body, success: success, failure: failure) } private func get<Response: SwiftProtobuf.Message>(path: String, success: @escaping ((Response) -> Void), failure: @escaping ((NetworkError) -> Void)) { let url = baseURL.appendingPathComponent(path) var request = URLRequest(url: url) request.httpMethod = "GET" request.allHTTPHeaderFields = contentType.headers response(from: request, success: success, failure: failure) } private func post<Body: SwiftProtobuf.Message, Response: SwiftProtobuf.Message>(path: String, body: Body, success: @escaping ((Response) -> Void), failure: @escaping ((NetworkError) -> Void)) { let url = baseURL.appendingPathComponent(path) var request = URLRequest(url: url) request.httpMethod = "POST" request.allHTTPHeaderFields = contentType.headers request.httpBody = try! body.serializedData() response(from: request, success: success, failure: failure) } private func response<Response: SwiftProtobuf.Message>(from request: URLRequest, success: @escaping ((Response) -> Void), failure: @escaping ((NetworkError) -> Void)) { let task = URLSession.shared.dataTask(with: request) { data, urlResponse, error in // ignore unexpected response guard let data = data, let urlResponse = urlResponse as? HTTPURLResponse, let type = urlResponse.allHeaderFields["Content-Type"] as? String, let contentType = ContentType(rawValue: type) else { DispatchQueue.main.async { failure(NetworkError()) } return } // error handling guard 200..<300 ~= urlResponse.statusCode else { let error: NetworkError = self.convertData(data, to: contentType) switch error.code { case .badRequest: DispatchQueue.main.async { failure(error) } case .unauthorized: break case .forbidden: break case .notFound: break case .internalServerError: break default: break } return } let response: Response = self.convertData(data, to: contentType) DispatchQueue.main.async { success(response) } } task.resume() } private func convertData<T: SwiftProtobuf.Message>(_ data: Data, to contentType: ContentType) -> T { switch contentType { case .protobuf: return try! T(serializedData: data) case .json: return try! T(jsonUTF8Data: data) } } }
mit
75008ea538430fd182696b2602b324c6
34.025424
197
0.545367
5.211854
false
false
false
false
Ferrari-lee/firefox-ios
Sync/Synchronizers/ClientsSynchronizer.swift
16
14120
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger private let ClientsStorageVersion = 1 // TODO public protocol Command { static func fromName(command: String, args: [JSON]) -> Command? func run(synchronizer: ClientsSynchronizer) -> Success static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? } // Shit. // We need a way to wipe or reset engines. // We need a way to log out the account. // So when we sync commands, we're gonna need a delegate of some kind. public class WipeCommand: Command { public init?(command: String, args: [JSON]) { return nil } public class func fromName(command: String, args: [JSON]) -> Command? { return WipeCommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return WipeCommand.fromName(name, args: args) } return nil } } public class DisplayURICommand: Command { let uri: NSURL let title: String public init?(command: String, args: [JSON]) { if let uri = args[0].asString?.asURL, title = args[2].asString { self.uri = uri self.title = title } else { // Oh, Swift. self.uri = "http://localhost/".asURL! self.title = "" return nil } } public class func fromName(command: String, args: [JSON]) -> Command? { return DisplayURICommand(command: command, args: args) } public func run(synchronizer: ClientsSynchronizer) -> Success { synchronizer.delegate.displaySentTabForURL(uri, title: title) return succeed() } public static func commandFromSyncCommand(syncCommand: SyncCommand) -> Command? { let json = JSON.parse(syncCommand.value) if let name = json["command"].asString, args = json["args"].asArray { return DisplayURICommand.fromName(name, args: args) } return nil } } let Commands: [String: (String, [JSON]) -> Command?] = [ "wipeAll": WipeCommand.fromName, "wipeEngine": WipeCommand.fromName, // resetEngine // resetAll // logout "displayURI": DisplayURICommand.fromName, ] public class ClientsSynchronizer: BaseSingleCollectionSynchronizer, Synchronizer { public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs) { super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, collection: "clients") } override var storageVersion: Int { return ClientsStorageVersion } var clientRecordLastUpload: Timestamp { set(value) { self.prefs.setLong(value, forKey: "lastClientUpload") } get { return self.prefs.unsignedLongForKey("lastClientUpload") ?? 0 } } public func getOurClientRecord() -> Record<ClientPayload> { let guid = self.scratchpad.clientGUID let json = JSON([ "id": guid, "version": "0.1", // TODO "protocols": ["1.5"], "name": self.scratchpad.clientName, "os": "iOS", "commands": [JSON](), "type": "mobile", "appPackage": NSBundle.mainBundle().bundleIdentifier ?? "org.mozilla.ios.FennecUnknown", "application": DeviceInfo.appName(), "device": DeviceInfo.deviceModel(), // Do better here: Bug 1157518. "formfactor": DeviceInfo.isSimulator() ? "simulator" : "phone", ]) let payload = ClientPayload(json) return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds) } private func clientRecordToLocalClientEntry(record: Record<ClientPayload>) -> RemoteClient { let modified = record.modified let payload = record.payload return RemoteClient(json: payload, modified: modified) } // If this is a fresh start, do a wipe. // N.B., we don't wipe outgoing commands! (TODO: check this when we implement commands!) // N.B., but perhaps we should discard outgoing wipe/reset commands! private func wipeIfNecessary(localClients: RemoteClientsAndTabs) -> Success { if self.lastFetched == 0 { return localClients.wipeClients() } return succeed() } /** * Returns whether any commands were found (and thus a replacement record * needs to be uploaded). Also returns the commands: we run them after we * upload a replacement record. */ private func processCommandsFromRecord(record: Record<ClientPayload>?, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Deferred<Maybe<(Bool, [Command])>> { log.debug("Processing commands from downloaded record.") // TODO: short-circuit based on the modified time of the record we uploaded, so we don't need to skip ahead. if let record = record { let commands = record.payload.commands if !commands.isEmpty { func parse(json: JSON) -> Command? { if let name = json["command"].asString, args = json["args"].asArray, constructor = Commands[name] { return constructor(name, args) } return nil } // TODO: can we do anything better if a command fails? return deferMaybe((true, optFilter(commands.map(parse)))) } } return deferMaybe((false, [])) } private func uploadClientCommands(toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { return localClients.getCommands() >>== { clientCommands in return clientCommands.map { (clientGUID, commands) -> Success in self.syncClientCommands(clientGUID, commands: commands, clientsAndTabs: localClients, withServer: storageClient) }.allSucceed() } } private func syncClientCommands(clientGUID: GUID, commands: [SyncCommand], clientsAndTabs: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let deleteCommands: () -> Success = { return clientsAndTabs.deleteCommands(clientGUID).bind({ x in return succeed() }) } log.debug("Fetching current client record for client \(clientGUID).") let fetch = storageClient.get(clientGUID) return fetch.bind() { result in if let response = result.successValue { let record = response.value if var clientRecord = record.payload.asDictionary { clientRecord["commands"] = JSON(record.payload.commands + commands.map { JSON.parse($0.value) }) let uploadRecord = Record(id: clientGUID, payload: ClientPayload(JSON(clientRecord)), ttl: ThreeWeeksInSeconds) return storageClient.put(uploadRecord, ifUnmodifiedSince: record.modified) >>== { resp in log.debug("Client \(clientGUID) commands upload succeeded.") // Always succeed, even if we couldn't delete the commands. return deleteCommands() } } } else { if let failure = result.failureValue { log.warning("Failed to fetch record with GUID \(clientGUID).") if failure is NotFound<NSHTTPURLResponse> { log.debug("Not waiting to see if the client comes back.") // TODO: keep these around and retry, expiring after a while. // For now we just throw them away so we don't fail every time. return deleteCommands() } if failure is BadRequestError<NSHTTPURLResponse> { log.debug("We made a bad request. Throwing away queued commands.") return deleteCommands() } } } log.error("Client \(clientGUID) commands upload failed: No remote client for GUID") return deferMaybe(UnknownError()) } } /** * Upload our record if either (a) we know we should upload, or (b) * our own notes tell us we're due to reupload. */ private func maybeUploadOurRecord(should: Bool, ifUnmodifiedSince: Timestamp?, toServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { let lastUpload = self.clientRecordLastUpload let expired = lastUpload < (NSDate.now() - (2 * OneDayInMilliseconds)) log.debug("Should we upload our client record? Caller = \(should), expired = \(expired).") if !should && !expired { return succeed() } let iUS: Timestamp? = ifUnmodifiedSince ?? ((lastUpload == 0) ? nil : lastUpload) return storageClient.put(getOurClientRecord(), ifUnmodifiedSince: iUS) >>== { resp in if let ts = resp.metadata.lastModifiedMilliseconds { // Protocol says this should always be present for success responses. log.debug("Client record upload succeeded. New timestamp: \(ts).") self.clientRecordLastUpload = ts } return succeed() } } private func applyStorageResponse(response: StorageResponse<[Record<ClientPayload>]>, toLocalClients localClients: RemoteClientsAndTabs, withServer storageClient: Sync15CollectionClient<ClientPayload>) -> Success { log.debug("Applying clients response.") let records = response.value let responseTimestamp = response.metadata.lastModifiedMilliseconds log.debug("Got \(records.count) client records.") let ourGUID = self.scratchpad.clientGUID var toInsert = [RemoteClient]() var ours: Record<ClientPayload>? = nil for (rec) in records { if rec.id == ourGUID { if rec.modified == self.clientRecordLastUpload { log.debug("Skipping our own unmodified record.") } else { log.debug("Saw our own record in response.") ours = rec } } else { toInsert.append(self.clientRecordToLocalClientEntry(rec)) } } // Apply remote changes. // Collect commands from our own record and reupload if necessary. // Then run the commands and return. return localClients.insertOrUpdateClients(toInsert) >>== { self.processCommandsFromRecord(ours, withServer: storageClient) } >>== { (shouldUpload, commands) in return self.maybeUploadOurRecord(shouldUpload, ifUnmodifiedSince: ours?.modified, toServer: storageClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: storageClient) } >>> { log.debug("Running \(commands.count) commands.") for (command) in commands { command.run(self) } self.lastFetched = responseTimestamp! return succeed() } } } public func synchronizeLocalClients(localClients: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult { log.debug("Synchronizing clients.") if let reason = self.reasonToNotSync(storageClient) { switch reason { case .EngineRemotelyNotEnabled: // This is a hard error for us. return deferMaybe(FatalError(message: "clients not mentioned in meta/global. Server wiped?")) default: return deferMaybe(SyncStatus.NotStarted(reason)) } } let keys = self.scratchpad.keys?.value let encoder = RecordEncoder<ClientPayload>(decode: { ClientPayload($0) }, encode: { $0 }) let encrypter = keys?.encrypter(self.collection, encoder: encoder) if encrypter == nil { log.error("Couldn't make clients encrypter.") return deferMaybe(FatalError(message: "Couldn't make clients encrypter.")) } let clientsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter!) if !self.remoteHasChanges(info) { log.debug("No remote changes for clients. (Last fetched \(self.lastFetched).)") return self.maybeUploadOurRecord(false, ifUnmodifiedSince: nil, toServer: clientsClient) >>> { self.uploadClientCommands(toLocalClients: localClients, withServer: clientsClient) } >>> { deferMaybe(.Completed) } } // TODO: some of the commands we process might involve wiping collections or the // entire profile. We should model this as an explicit status, and return it here // instead of .Completed. return clientsClient.getSince(self.lastFetched) >>== { response in return self.wipeIfNecessary(localClients) >>> { self.applyStorageResponse(response, toLocalClients: localClients, withServer: clientsClient) } } >>> { deferMaybe(.Completed) } } }
mpl-2.0
5ac6d4f80e48243067c29669774026ec
40.28655
218
0.60347
5.258845
false
false
false
false
t4thswm/Course
Course/AddAssignmentViewController.swift
1
10974
// // AddAssignmentViewController.swift // Course // // Created by Archie Yu on 2016/11/21. // Copyright © 2016年 Archie Yu. All rights reserved. // import UIKit import CourseModel class AddAssignmentViewController : UIViewController, UITextFieldDelegate, UITextViewDelegate { var year = 0 let max = 16384 var editingItem = "" var courseOldHeight: CGFloat! var timeOldHeight: CGFloat! var courseVC: ChooseCourseViewController! var timeVC: ChooseTimeViewController! @IBOutlet weak var shadow: UIButton! @IBOutlet weak var courseView: UIView! @IBOutlet weak var courseButton: UIButton! @IBOutlet weak var timeView: UIView! @IBOutlet weak var beginTimeButton: UIButton! @IBOutlet weak var endTimeButton: UIButton! @IBOutlet weak var contentField: UITextField! @IBOutlet weak var contentBackground: UILabel! @IBOutlet weak var notePlaceHolder: UILabel! @IBOutlet weak var noteText: UITextView! @IBOutlet weak var noteBackground: UILabel! var contentHeight: CGFloat! var noteHeight: CGFloat! @IBOutlet weak var courseViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var timeViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var courseViewTopConstraint: NSLayoutConstraint! @IBOutlet weak var toButtom: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 在子控制器中找到课程选择界面和时间选择界面对应的控制器 for vc in self.childViewControllers { switch vc { case is ChooseCourseViewController: courseVC = vc as! ChooseCourseViewController case is ChooseTimeViewController: timeVC = vc as! ChooseTimeViewController default: break } } contentField.delegate = self noteText.delegate = self // 保存课程选择界面和时间选择界面的初始大小,方便视图变化结束后恢复 courseOldHeight = courseView.bounds.height timeOldHeight = timeView.bounds.height contentHeight = contentField.frame.maxY noteHeight = noteText.frame.minY + 125 } override func viewWillAppear(_ animated: Bool) { // 注册键盘出现和键盘消失的通知 let NC = NotificationCenter.default NC.addObserver(self, selector: #selector(AddAssignmentViewController.keyboardWillChangeFrame(notification:)), name:NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) NC.addObserver(self, selector: #selector(AddAssignmentViewController.keyboardWillHide(notification:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { // 注销键盘出现和键盘消失的通知 NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancel(_ sender: UIBarButtonItem) { self.presentingViewController?.dismiss(animated: true, completion: nil) } @IBAction func chooseCourse(_ sender: UIButton) { editingItem = "course" // 将阴影和当前编辑视图前置 self.view.bringSubview(toFront: shadow) self.view.bringSubview(toFront: courseView) // 计算视图弹出时应该变化的大小 let newHeight = courseVC!.beginChooseCourse().height // 渐变 courseViewHeightConstraint.constant = newHeight UIView.animate(withDuration: 0.3, animations: {() -> Void in self.shadow.alpha = 0.7 self.view.layoutIfNeeded() }) } @IBAction func chooseBeginTime(_ sender: UIButton) { editingItem = "beginTime" // 开始时间选择器和结束时间选择器共享,利用editingItem进行区分 timeVC?.editingItem = "beginTime" // 将阴影和当前编辑视图前置 self.view.bringSubview(toFront: shadow) self.view.bringSubview(toFront: timeView) // 计算视图弹出时应该变化的大小 let newSize = timeVC!.beginChooseTime() // 渐变 timeViewHeightConstraint.constant = newSize.height UIView.animate(withDuration: 0.3, animations: {() -> Void in self.shadow.alpha = 0.7 self.view.layoutIfNeeded() }) } @IBAction func chooseEndTime(_ sender: UIButton) { editingItem = "endTime" // 开始时间选择器和结束时间选择器共享,利用editingItem进行区分 timeVC?.editingItem = "endTime" // 将阴影和当前编辑视图前置 self.view.bringSubview(toFront: shadow) self.view.bringSubview(toFront: timeView) // 计算视图弹出时应该变化的大小 let newSize = timeVC!.beginChooseTime() // 渐变 timeViewHeightConstraint.constant = newSize.height UIView.animate(withDuration: 0.3, animations: {() -> Void in self.shadow.alpha = 0.7 self.view.layoutIfNeeded() }) } @IBAction func editContent(_ sender: UITextField) { editingItem = "content" // 将阴影和当前编辑视图前置 self.view.bringSubview(toFront: shadow) self.view.bringSubview(toFront: contentBackground) self.view.bringSubview(toFront: contentField) UIView.animate(withDuration: 0.2, animations: {() -> Void in self.shadow.alpha = 0.7 }) } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { editingItem = "note" // 将阴影和当前编辑视图前置 self.view.bringSubview(toFront: shadow) self.view.bringSubview(toFront: noteBackground) self.view.bringSubview(toFront: noteText) self.view.bringSubview(toFront: notePlaceHolder) UIView.animate(withDuration: 0.2, animations: {() -> Void in self.shadow.alpha = 0.7 }) return true } func textViewDidChange(_ textView: UITextView) { notePlaceHolder.isHidden = (noteText.text != "") } @IBAction func endEdit(_ sender: UIControl) { // 恢复前置区域 self.view.bringSubview(toFront: courseButton) self.view.bringSubview(toFront: beginTimeButton) self.view.bringSubview(toFront: endTimeButton) // 根据正在编辑的区域恢复视图 switch editingItem { case "course": courseVC!.endChooseCourse() courseViewHeightConstraint.constant = courseOldHeight UIView.animate(withDuration: 0.3, animations: {() -> Void in self.shadow.alpha = 0 self.view.layoutIfNeeded() }) case "beginTime", "endTime": timeVC!.endChooseTime() timeViewHeightConstraint.constant = timeOldHeight UIView.animate(withDuration: 0.3, animations: {() -> Void in self.shadow.alpha = 0 self.view.layoutIfNeeded() }) case "content": finishInput(contentField) case "note": finishInput(noteText) default: break } } func keyboardWillChangeFrame(notification: NSNotification) { // 获取键盘高度 let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect let keyboardHeight = keyboardFrame.origin.y // 计算可能需要上移的距离 var deltaY: CGFloat = 0 switch(editingItem) { case "content": deltaY = keyboardHeight - contentHeight - 16 case "note": toButtom.priority = 100 deltaY = keyboardHeight - noteHeight - 16 default: break } // 需要上移时,变化视图位置 if deltaY < 0 { courseViewTopConstraint.constant = deltaY + 16 UIView.animate(withDuration: 0.5, animations: {() -> Void in self.view.layoutIfNeeded() }) } } func keyboardWillHide(notification: NSNotification) { courseViewTopConstraint.constant = 16 toButtom.priority = 750 UIView.animate(withDuration: 0.5, animations: {() -> Void in self.shadow.alpha = 0 self.view.layoutIfNeeded() }) } func finishInput(_ textArea: UIView) { textArea.resignFirstResponder() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { finishInput(textField) return true } // 用于比较两个任务先后次序 func endTimeOrder(a: Assignment, b: Assignment) ->Bool { return a.endTime.compare(b.endTime) == .orderedAscending } @IBAction func addAssignmentButtonDown(_ sender: UIBarButtonItem) { var hint: String! if courseVC?.course == "" { hint = "未选择课程!" } else if !timeVC.finish { hint = "未选择结束时间!" } else if timeVC.beginTime.compare(timeVC.endTime) != ComparisonResult.orderedAscending { hint = "任务结束时间不能晚于开始时间!" } else if contentField.text == "" { hint = "未输入作业内容!" } else { // 将信息保存到assignmentList中 let course = courseVC.course let content = contentField.text! let note = noteText.text! let beginTime = timeVC.beginTime! let endTime = timeVC.endTime! assignmentList.append(Assignment(in: course, todo: content, note: note, from: beginTime, to: endTime)) // 插入列表后按结束时间重新排序 assignmentList.sort(by: endTimeOrder) self.presentingViewController?.dismiss(animated: true, completion: nil) return } let alertController = UIAlertController(title: "提示", message: hint, preferredStyle: .alert) let confirmAction = UIAlertAction(title: "确定", style: .default, handler: nil) alertController.addAction(confirmAction) self.present(alertController, animated: true, completion: nil) } }
gpl-3.0
d13b69d6872fd764316930feea83d585
31.305994
114
0.599063
4.933044
false
false
false
false
dkarsh/SwiftGoal
Carthage/Checkouts/Argo/ArgoTests/Tests/DecodedTests.swift
5
4326
import XCTest import Argo class DecodedTests: XCTestCase { func testDecodedSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) switch user { case let .Success(x): XCTAssert(user.description == "Success(\(x))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedWithError() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) switch user.error { case .Some: XCTAssert(true) case .None: XCTFail("Unexpected Success") } } func testDecodedWithNoError() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) switch user.error { case .Some: XCTFail("Unexpected Error Occurred") case .None: XCTAssert(true) } } func testDecodedTypeMissmatch() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) switch user { case let .Failure(.TypeMismatch(expected, actual)): XCTAssert(user.description == "Failure(TypeMismatch(Expected \(expected), got \(actual)))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMissingKey() { let user: Decoded<User> = decode(JSONFromFile("user_without_key")!) switch user { case let .Failure(.MissingKey(s)): XCTAssert(user.description == "Failure(MissingKey(\(s)))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedCustomError() { let customError: Decoded<Dummy> = decode([:]) switch customError { case let .Failure(e): XCTAssert(e.description == "Custom(My Custom Error)") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMaterializeSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) let materialized = materialize { user.value! } switch materialized { case let .Success(x): XCTAssert(user.description == "Success(\(x))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMaterializeFailure() { let error = NSError(domain: "com.thoughtbot.Argo", code: 0, userInfo: nil) let materialized = materialize { throw error } switch materialized { case let .Failure(e): XCTAssert(e.description == "Custom(\(error.description))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedDematerializeSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) do { try user.dematerialize() XCTAssert(true) } catch { XCTFail("Unexpected Error Occurred") } } func testDecodedDematerializeTypeMismatch() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) do { try user.dematerialize() XCTFail("Unexpected Success") } catch DecodeError.TypeMismatch { XCTAssert(true) } catch DecodeError.MissingKey { XCTFail("Unexpected Error Occurred") } catch { XCTFail("Unexpected Error Occurred") } } func testDecodedDematerializeMissingKey() { let user: Decoded<User> = decode(JSONFromFile("user_without_key")!) do { try user.dematerialize() XCTFail("Unexpected Success") } catch DecodeError.MissingKey { XCTAssert(true) } catch DecodeError.TypeMismatch { XCTFail("Unexpected Error Occurred") } catch { XCTFail("Unexpected Error Occurred") } } func testDecodedOrWithSuccess() { let successUser: Decoded<User> = decode(JSONFromFile("user_with_email")!) let failedUser: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) let result = successUser.or(failedUser) switch result { case .Success: XCTAssert(result.description == successUser.description) default: XCTFail("Unexpected Case Occurred") } } func testDecodedOrWithError() { let successUser: Decoded<User> = decode(JSONFromFile("user_with_email")!) let failedUser: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) let result = failedUser.or(successUser) switch result { case .Success: XCTAssert(result.description == successUser.description) default: XCTFail("Unexpected Case Occurred") } } } private struct Dummy: Decodable { static func decode(json: JSON) -> Decoded<Dummy> { return .Failure(.Custom("My Custom Error")) } }
mit
bc9fcfd822369b759b3189c428884280
28.033557
147
0.66736
4.212269
false
true
false
false
linusnyberg/RepoList
Pods/OAuthSwiftAlamofire/Sources/OAuthSwiftRequestAdapter.swift
2
3318
// // OAuthSwiftRequestAdapter.swift // OAuthSwift-Alamofire // // Created by phimage on 05/10/16. // Copyright © 2016 phimage. All rights reserved. // import Foundation import Alamofire import OAuthSwift // Add authentification headers from OAuthSwift to Alamofire request open class OAuthSwiftRequestAdapter: RequestAdapter { fileprivate let oauthSwift: OAuthSwift public var paramsLocation: OAuthSwiftHTTPRequest.ParamsLocation = .authorizationHeader public var dataEncoding: String.Encoding = .utf8 public init(_ oauthSwift: OAuthSwift) { self.oauthSwift = oauthSwift } public func adapt(_ urlRequest: URLRequest) throws -> URLRequest { var config = OAuthSwiftHTTPRequest.Config( urlRequest: urlRequest, paramsLocation: paramsLocation, dataEncoding: dataEncoding ) config.updateRequest(credential: oauthSwift.client.credential) return try OAuthSwiftHTTPRequest.makeRequest(config: config) } } open class OAuthSwift2RequestAdapter: OAuthSwiftRequestAdapter, RequestRetrier { public init(_ oauthSwift: OAuth2Swift) { super.init(oauthSwift) } fileprivate var oauth2Swift: OAuth2Swift { return oauthSwift as! OAuth2Swift } private let lock = NSLock() private var isRefreshing = false private var requestsToRetry: [RequestRetryCompletion] = [] public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { lock.lock() ; defer { lock.unlock() } if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 { requestsToRetry.append(completion) if !isRefreshing { refreshTokens { [weak self] succeeded in guard let strongSelf = self else { return } strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() } strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) } strongSelf.requestsToRetry.removeAll() } } } else { completion(false, 0.0) } } private typealias RefreshCompletion = (_ succeeded: Bool) -> Void private func refreshTokens(completion: @escaping RefreshCompletion) { guard !isRefreshing else { return } isRefreshing = true oauth2Swift.renewAccessToken( withRefreshToken: "", success: { [weak self] (credential, response, parameters) in guard let strongSelf = self else { return } completion(true) strongSelf.isRefreshing = false }, failure: { [weak self] (error) in guard let strongSelf = self else { return } completion(false) strongSelf.isRefreshing = false } ) } } extension OAuth1Swift { open var requestAdapter: OAuthSwiftRequestAdapter { return OAuthSwiftRequestAdapter(self) } } extension OAuth2Swift { open var requestAdapter: OAuthSwift2RequestAdapter { return OAuthSwift2RequestAdapter(self) } }
mit
96a030ff27c2132c45ddb9ae6fe96d3c
29.431193
140
0.625867
5.341385
false
false
false
false
liutongchao/LCRefresh
Source/LCRefreshConst.swift
1
1012
// // LCRefreshConst.swift // LCRefresh // // Created by 刘通超 on 16/8/3. // Copyright © 2016年 West. All rights reserved. // import UIKit struct LCRefresh { struct Const { struct Common { static let screenWidth: CGFloat = UIScreen.main.bounds.width static let screenHeight: CGFloat = UIScreen.main.bounds.height } struct Header { static let X: CGFloat = 0 static let Y: CGFloat = -50 static let width: CGFloat = 300 static let height: CGFloat = 50 } struct Footer { static let X: CGFloat = 0 static let Y: CGFloat = 0 static let width: CGFloat = 300 static let height: CGFloat = 50 } } struct Object { static let current = "LCRefreshCurrentObject" static let last = "LCRefreshLastObject" static let header = "LCRefreshHeader" static let footer = "LCRefreshFooter" } }
mit
cc0c282d414dca911281adc17bad83fc
24.717949
74
0.565304
4.497758
false
false
false
false
steelwheels/Canary
Source/CNJSONMatcher.swift
1
2008
/* * @file CNJSONMatcher.swift * @brief Define CNJSONMatcher class * @par Copyright * Copyright (C) 2018 Steel Wheels Project */ import Foundation public class CNJSONMatcher: CNJSONVisitor { private var mNameExpression: NSRegularExpression? private var mValueExpression: NSRegularExpression? private var mResult: Bool public init(nameExpression nexp: NSRegularExpression?, valueExpression vexp: NSRegularExpression?){ mNameExpression = nexp mValueExpression = vexp mResult = false } public func match(name nm: NSString, anyObject obj: Any?) -> Bool { super.accept(name: nm, anyObject: obj) return mResult } open override func visit(name nm: NSString, array arr: NSArray){ if mValueExpression == nil { tryMatch(name: nm, string: nil) } else { /* Never match */ mResult = false } } open override func visit(name nm: NSString, dictionary dict: NSDictionary){ if mValueExpression == nil { tryMatch(name: nm, string: nil) } else { /* Never match */ mResult = false } } open override func visit(name nm: NSString, number num: NSNumber){ tryMatch(name: nm, string: NSString(string: num.description)) } open override func visit(name nm: NSString, string str: NSString){ tryMatch(name: nm, string: str) } open override func visit(name nm: NSString, null nul: NSNull){ tryMatch(name: nm, string: nil) } private func tryMatch(name nm: NSString, string str: NSString?){ if let nexp = mNameExpression { if !doesMatch(regularExpression: nexp, string: nm) { mResult = false return } } if let vexp = mValueExpression, let strval = str { if !doesMatch(regularExpression: vexp, string: strval) { mResult = false return } } mResult = true } private func doesMatch(regularExpression regexp: NSRegularExpression, string str: NSString) -> Bool { let strrange = NSMakeRange(0, str.length) let matches = regexp.matches(in: str as String, options: [], range: strrange) return matches.count > 0 } }
gpl-2.0
86acf920bc912bc4566ebbe55bf75319
24.417722
102
0.703685
3.386172
false
false
false
false
kwkhaw/SwiftAnyPic
SwiftAnyPic/PAPFindFriendsCell.swift
1
7091
import Foundation import ParseUI class PAPFindFriendsCell: PFTableViewCell { var delegate: PAPFindFriendsCellDelegate? var photoLabel: UILabel! var followButton: UIButton! /*! The cell's views. These shouldn't be modified but need to be exposed for the subclass */ var nameButton: UIButton! var avatarImageButton: UIButton! var avatarImageView: PAPProfileImageView! // MARK:- NSObject override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.blackColor() self.selectionStyle = UITableViewCellSelectionStyle.None self.avatarImageView = PAPProfileImageView() self.avatarImageView.frame = CGRectMake(10.0, 14.0, 40.0, 40.0) self.avatarImageView.layer.cornerRadius = 20.0 self.avatarImageView.layer.masksToBounds = true self.contentView.addSubview(self.avatarImageView) self.avatarImageButton = UIButton(type: UIButtonType.Custom) self.avatarImageButton.backgroundColor = UIColor.clearColor() self.avatarImageButton.frame = CGRectMake(10.0, 14.0, 40.0, 40.0) self.avatarImageButton.addTarget(self, action: #selector(PAPFindFriendsCell.didTapUserButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.avatarImageButton) self.nameButton = UIButton(type: UIButtonType.Custom) self.nameButton.backgroundColor = UIColor.clearColor() self.nameButton.titleLabel!.font = UIFont.boldSystemFontOfSize(16.0) self.nameButton.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail self.nameButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) self.nameButton.setTitleColor(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forState: UIControlState.Highlighted) self.nameButton.addTarget(self, action: #selector(PAPFindFriendsCell.didTapUserButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.nameButton) self.photoLabel = UILabel() self.photoLabel.font = UIFont.systemFontOfSize(11.0) self.photoLabel.textColor = UIColor.grayColor() self.photoLabel.backgroundColor = UIColor.clearColor() self.contentView.addSubview(self.photoLabel) self.followButton = UIButton(type: UIButtonType.Custom) self.followButton.titleLabel!.font = UIFont.boldSystemFontOfSize(15.0) self.followButton.titleEdgeInsets = UIEdgeInsetsMake(0.0, 10.0, 0.0, 0.0) self.followButton.setBackgroundImage(UIImage(named: "ButtonFollow.png"), forState: UIControlState.Normal) self.followButton.setBackgroundImage(UIImage(named: "ButtonFollowing.png"), forState: UIControlState.Selected) self.followButton.setImage(UIImage(named: "IconTick.png"), forState: UIControlState.Selected) self.followButton.setTitle(NSLocalizedString("Follow ", comment: "Follow string, with spaces added for centering"), forState: UIControlState.Normal) self.followButton.setTitle("Following", forState: UIControlState.Selected) self.followButton.setTitleColor(UIColor(red: 254.0/255.0, green: 149.0/255.0, blue: 50.0/255.0, alpha: 1.0), forState: UIControlState.Normal) self.followButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) self.followButton.addTarget(self, action: #selector(PAPFindFriendsCell.didTapFollowButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.followButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- PAPFindFriendsCell /*! The user represented in the cell */ var user: PFUser? { didSet { // Configure the cell if PAPUtility.userHasProfilePictures(self.user!) { self.avatarImageView.setFile(self.user!.objectForKey(kPAPUserProfilePicSmallKey) as? PFFile) } else { self.avatarImageView.setImage(PAPUtility.defaultProfilePicture()!) } // Set name let nameString: String = self.user!.objectForKey(kPAPUserDisplayNameKey) as! String let nameSize: CGSize = nameString.boundingRectWithSize(CGSizeMake(144.0, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(16.0)], context: nil).size nameButton.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState: UIControlState.Normal) nameButton.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState: UIControlState.Highlighted) nameButton.frame = CGRectMake(60.0, 17.0, nameSize.width, nameSize.height) // Set photo number label let photoLabelSize: CGSize = "photos".boundingRectWithSize(CGSizeMake(144.0, CGFloat.max), options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)], context: nil).size photoLabel.frame = CGRectMake(60.0, 17.0 + nameSize.height, 140.0, photoLabelSize.height) // Set follow button followButton.frame = CGRectMake(208.0, 20.0, 103.0, 32.0) } } // MARK:- () class func heightForCell() -> CGFloat { return 67.0 } /* Inform delegate that a user image or name was tapped */ func didTapUserButtonAction(sender: AnyObject) { if self.delegate?.respondsToSelector(#selector(PAPFindFriendsCellDelegate.cell(_:didTapUserButton:))) != nil { self.delegate!.cell(self, didTapUserButton: self.user!) } } /* Inform delegate that the follow button was tapped */ func didTapFollowButtonAction(sender: AnyObject) { if self.delegate?.respondsToSelector(#selector(PAPFindFriendsCellDelegate.cell(_:didTapFollowButton:))) != nil { self.delegate!.cell(self, didTapFollowButton: self.user!) } } } @objc protocol PAPFindFriendsCellDelegate: NSObjectProtocol { /*! Sent to the delegate when a user button is tapped @param aUser the PFUser of the user that was tapped */ func cell(cellView: PAPFindFriendsCell, didTapUserButton aUser: PFUser) func cell(cellView: PAPFindFriendsCell, didTapFollowButton aUser: PFUser) }
cc0-1.0
2a59b2f85e7768fa3f0eb7de26c0a29c
53.129771
166
0.674658
4.907266
false
false
false
false
tomtclai/swift-algorithm-club
Convex Hull/Convex Hull/AppDelegate.swift
8
2452
// // AppDelegate.swift // Convex Hull // // Created by Jaap Wijnen on 19/02/2017. // Copyright © 2017 Workmoose. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let screenBounds = UIScreen.main.bounds window = UIWindow(frame: screenBounds) let viewController = UIViewController() viewController.view = View(frame: (window?.frame)!) viewController.view.backgroundColor = .white window?.rootViewController = viewController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
7cc8556295e1c922ad72c0a14de8739f
44.388889
285
0.742554
5.59589
false
false
false
false
JGiola/swift-corelibs-foundation
Foundation/NSDecimalNumber.swift
1
18103
// 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 // /*************** Exceptions ***********/ public struct NSExceptionName : RawRepresentable, Equatable, Hashable { public private(set) var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: NSExceptionName, _ rhs: NSExceptionName) -> Bool { return lhs.rawValue == rhs.rawValue } } extension NSExceptionName { public static let decimalNumberExactnessException = NSExceptionName(rawValue: "NSDecimalNumberExactnessException") public static let decimalNumberOverflowException = NSExceptionName(rawValue: "NSDecimalNumberOverflowException") public static let decimalNumberUnderflowException = NSExceptionName(rawValue: "NSDecimalNumberUnderflowException") public static let decimalNumberDivideByZeroException = NSExceptionName(rawValue: "NSDecimalNumberDivideByZeroException") } /*************** Rounding and Exception behavior ***********/ // Rounding policies : // Original // value 1.2 1.21 1.25 1.35 1.27 // Plain 1.2 1.2 1.3 1.4 1.3 // Down 1.2 1.2 1.2 1.3 1.2 // Up 1.2 1.3 1.3 1.4 1.3 // Bankers 1.2 1.2 1.2 1.4 1.3 /*************** Type definitions ***********/ extension NSDecimalNumber { public enum RoundingMode : UInt { case plain // Round up on a tie case down // Always down == truncate case up // Always up case bankers // on a tie round so last digit is even } public enum CalculationError : UInt { case noError case lossOfPrecision // Result lost precision case underflow // Result became 0 case overflow // Result exceeds possible representation case divideByZero } } public protocol NSDecimalNumberBehaviors { func roundingMode() -> NSDecimalNumber.RoundingMode func scale() -> Int16 } // Receiver can raise, return a new value, or return nil to ignore the exception. fileprivate func handle(_ error: NSDecimalNumber.CalculationError, _ handler: NSDecimalNumberBehaviors) { // handle the error condition, such as throwing an error for over/underflow } /*************** NSDecimalNumber: the class ***********/ open class NSDecimalNumber : NSNumber { fileprivate let decimal: Decimal public convenience init(mantissa: UInt64, exponent: Int16, isNegative: Bool) { var d = Decimal(mantissa) d._exponent += Int32(exponent) d._isNegative = isNegative ? 1 : 0 self.init(decimal: d) } public init(decimal dcm: Decimal) { self.decimal = dcm super.init() } public convenience init(string numberValue: String?) { self.init(decimal: Decimal(string: numberValue ?? "") ?? Decimal.nan) } public convenience init(string numberValue: String?, locale: Any?) { self.init(decimal: Decimal(string: numberValue ?? "", locale: locale as? Locale) ?? Decimal.nan) } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let exponent:Int32 = coder.decodeInt32(forKey: "NS.exponent") let length:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.length")) let isNegative:UInt32 = UInt32(coder.decodeBool(forKey: "NS.negative") ? 1 : 0) let isCompact:UInt32 = UInt32(coder.decodeBool(forKey: "NS.compact") ? 1 : 0) // let byteOrder:UInt32 = UInt32(coder.decodeInt32(forKey: "NS.bo")) guard let mantissaData: Data = coder.decodeObject(forKey: "NS.mantissa") as? Data else { return nil // raise "Critical NSDecimalNumber archived data is missing" } guard mantissaData.count == Int(NSDecimalMaxSize * 2) else { return nil // raise "Critical NSDecimalNumber archived data is wrong size" } // Byte order? let mantissa:(UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16, UInt16) = ( UInt16(mantissaData[0]) << 8 & UInt16(mantissaData[1]), UInt16(mantissaData[2]) << 8 & UInt16(mantissaData[3]), UInt16(mantissaData[4]) << 8 & UInt16(mantissaData[5]), UInt16(mantissaData[6]) << 8 & UInt16(mantissaData[7]), UInt16(mantissaData[8]) << 8 & UInt16(mantissaData[9]), UInt16(mantissaData[10]) << 8 & UInt16(mantissaData[11]), UInt16(mantissaData[12]) << 8 & UInt16(mantissaData[13]), UInt16(mantissaData[14]) << 8 & UInt16(mantissaData[15]) ) self.decimal = Decimal(_exponent: exponent, _length: length, _isNegative: isNegative, _isCompact: isCompact, _reserved: 0, _mantissa: mantissa) super.init() } public init(value: Int) { decimal = Decimal(value) super.init() } public init(value: UInt) { decimal = Decimal(value) super.init() } public init(value: Int8) { decimal = Decimal(value) super.init() } public init(value: UInt8) { decimal = Decimal(value) super.init() } public init(value: Int16) { decimal = Decimal(value) super.init() } public init(value: UInt16) { decimal = Decimal(value) super.init() } public init(value: Int32) { decimal = Decimal(value) super.init() } public init(value: UInt32) { decimal = Decimal(value) super.init() } public init(value: Int64) { decimal = Decimal(value) super.init() } public init(value: UInt64) { decimal = Decimal(value) super.init() } public init(value: Bool) { decimal = Decimal(value ? 1 : 0) super.init() } public init(value: Float) { decimal = Decimal(Double(value)) super.init() } public init(value: Double) { decimal = Decimal(value) super.init() } public required convenience init(floatLiteral value: Double) { self.init(decimal:Decimal(value)) } public required convenience init(booleanLiteral value: Bool) { if value { self.init(integerLiteral: 1) } else { self.init(integerLiteral: 0) } } public required convenience init(integerLiteral value: Int) { self.init(decimal:Decimal(value)) } public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { NSRequiresConcreteImplementation() } open override var description: String { return self.decimal.description } open override func description(withLocale locale: Locale?) -> String { guard locale == nil else { fatalError("Locale not supported: \(locale!)") } return self.decimal.description } open class var zero: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 0) } open class var one: NSDecimalNumber { return NSDecimalNumber(integerLiteral: 1) } open class var minimum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.leastFiniteMagnitude) } open class var maximum: NSDecimalNumber { return NSDecimalNumber(decimal:Decimal.greatestFiniteMagnitude) } open class var notANumber: NSDecimalNumber { return NSDecimalNumber(decimal: Decimal.nan) } open func adding(_ other: NSDecimalNumber) -> NSDecimalNumber { return adding(other, withBehavior: nil) } open func adding(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalAdd(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func subtracting(_ other: NSDecimalNumber) -> NSDecimalNumber { return subtracting(other, withBehavior: nil) } open func subtracting(_ other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalSubtract(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(by other: NSDecimalNumber) -> NSDecimalNumber { return multiplying(by: other, withBehavior: nil) } open func multiplying(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalMultiply(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func dividing(by other: NSDecimalNumber) -> NSDecimalNumber { return dividing(by: other, withBehavior: nil) } open func dividing(by other: NSDecimalNumber, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var left = self.decimal var right = other.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalDivide(&result, &left, &right, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func raising(toPower power: Int) -> NSDecimalNumber { return raising(toPower:power, withBehavior: nil) } open func raising(toPower power: Int, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, power, roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } open func multiplying(byPowerOf10 power: Int16) -> NSDecimalNumber { return multiplying(byPowerOf10: power, withBehavior: nil) } open func multiplying(byPowerOf10 power: Int16, withBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let error = NSDecimalPower(&result, &input, Int(power), roundingMode) handle(error,behavior) return NSDecimalNumber(decimal: result) } // Round to the scale of the behavior. open func rounding(accordingToBehavior b: NSDecimalNumberBehaviors?) -> NSDecimalNumber { var result = Decimal() var input = self.decimal let behavior = b ?? NSDecimalNumber.defaultBehavior let roundingMode = behavior.roundingMode() let scale = behavior.scale() NSDecimalRound(&result, &input, Int(scale), roundingMode) return NSDecimalNumber(decimal: result) } // compare two NSDecimalNumbers open override func compare(_ decimalNumber: NSNumber) -> ComparisonResult { if let num = decimalNumber as? NSDecimalNumber { return decimal.compare(to:num.decimal) } else { return decimal.compare(to:Decimal(decimalNumber.doubleValue)) } } open class var defaultBehavior: NSDecimalNumberBehaviors { return NSDecimalNumberHandler.defaultBehavior } // One behavior per thread - The default behavior is // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException // raise on overflow, underflow and divide by zero. static let OBJC_TYPE = "d".utf8CString open override var objCType: UnsafePointer<Int8> { return NSDecimalNumber.OBJC_TYPE.withUnsafeBufferPointer{ $0.baseAddress! } } // return 'd' for double open override var int8Value: Int8 { return Int8(exactly: decimal.doubleValue) ?? 0 as Int8 } open override var uint8Value: UInt8 { return UInt8(exactly: decimal.doubleValue) ?? 0 as UInt8 } open override var int16Value: Int16 { return Int16(exactly: decimal.doubleValue) ?? 0 as Int16 } open override var uint16Value: UInt16 { return UInt16(exactly: decimal.doubleValue) ?? 0 as UInt16 } open override var int32Value: Int32 { return Int32(exactly: decimal.doubleValue) ?? 0 as Int32 } open override var uint32Value: UInt32 { return UInt32(exactly: decimal.doubleValue) ?? 0 as UInt32 } open override var int64Value: Int64 { return Int64(exactly: decimal.doubleValue) ?? 0 as Int64 } open override var uint64Value: UInt64 { return UInt64(exactly: decimal.doubleValue) ?? 0 as UInt64 } open override var floatValue: Float { return Float(decimal.doubleValue) } open override var doubleValue: Double { return decimal.doubleValue } open override var boolValue: Bool { return !decimal.isZero } open override var intValue: Int { return Int(exactly: decimal.doubleValue) ?? 0 as Int } open override var uintValue: UInt { return UInt(exactly: decimal.doubleValue) ?? 0 as UInt } open override func isEqual(_ value: Any?) -> Bool { guard let other = value as? NSDecimalNumber else { return false } return self.decimal == other.decimal } override var _swiftValueOfOptimalType: Any { return decimal } } // return an approximate double value /*********** A class for defining common behaviors *******/ open class NSDecimalNumberHandler : NSObject, NSDecimalNumberBehaviors, NSCoding { static let defaultBehavior = NSDecimalNumberHandler() let _roundingMode: NSDecimalNumber.RoundingMode let _scale:Int16 let _raiseOnExactness: Bool let _raiseOnOverflow: Bool let _raiseOnUnderflow: Bool let _raiseOnDivideByZero: Bool public override init() { _roundingMode = .plain _scale = Int16(NSDecimalNoScale) _raiseOnExactness = false _raiseOnOverflow = true _raiseOnUnderflow = true _raiseOnDivideByZero = true } public required init?(coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } _roundingMode = NSDecimalNumber.RoundingMode(rawValue: UInt(coder.decodeInteger(forKey: "NS.roundingMode")))! if coder.containsValue(forKey: "NS.scale") { _scale = Int16(coder.decodeInteger(forKey: "NS.scale")) } else { _scale = Int16(NSDecimalNoScale) } _raiseOnExactness = coder.decodeBool(forKey: "NS.raise.exactness") _raiseOnOverflow = coder.decodeBool(forKey: "NS.raise.overflow") _raiseOnUnderflow = coder.decodeBool(forKey: "NS.raise.underflow") _raiseOnDivideByZero = coder.decodeBool(forKey: "NS.raise.dividebyzero") } open func encode(with coder: NSCoder) { guard coder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if _roundingMode != .plain { coder.encode(Int(_roundingMode.rawValue), forKey: "NS.roundingmode") } if _scale != Int16(NSDecimalNoScale) { coder.encode(_scale, forKey:"NS.scale") } if _raiseOnExactness { coder.encode(_raiseOnExactness, forKey:"NS.raise.exactness") } if _raiseOnOverflow { coder.encode(_raiseOnOverflow, forKey:"NS.raise.overflow") } if _raiseOnUnderflow { coder.encode(_raiseOnUnderflow, forKey:"NS.raise.underflow") } if _raiseOnDivideByZero { coder.encode(_raiseOnDivideByZero, forKey:"NS.raise.dividebyzero") } } open class var `default`: NSDecimalNumberHandler { return defaultBehavior } // rounding mode: NSRoundPlain // scale: No defined scale (full precision) // ignore exactnessException (return nil) // raise on overflow, underflow and divide by zero. public init(roundingMode: NSDecimalNumber.RoundingMode, scale: Int16, raiseOnExactness exact: Bool, raiseOnOverflow overflow: Bool, raiseOnUnderflow underflow: Bool, raiseOnDivideByZero divideByZero: Bool) { _roundingMode = roundingMode _scale = scale _raiseOnExactness = exact _raiseOnOverflow = overflow _raiseOnUnderflow = underflow _raiseOnDivideByZero = divideByZero } open func roundingMode() -> NSDecimalNumber.RoundingMode { return _roundingMode } // The scale could return NoScale for no defined scale. open func scale() -> Int16 { return _scale } } extension NSNumber { public var decimalValue: Decimal { if let d = self as? NSDecimalNumber { return d.decimal } else { return Decimal(self.doubleValue) } } }
apache-2.0
775fd11cfbcf4d25ac7954cf7f3f2ca4
34.288499
211
0.644865
4.734048
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/PhysicsSolver.swift
1
1180
import Foundation import GLKit func PhysicsSolver(_ postures: [Posture], physicsSolving solver: PhysicsSolving) { for rigidBody in solver.rigidBodies { if rigidBody.boneIndex < 0 { continue } if rigidBody.type != 0 { continue } let posture = postures[rigidBody.boneIndex] solver.move(rigidBody.boneIndex, rot:posture.worldRot, pos:posture.worldPos) } solver.step() for rigidBody in solver.rigidBodies { if rigidBody.boneIndex < 0 { continue } if rigidBody.type == 0 { continue } var rot = GLKQuaternionMake(0, 0, 0, 0) var pos = GLKVector3Make(0, 0, 0) solver.getTransform(rigidBody.boneIndex, rot:&rot, pos:&pos) let bone = postures[rigidBody.boneIndex].bone let m = GLKMatrix4Multiply( GLKMatrix4MakeTranslation(pos.x, pos.y, pos.z), GLKMatrix4Multiply( GLKMatrix4MakeWithQuaternion(rot), GLKMatrix4MakeTranslation(-bone.pos.x, -bone.pos.y, -bone.pos.z) ) ) postures[rigidBody.boneIndex].wm = m } }
mit
169c4d8375813b4f5d4bfa15d548ed4a
27.095238
84
0.586441
3.973064
false
false
false
false
SEMT2Group1/CASPER_IOS_Client
Pods/Socket.IO-Client-Swift/Source/SocketEnginePollable.swift
2
8265
// // SocketEnginePollable.swift // Socket.IO-Client-Swift // // Created by Erik Little on 1/15/16. // // 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 /// Protocol that is used to implement socket.io polling support public protocol SocketEnginePollable: SocketEngineSpec { var invalidated: Bool { get } /// Holds strings waiting to be sent over polling. /// You shouldn't need to mess with this. var postWait: [String] { get set } var session: NSURLSession? { get } /// Because socket.io doesn't let you send two polling request at the same time /// we have to keep track if there's an outstanding poll var waitingForPoll: Bool { get set } /// Because socket.io doesn't let you send two post request at the same time /// we have to keep track if there's an outstanding post var waitingForPost: Bool { get set } func doPoll() func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) func stopPolling() } // Default polling methods extension SocketEnginePollable { private func addHeaders(req: NSMutableURLRequest) { if cookies != nil { let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!) req.allHTTPHeaderFields = headers } if extraHeaders != nil { for (headerName, value) in extraHeaders! { req.setValue(value, forHTTPHeaderField: headerName) } } } func createRequestForPostWithPostWait() -> NSURLRequest { var postStr = "" for packet in postWait { let len = packet.characters.count postStr += "\(len):\(packet)" } DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr) postWait.removeAll(keepCapacity: false) let req = NSMutableURLRequest(URL: urlPollingWithSid) addHeaders(req) req.HTTPMethod = "POST" req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type") let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! req.HTTPBody = postData req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length") return req } public func doPoll() { if websocket || waitingForPoll || !connected || closed { return } waitingForPoll = true let req = NSMutableURLRequest(URL: urlPollingWithSid) addHeaders(req) doLongPoll(req) } func doRequest(req: NSURLRequest, withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) { if !polling || closed || invalidated { DefaultSocketLogger.Logger.error("Tried to do polling request when not supposed to", type: "SocketEnginePolling") return } DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling") session?.dataTaskWithRequest(req, completionHandler: callback).resume() } func doLongPoll(req: NSURLRequest) { doRequest(req) {[weak self] data, res, err in guard let this = self else { return } if err != nil || data == nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling") if this.polling { this.didError(err?.localizedDescription ?? "Error") } return } DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling") if let str = String(data: data!, encoding: NSUTF8StringEncoding) { dispatch_async(this.parseQueue) { this.parsePollingMessage(str) } } this.waitingForPoll = false if this.fastUpgrade { this.doFastUpgrade() } else if !this.closed && this.polling { this.doPoll() } } } private func flushWaitingForPost() { if postWait.count == 0 || !connected { return } else if websocket { flushWaitingForPostToWebSocket() return } let req = createRequestForPostWithPostWait() waitingForPost = true DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling") doRequest(req) {[weak self] data, res, err in guard let this = self else { return } if err != nil { DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling") if this.polling { this.didError(err?.localizedDescription ?? "Error") } return } this.waitingForPost = false dispatch_async(this.emitQueue) { if !this.fastUpgrade { this.flushWaitingForPost() this.doPoll() } } } } func parsePollingMessage(str: String) { guard str.characters.count != 1 else { return } var reader = SocketStringReader(message: str) while reader.hasNext { if let n = Int(reader.readUntilStringOccurence(":")) { let str = reader.read(n) dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } } else { dispatch_async(handleQueue) { self.parseEngineMessage(str, fromPolling: true) } break } } } /// Send polling message. /// Only call on emitQueue public func sendPollMessage(message: String, withType type: SocketEnginePacketType, withData datas: [NSData]) { DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue) let fixedMessage: String if doubleEncodeUTF8 { fixedMessage = doubleEncodeUTF8(message) } else { fixedMessage = message } let strMsg = "\(type.rawValue)\(fixedMessage)" postWait.append(strMsg) for data in datas { if case let .Right(bin) = createBinaryDataForSend(data) { postWait.append(bin) } } if !waitingForPost { flushWaitingForPost() } } public func stopPolling() { waitingForPoll = false waitingForPost = false session?.finishTasksAndInvalidate() } }
mit
83a18fd355450fa6b2c215354943671e
33.726891
129
0.574229
5.412574
false
false
false
false
TheBrewery/Hikes
WorldHeritage/Components/TBClosureDeclarations.swift
1
1520
import Foundation import UIKit // Use this file to define typealised closures to use in the project typealias TBVoidClosure = () -> () typealias TBVoidWithBoolClosure = (Bool) -> () typealias TBVoidWithAnyObjectClosure = (AnyObject) -> () typealias TBVoidWithCountOrErrorClosure = (Int, NSError?) -> () typealias TBVoidWithFramesClosure = (beginFrame: CGRect, endFrame: CGRect) -> () var TBUnknownError: NSError { return NSError(domain: "io.thebrewery", code: 915, userInfo: nil) } enum DispatchQueueType { case Main case Background case Default case High case Low } func DispatchQueue(type: DispatchQueueType) -> dispatch_queue_t { switch type { case .Main: return dispatch_get_main_queue() case .Background: return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) case .Default: return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) case .High: return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) case .Low: return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0) } } func executeOn(type: DispatchQueueType, afterDelay delay: NSTimeInterval? = 0.0, block: TBVoidClosure) { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay! * Double(NSEC_PER_SEC))) guard type == .Main && NSThread.isMainThread() else { return dispatch_after(time, DispatchQueue(type), block) } guard delay != 0.0 else { return block() } dispatch_after(time, DispatchQueue(type), block) }
mit
ae18ffcadb25dec7316821fa4202f0fb
30.666667
104
0.713158
3.848101
false
false
false
false
festrs/Plantinfo
PlantInfo/Identification.swift
1
1517
// // Identification.swift // PlantInfo // // Created by Felipe Dias Pereira on 2016-08-28. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit import ObjectMapper class Identification: Mappable { var date:NSDate? var local:Local? var plantID:String? var imageLink:String? var comments: [Comment] = [] init(latitude:Double,longitude:Double, plantID:String?){ self.date = NSDate() self.local = Local(latitude: latitude, longitude: longitude) self.plantID = plantID let uuid = NSUUID().UUIDString let nid = plantID?.stringByReplacingOccurrencesOfString("n", withString: "") self.imageLink = "newimages/"+nid!+"/"+uuid+".jpeg" } required init?(_ map: Map) {} // Mappable func mapping(map: Map) { date <- (map["date"],DateTransform()) local <- map["local"] plantID <- map["id_plant"] imageLink <- map["image_link"] comments <- map["comments"] } } class Local : Mappable { var latitude:Double! var longitude:Double! init(latitude:Double!, longitude:Double!){ self.latitude = latitude self.longitude = longitude } required init?(_ map: Map) { } // Mappable func mapping(map: Map) { latitude <- map["latitude"] longitude <- map["longitude"] } }
mit
9ae3efcac7a5df8e18e84fb5122cbe92
23.868852
84
0.550792
4.485207
false
false
false
false
sugar2010/arcgis-runtime-samples-ios
DownloadTileCacheSample/swift/DownloadTileCache/ViewController.swift
4
10906
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit import ArcGIS class ViewController: UIViewController, AGSLayerDelegate { @IBOutlet weak var mapView:AGSMapView! @IBOutlet weak var downloadPanel:UIView! @IBOutlet weak var scaleLabel:UILabel! @IBOutlet var estimateLabel:UILabel! @IBOutlet weak var lodLabel:UILabel! @IBOutlet weak var estimateButton:UIButton! @IBOutlet weak var downloadButton:UIButton! @IBOutlet weak var levelStepper:UIStepper! @IBOutlet weak var timerLabel:UILabel! var tileCacheTask:AGSExportTileCacheTask! var tiledLayer:AGSTiledMapServiceLayer! // in iOS7 this gets called and hides the status bar so the view does not go under the top iPhone status bar override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() //You can change this to any other service on tiledbasemaps.arcgis.com if you have an ArcGIS for Organizations subscription let tileServiceURL = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer" //Add basemap layer to the map //Set delegate to be notified of success or failure while loading let tiledUrl = NSURL(string: tileServiceURL) self.tiledLayer = AGSTiledMapServiceLayer(URL: tiledUrl) self.tiledLayer.delegate = self self.mapView.addMapLayer(self.tiledLayer, withName:"World Street Map") // Init the tile cache task if self.tileCacheTask == nil { self.tileCacheTask = AGSExportTileCacheTask(URL: tiledUrl) } self.scaleLabel.numberOfLines = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - AGSLayer delegate func layer(layer: AGSLayer!, didFailToLoadWithError error: NSError!) { //Alert user of error UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: nil).show() } func layerDidLoad(layer: AGSLayer!) { if layer == self.tiledLayer { //Initialize UIStepper based on number of scale levels in the tiled layer self.levelStepper.value = 0 self.levelStepper.minimumValue = 0 self.levelStepper.maximumValue = Double(self.tiledLayer.tileInfo.lods.count-1) //Register observer for mapScale property so we can reset the stepper and other UI when map is zoomed in/out self.mapView.addObserver(self, forKeyPath: "mapScale", options: .New, context: nil) } } //MARK: - KVO override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { //Clear out any estimate or previously chosen levels by the user //They are no longer relevant as the map's scale has changed //Disable buttons to force the user to specify levels again self.estimateLabel.text = "" self.scaleLabel.text = "" self.lodLabel.text = "" self.estimateButton.enabled = false self.downloadButton.enabled = false //Re-initialize the stepper with possible values based on current map scale if self.tiledLayer.currentLOD() != nil { if let index = find(self.tiledLayer.mapServiceInfo.tileInfo.lods as! [AGSLOD], self.tiledLayer.currentLOD()) { self.levelStepper.maximumValue = Double(self.tiledLayer.tileInfo.lods.count - index) self.levelStepper.minimumValue = 0 self.levelStepper.value = 0 } } } @IBAction func changeLevels(sender:AnyObject) { //Enable buttons because the user has specified how many levels to download self.estimateButton.enabled = true self.downloadButton.enabled = true self.levelStepper.minimumValue = 1 //Display the levels self.lodLabel.text = "\(Int(self.levelStepper.value))" //Display the scale range that will be downloaded based on specified levels let currentScale = "\(Int(self.tiledLayer.currentLOD().scale))" let maxLOD = self.tiledLayer.mapServiceInfo.tileInfo.lods[Int(self.levelStepper.value)] as! AGSLOD let maxScale = "\(Int(maxLOD.scale))" self.scaleLabel.text = String(format: "1:%@\n\tto\n1:%@",currentScale , maxScale) } @IBAction func estimateAction(sender:AnyObject) { //Prepare list of levels to download let desiredLevels = self.levelsWithCount(Int(self.levelStepper.value), startingAt:self.tiledLayer.currentLOD(), fromLODs:self.tiledLayer.tileInfo.lods as! [AGSLOD]) println("LODs requested \(desiredLevels)") //Use current envelope to download let extent = self.mapView.visibleAreaEnvelope //Prepare params with levels and envelope let params = AGSExportTileCacheParams(levelsOfDetail: desiredLevels, areaOfInterest:extent) //kick-off operation to estimate size self.tileCacheTask.estimateTileCacheSizeWithParameters(params, status: { (status, userInfo) -> Void in println("\(AGSResumableTaskJobStatusAsString(status)), \(userInfo)") }) { (tileCacheSizeEstimate, error) -> Void in if error != nil { //Report error to user UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok").show() SVProgressHUD.dismiss() }else{ //Display results (# of bytes and tiles), properly formatted, ofcourse let tileCountString = "\(tileCacheSizeEstimate.tileCount)" let byteCountFormatter = NSByteCountFormatter() let byteCountString = byteCountFormatter.stringFromByteCount(tileCacheSizeEstimate.fileSize) self.estimateLabel.text = "\(byteCountString) / \(tileCountString) tiles" SVProgressHUD.showSuccessWithStatus("Estimated size:\n\(byteCountString) / \(tileCountString) tiles") } } SVProgressHUD.showWithStatus("Estimating\n size", maskType:4) } @IBAction func downloadAction(sender:AnyObject) { //Prepare list of levels to download let desiredLevels = self.levelsWithCount(Int(self.levelStepper.value), startingAt:self.tiledLayer.currentLOD(), fromLODs:self.tiledLayer.tileInfo.lods as! [AGSLOD]) println("LODs requested \(desiredLevels)") //Use current envelope to download let extent = self.mapView.visibleAreaEnvelope //Prepare params using levels and envelope let params = AGSExportTileCacheParams(levelsOfDetail: desiredLevels, areaOfInterest:extent) //Kick-off operation self.tileCacheTask.exportTileCacheWithParameters(params, downloadFolderPath: nil, useExisting: true, status: { (status, userInfo) -> Void in //Print the job status println("\(AGSResumableTaskJobStatusAsString(status)), \(userInfo)") if userInfo != nil { let allMessages = userInfo["messages"] as? [AGSGPMessage] if status == .FetchingResult { let totalBytesDownloaded = userInfo["AGSDownloadProgressTotalBytesDownloaded"] as? Double let totalBytesExpected = userInfo["AGSDownloadProgressTotalBytesExpected"] as? Double if totalBytesDownloaded != nil && totalBytesExpected != nil { let dPercentage = totalBytesDownloaded!/totalBytesExpected! println("\(totalBytesDownloaded) / \(totalBytesExpected) = \(dPercentage)") SVProgressHUD.showProgress(Float(dPercentage), status: "Downloading", maskType: 4) } } else if allMessages != nil && allMessages!.count > 0 { //Else, display latest progress message provided by the service if let message = MessageHelper.extractMostRecentMessage(allMessages!) { println(message) SVProgressHUD.showWithStatus(message, maskType:4) } } } }) { (localTiledLayer, error) -> Void in SVProgressHUD.dismiss() if error != nil { //alert the user UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "Ok").show() self.estimateLabel.text = "" } else{ //clear out the map, and add the downloaded tile cache to the map self.mapView.reset() self.mapView.addMapLayer(localTiledLayer, withName:"offline") //Tell the user we're done UIAlertView(title: "Download Complete", message: "The tile cache has been added to the map", delegate: nil, cancelButtonTitle: "Ok").show() //Remove the option to download again. // for subview in self.downloadPanel.subviews as [UIView] { // subview.removeFromSuperview() // } self.levelStepper.enabled = false BackgroundHelper.postLocalNotificationIfAppNotActive("Tile cache downloaded.") } } SVProgressHUD.showWithStatus("Preparing\n to download", maskType: 4) } func levelsWithCount(count:Int, startingAt startLOD:AGSLOD, fromLODs allLODs:[AGSLOD]) -> [UInt] { if let index = find(allLODs, startLOD) { let endIndex = index + count-1 let desiredLODs = Array(allLODs[index...endIndex]) var desiredLevels = [UInt]() for LOD in desiredLODs { desiredLevels.append(LOD.level) } return desiredLevels } return [UInt]() } }
apache-2.0
59c3fb8fb91fca65f9028ac10566c376
42.450199
172
0.619567
5.016559
false
false
false
false
maniramezan/PersianCalendar
PersianCalendarMac/PersianCalendarMac/ViewController.swift
1
1516
// // ViewController.swift // PersianCalendarMac // // Created by Mani Ramezan on 10/12/19. // Copyright © 2019 Mani Ramezan. All rights reserved. // import Cocoa import SafariServices.SFSafariApplication import SwiftUI class ViewController: NSViewController { @IBOutlet var calendarPlaceholder: NSView! private var theme = CalendarView.Theme() private let calendarView = CalendarView(currentCalendar: Calendar(identifier: .persian)) override func viewDidLoad() { super.viewDidLoad() let calendarContainerView = NSHostingView(rootView: calendarView.environmentObject(theme)) calendarPlaceholder.addSubview(calendarContainerView) calendarContainerView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ calendarContainerView.topAnchor.constraint(equalTo: calendarPlaceholder.topAnchor), calendarContainerView.bottomAnchor.constraint(equalTo: calendarPlaceholder.bottomAnchor), calendarContainerView.leftAnchor.constraint(equalTo: calendarPlaceholder.leftAnchor), calendarContainerView.rightAnchor.constraint(equalTo: calendarPlaceholder.rightAnchor), ]) } @IBAction func openSafariExtensionPreferences(_ sender: AnyObject?) { SFSafariApplication.showPreferencesForExtension(withIdentifier: "com.manman.PersianCalendarMacExtension") { error in if let _ = error { } } } }
mit
d8052147e910d3949bd8845296a6d4cb
35.071429
124
0.718812
5.569853
false
false
false
false
RyanTech/SwinjectMVVMExample
ExampleView/ImageSearchTableViewController.swift
1
4249
// // ImageSearchTableViewController.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/22/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import ExampleViewModel public final class ImageSearchTableViewController: UITableViewController { private var autoSearchStarted = false @IBOutlet var footerView: UIView! @IBOutlet weak var searchingIndicator: UIActivityIndicatorView! public var viewModel: ImageSearchTableViewModeling? { didSet { if let viewModel = viewModel { viewModel.cellModels.producer .on(next: { _ in self.tableView.reloadData() }) .start() viewModel.searching.producer .on(next: { searching in if searching { // Display the activity indicator at the center of the screen if the table is empty. self.footerView.frame.size.height = viewModel.cellModels.value.isEmpty ? self.tableView.frame.size.height + self.tableView.contentOffset.y : 44.0 self.tableView.tableFooterView = self.footerView self.searchingIndicator.startAnimating() } else { self.tableView.tableFooterView = nil self.searchingIndicator.stopAnimating() } }) .start() viewModel.errorMessage.producer .on(next: { errorMessage in if let errorMessage = errorMessage { self.displayErrorMessage(errorMessage) } }) .start() } } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if !autoSearchStarted { autoSearchStarted = true viewModel?.startSearch() } } private func displayErrorMessage(errorMessage: String) { let title = LocalizedString("ImageSearchTableViewController_ErrorAlertTitle", comment: "Error alert title.") let dismissButtonText = LocalizedString("ImageSearchTableViewController_DismissButtonTitle", comment: "Dismiss button title on an alert.") let message = errorMessage let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: dismissButtonText, style: .Default) { _ in alert.dismissViewControllerAnimated(true, completion: nil) }) self.presentViewController(alert, animated: true, completion: nil) } } // MARK: UITableViewDataSource extension ImageSearchTableViewController { public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let viewModel = viewModel { return viewModel.cellModels.value.count } return 0 // The following code invokes didSet of viewModel property. A bug? // return viewModel?.cellModels.value.count ?? 0 } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ImageSearchTableViewCell", forIndexPath: indexPath) as! ImageSearchTableViewCell cell.viewModel = viewModel.map { $0.cellModels.value[indexPath.row] } if let viewModel = viewModel where indexPath.row >= viewModel.cellModels.value.count - 1 && viewModel.loadNextPage.enabled.value { viewModel.loadNextPage.apply(()).start() } return cell } } // MARK: - UITableViewDelegate extension ImageSearchTableViewController { public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { viewModel?.selectCellAtIndex(indexPath.row) performSegueWithIdentifier("ImageDetailViewControllerSegue", sender: self) } }
mit
cfcaf6ff5bfb3692a5d548554837aaa2
41.059406
146
0.612524
5.924686
false
false
false
false
wayfair/brickkit-ios
Tests/Cells/DummyResizableBrick.swift
1
1130
// // DummyResizableBrick.swift // BrickKit // // Created by Peter Cheung on 7/28/17. // Copyright © 2017 Wayfair. All rights reserved. // import Foundation import BrickKit class DummyResizableBrick: Brick { var didChangeSizeCallBack: (() -> Void)? let newHeight: CGFloat public init(_ identifier: String = "", width: BrickDimension = .ratio(ratio: 1), height: BrickDimension = .auto(estimate: .fixed(size: 50)), backgroundColor: UIColor = UIColor.clear, backgroundView: UIView? = nil, setHeight: CGFloat) { self.newHeight = setHeight super.init(identifier, size: BrickSize(width: width, height: height), backgroundColor: backgroundColor, backgroundView: backgroundView) } } class DummyResizableBrickCell: BrickCell, Bricklike { typealias BrickType = DummyResizableBrick @IBOutlet weak var heightConstraint: NSLayoutConstraint! override func updateContent() { self.heightConstraint.constant = brick.newHeight super.updateContent() } func changeHeight(newHeight: CGFloat) { self.heightConstraint.constant = newHeight } }
apache-2.0
41bddcfa3621c30a3f1390e460e431f8
30.361111
239
0.703277
4.57085
false
false
false
false
ayanna92/ayannacolden-programmeerproject
programmeerproject/UsersViewController.swift
1
7755
// // UsersViewController.swift // programmeerproject // // Created by Ayanna Colden on 10/01/2017. // Copyright © 2017 Ayanna Colden. All rights reserved. // import UIKit import Firebase class UsersViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate { @IBOutlet weak var open: UIBarButtonItem! @IBOutlet weak var tableview: UITableView! @IBOutlet weak var searchBar: UISearchBar! //let searchController = UISearchController(searchResultsController: nil) var userMessages = [UserMessages]() var filteredUser = [UserMessages]() var isSearching = false override func viewDidLoad() { super.viewDidLoad() tableview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didSelectCell(sender:)))) self.hideKeyboard() navigationItem.title = "M.A.D. Users" retrieveUsers() open.target = self.revealViewController() searchBar.delegate = self searchDisplayController?.searchResultsDelegate = self; open.action = #selector(SWRevealViewController.revealToggle(_:)) self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } func didSelectCell(sender: UITapGestureRecognizer){ // Source: https://www.youtube.com/watch?v=js3gHOuPb28&t=1763s if let indexPath = tableview.indexPathForRow(at: sender.location(in: self.tableview)) { if let _ = tableview.cellForRow(at: indexPath) as? UserCell { let uid = FIRAuth.auth()!.currentUser!.uid let ref = FIRDatabase.database().reference() let key = ref.child("users").childByAutoId().key let array = isSearching ? self.filteredUser : self.userMessages var isFollower = false ref.child("users").child(uid).child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in if let following = snapshot.value as? [String : AnyObject] { for (ke, value) in following { if value as? String == array[indexPath.row].uid { isFollower = true ref.child("users").child(uid).child("following/\(ke)").removeValue() ref.child("users").child(array[indexPath.row].uid!).child("followers/\(ke)").removeValue() self.tableview.cellForRow(at: indexPath)?.accessoryType = .none } } } if !isFollower { let following = ["following/\(key)" : array[indexPath.row].uid] let followers = ["followers/\(key)" : uid] ref.child("users").child(uid).updateChildValues(following) ref.child("users").child(array[indexPath.row].uid!).updateChildValues(followers) self.tableview.cellForRow(at: indexPath)?.accessoryType = .checkmark } }) ref.removeAllObservers() tableview.deselectRow(at: indexPath, animated: true) } } } func retrieveUsers() { let ref = FIRDatabase.database().reference() ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in AppDelegate.instance().showActivityIndicator() let users = snapshot.value as! [String : AnyObject] self.userMessages.removeAll() for (_, value) in users { if let uid = value["uid"] as? String { if uid != FIRAuth.auth()!.currentUser!.uid { let userToShow = UserMessages() if let fullName = value["fullname"] as? String, let imagePath = value["urlToImage"] as? String { userToShow.fullname = fullName userToShow.urlToImage = imagePath userToShow.uid = uid self.userMessages.append(userToShow) } } } } self.tableview.reloadData() AppDelegate.instance().dismissActivityIndicator() }) ref.removeAllObservers() } func checkFollowing(indexPath: IndexPath, isSearching: Bool) { let uid = FIRAuth.auth()!.currentUser!.uid let ref = FIRDatabase.database().reference() ref.child("users").child(uid).child("following").queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in if let following = snapshot.value as? [String: AnyObject] { for (_, value) in following { var array = isSearching ? self.filteredUser: self.userMessages if array.count == 0 { return } if array.count > indexPath.row && value as? String == array[indexPath.row].uid { self.tableview.cellForRow(at: indexPath)?.accessoryType = .checkmark } } } }) ref.removeAllObservers() } // MARK: Searchbar functions. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { filteredUser = searchText.isEmpty ? userMessages : userMessages.filter({(dataString: UserMessages) -> Bool in return dataString.fullname?.range(of: searchText, options: .caseInsensitive) != nil }) tableview.reloadData() } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { isSearching = true self.searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { isSearching = false searchBar.showsCancelButton = false searchBar.text = "" searchBar.resignFirstResponder() tableview.reloadData() } // MARK: Tableview. func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableview.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UserCell if isSearching == true { cell.userID = self.filteredUser[indexPath.row].uid cell.nameLabel.text = self.filteredUser[indexPath.row].fullname cell.userImage.downloadImage(from: self.filteredUser[indexPath.row].urlToImage!) } else { cell.userID = self.userMessages[indexPath.row].uid cell.nameLabel.text = self.userMessages[indexPath.row].fullname cell.userImage.downloadImage(from: self.userMessages[indexPath.row].urlToImage!) } checkFollowing(indexPath: indexPath, isSearching: isSearching) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearching ? filteredUser.count: userMessages.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
apache-2.0
84e78be60b93827118f827d846852f13
37.964824
135
0.558937
5.659854
false
false
false
false
pandazheng/Spiral
Spiral/HelpMethods.swift
1
1351
// // HelpFile.swift // Spiral // // Created by 杨萧玉 on 15/6/9. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import Foundation func * (left:CGFloat, right:Double) -> Double { return Double(left) * right } func * (left:Int, right:CGFloat) -> CGFloat { return CGFloat(left) * right } func * (left:CGSize, right:CGFloat) -> CGSize { return CGSize(width: left.width * right, height: left.height * right) } private func imageWithView(view:UIView)->UIImage{ UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0); view.drawViewHierarchyInRect(view.bounds,afterScreenUpdates:true) let img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return img; } func imageFromNode(node:SKNode)->UIImage{ if let tex = ((UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController?.view as! SKView).textureFromNode(node) { let view = SKView(frame: CGRectMake(0, 0, tex.size().width, tex.size().height)) let scene = SKScene(size: tex.size()) let sprite = SKSpriteNode(texture: tex) sprite.position = CGPointMake( CGRectGetMidX(view.frame), CGRectGetMidY(view.frame) ); scene.addChild(sprite) view.presentScene(scene) return imageWithView(view) } return UIImage() }
mit
0f828c97e252604a65f7217945911ed5
30.116279
147
0.693343
3.955621
false
false
false
false
moonrailgun/OpenCode
OpenCode/UIViewAdditions.swift
1
829
// // UIViewAdditions.swift // OpenCode // // Created by 陈亮 on 16/6/3. // Copyright © 2016年 moonrailgun. All rights reserved. // import UIKit /* extension UIView{ func getCurrentViewController() -> UIViewController?{ for(var next = self.superview; (next != nil); next = next?.superview){ var responder:UIResponder? = next?.nextResponder() while(responder != nil){ if(responder!.isKindOfClass(UIViewController.self)){ return nextResponder as? UIViewController } responder = responder!.nextResponder()! } } return nil } }*/ extension UIView{ func removeAllSubview(){ for view:UIView in self.subviews{ view.removeFromSuperview() } } }
gpl-2.0
9cb2851c8666e47d1b32619a29c04a22
23.939394
78
0.568127
4.835294
false
false
false
false
puyanLiu/LPYFramework
第三方框架改造/Toast-Swift-master/Demo/ViewController.swift
1
15480
// // ViewController.swift // Toast-Swift // // Copyright (c) 2015 Charles Scalesse. // // 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 ViewController: UITableViewController { fileprivate let switchCellId = "ToastSwitchCellId" fileprivate let demoCellId = "ToastDemoCellId" fileprivate var showingActivity = false // MARK: - Constructors override init(style: UITableViewStyle) { super.init(style: style) self.title = "Toast-Swift" } required init?(coder aDecoder: NSCoder) { fatalError("not used") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: demoCellId) } // MARK: - Events func handleTapToDismissToggled() { ToastManager.shared.tapToDismissEnabled = !ToastManager.shared.tapToDismissEnabled } func handleQueueToggled() { ToastManager.shared.queueEnabled = !ToastManager.shared.queueEnabled } } // MARK: - UITableViewDelegate & DataSource Methods extension ViewController { override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } else { return 9 } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40.0 } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "SETTINGS" } else { return "DEMOS" } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath as NSIndexPath).section == 0 { var cell = tableView.dequeueReusableCell(withIdentifier: switchCellId) if (indexPath as NSIndexPath).row == 0 { if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: switchCellId) let tapToDismissSwitch = UISwitch() tapToDismissSwitch.onTintColor = UIColor.blue tapToDismissSwitch.isOn = ToastManager.shared.tapToDismissEnabled tapToDismissSwitch.addTarget(self, action: #selector(ViewController.handleTapToDismissToggled), for: .valueChanged) cell?.accessoryView = tapToDismissSwitch cell?.selectionStyle = .none cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0) } cell?.textLabel?.text = "Tap to dismiss" } else { if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: switchCellId) let queueSwitch = UISwitch() queueSwitch.onTintColor = UIColor.blue queueSwitch.isOn = ToastManager.shared.queueEnabled queueSwitch.addTarget(self, action: #selector(ViewController.handleQueueToggled), for: .valueChanged) cell?.accessoryView = queueSwitch cell?.selectionStyle = .none cell?.textLabel?.font = UIFont.systemFont(ofSize: 16.0) } cell?.textLabel?.text = "Queue toast" } return cell! } else { let cell = tableView.dequeueReusableCell(withIdentifier: demoCellId, for: indexPath) cell.textLabel?.numberOfLines = 2 cell.textLabel?.font = UIFont.systemFont(ofSize: 16.0) cell.accessoryType = .disclosureIndicator if (indexPath as NSIndexPath).row == 0 { cell.textLabel?.text = "Make toast" } else if (indexPath as NSIndexPath).row == 1 { cell.textLabel?.text = "Make toast on top for 3 seconds" } else if (indexPath as NSIndexPath).row == 2 { cell.textLabel?.text = "Make toast with a title" } else if (indexPath as NSIndexPath).row == 3 { cell.textLabel?.text = "Make toast with an image" } else if (indexPath as NSIndexPath).row == 4 { cell.textLabel?.text = "Make toast with a title, image, and completion block" } else if (indexPath as NSIndexPath).row == 5 { cell.textLabel?.text = "Make toast with a custom style" } else if (indexPath as NSIndexPath).row == 6 { cell.textLabel?.text = "Show a custom view as toast" } else if (indexPath as NSIndexPath).row == 7 { cell.textLabel?.text = "Show an image as toast at point\n(110, 110)" } else if (indexPath as NSIndexPath).row == 8 { cell.textLabel?.text = (self.showingActivity) ? "Hide toast activity" : "Show toast activity" } return cell } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath as NSIndexPath).section == 0 { return } tableView.deselectRow(at: indexPath, animated: true) if (indexPath as NSIndexPath).row == 0 { // Make Toast // self.navigationController?.view.makeToast("This is a piece of toast") // 圆环直径 let circleSize: CGFloat = 40 // 缺口角度 let gapAngle: CGFloat = 20 let wrapperView = UIView() let screenSize = UIScreen.main.bounds.size let style = ToastManager.shared.style wrapperView.backgroundColor = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.8) wrapperView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] wrapperView.layer.cornerRadius = 10 // 中间部分 let customRect = CGRect(x: 0, y: style.horizontalPadding * 2, width: circleSize, height: circleSize) let customView = UIView(frame: customRect) wrapperView.addSubview(customView) let squareView = UIView(frame: CGRect(x: (circleSize - circleSize * 0.3) * 0.5, y: (circleSize - circleSize * 0.3) * 0.5, width: circleSize * 0.3, height: circleSize * 0.3)) squareView.layer.borderColor = UIColor.white.cgColor squareView.layer.borderWidth = 1 squareView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4)) customView.addSubview(squareView) // 转环 let animationLayer = CAShapeLayer() animationLayer.bounds = customView.bounds animationLayer.position = CGPoint(x: customView.bounds.midX, y: customView.bounds.midY) animationLayer.strokeColor = UIColor.white.cgColor animationLayer.fillColor = UIColor.clear.cgColor animationLayer.lineJoin = "round" animationLayer.lineCap = "round" animationLayer.lineWidth = 1 animationLayer.strokeStart = 0 animationLayer.strokeEnd = 1 let path = CGMutablePath() path.addArc(center: CGPoint(x: circleSize * 0.5, y: circleSize * 0.5), radius: circleSize * 0.5 - 2, startAngle: 0, endAngle: CGFloat(Double.pi * 2) - CGFloat(Double.pi) * gapAngle / 180, clockwise: false) animationLayer.path = path customView.layer.addSublayer(animationLayer) // 动画 let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = Double.pi * 2 animation.duration = 1 animation.isCumulative = true animation.repeatCount = Float.infinity animationLayer.add(animation, forKey: "") // 提示语 let messageLabel = UILabel() messageLabel.text = "正在拼命加载中" messageLabel.numberOfLines = style.messageNumberOfLines messageLabel.font = UIFont.systemFont(ofSize: 15) messageLabel.textAlignment = .center messageLabel.lineBreakMode = .byTruncatingTail; messageLabel.textColor = style.messageColor wrapperView.addSubview(messageLabel) // 计算messageLabel的frame let maxMessageSize = CGSize(width: screenSize.width * style.maxWidthPercentage, height: screenSize.height * style.maxHeightPercentage) let messageSize = messageLabel.sizeThatFits(maxMessageSize) let actualWidth = min(messageSize.width, maxMessageSize.width) let actualHeight = min(messageSize.height, maxMessageSize.height) let messageRect = CGRect(x: style.horizontalPadding * 2, y: style.verticalPadding + customRect.maxY, width: actualWidth, height: actualHeight) messageLabel.frame = messageRect // 计算wrapperView的frame let longerWidth = messageRect.size.width let longerX = messageRect.origin.x let wrapperWidth = max(style.horizontalPadding * 2.0, (longerX + longerWidth + style.horizontalPadding * 2)) let wrapperHeight = max((messageRect.origin.y + messageRect.size.height + style.verticalPadding * 2), style.verticalPadding * 2.0) wrapperView.frame = CGRect(x: 0.0, y: 0.0, width: wrapperWidth, height: wrapperHeight) // 计算customView的position var customCenter = customView.center customCenter.x = wrapperView.center.x customView.center = customCenter self.navigationController?.view.showToast(wrapperView) // // // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(5000)) { // self.navigationController?.view.hideToast() // } } else if (indexPath as NSIndexPath).row == 1 { // Make toast with a duration and position // self.navigationController?.view.makeToast("This is a piece of toast on top for 3 seconds", duration: 3.0, position: .top) self.navigationController?.view.makeToastActivity(.center) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .milliseconds(5000)) { self.navigationController?.view.hideToastActivity() } } else if (indexPath as NSIndexPath).row == 2 { // self.navigationController?.view.makeToast("哈哈哈") self.navigationController?.view.makeToast("您的借款申请正在安排放款,预计在24小时内完成!") // Make toast with a title // self.navigationController?.view.makeToast("This is a piece of toast with a title", duration: 2.0, position: .top, title: "Toast Title", image: nil, style: nil, completion: nil) } else if (indexPath as NSIndexPath).row == 3 { // Make toast with an image self.navigationController?.view.makeToast("This is a piece of toast with an image", duration: 2.0, position: .center, title: nil, image: UIImage(named: "toast.png"), style: nil, completion: nil) } else if (indexPath as NSIndexPath).row == 4 { // Make toast with an image, title, and completion closure self.navigationController?.view.makeToast("This is a piece of toast with a title, image, and completion closure", duration: 2.0, position: .bottom, title: "Toast Title", image: UIImage(named: "toast.png"), style:nil) { (didTap: Bool) -> Void in if didTap { print("completion from tap") } else { print("completion without tap") } } } else if (indexPath as NSIndexPath).row == 5 { var style = ToastStyle() style.messageFont = UIFont(name: "Zapfino", size: 14.0)! style.messageColor = UIColor.red style.messageAlignment = .center style.backgroundColor = UIColor.yellow self.navigationController?.view.makeToast("This is a piece of toast with a custom style", duration: 3.0, position: .bottom, style: style) } else if (indexPath as NSIndexPath).row == 6 { // Show a custom view as toast let customView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 80.0, height: 400.0)) customView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin] customView.backgroundColor = UIColor.blue self.navigationController?.view.showToast(customView, duration: 2.0, position: .center, completion:nil) } else if (indexPath as NSIndexPath).row == 7 { // Show an imageView as toast, on center at point (110,110) let toastView = UIImageView(image: UIImage(named: "toast.png")) self.navigationController?.view.showToast(toastView, duration: 2.0, position: CGPoint(x: 110.0, y: 110.0), completion: nil) } else if (indexPath as NSIndexPath).row == 8 { // Make toast activity if !self.showingActivity { self.navigationController?.view.makeToastActivity(.center) } else { self.navigationController?.view.hideToastActivity() } self.showingActivity = !self.showingActivity tableView.reloadData() } } }
apache-2.0
5dc95f0af35b512357ebf2001542a2e3
44.578635
256
0.598047
5.163025
false
false
false
false
CherishSmile/ZYBase
ZYBase/ThirdLib/LBXScan/LBXScanViewStyle.swift
3
2594
// // LBXScanViewStyle.swift // swiftScan // // Created by xialibing on 15/12/8. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit ///扫码区域动画效果 public enum LBXScanViewAnimationStyle { case LineMove //线条上下移动 case NetGrid//网格 case LineStill//线条停止在扫码区域中央 case None //无动画 } ///扫码区域4个角位置类型 public enum LBXScanViewPhotoframeAngleStyle { case Inner//内嵌,一般不显示矩形框情况下 case Outer//外嵌,包围在矩形框的4个角 case On //在矩形框的4个角上,覆盖 } public struct LBXScanViewStyle { // MARK: - -中心位置矩形框 /// 是否需要绘制扫码矩形框,默认YES public var isNeedShowRetangle:Bool = true /** * 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比 */ public var whRatio:CGFloat = 1.0 /** @brief 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移 */ public var centerUpOffset:CGFloat = 44 /** * 矩形框(视频显示透明区)域离界面左边及右边距离,默认60 */ public var xScanRetangleOffset:CGFloat = 60 /** @brief 矩形框线条颜色,默认白色 */ public var colorRetangleLine = UIColor.white //MARK -矩形框(扫码区域)周围4个角 /** @brief 扫码区域的4个角类型 */ public var photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Outer //4个角的颜色 public var colorAngle = UIColor(red: 0.0, green: 167.0/255.0, blue: 231.0/255.0, alpha: 1.0) //扫码区域4个角的宽度和高度 public var photoframeAngleW:CGFloat = 24.0 public var photoframeAngleH:CGFloat = 24.0 /** @brief 扫码区域4个角的线条宽度,默认6,建议8到4之间 */ public var photoframeLineW:CGFloat = 6 //MARK: ----动画效果 /** @brief 扫码动画效果:线条或网格 */ public var anmiationStyle = LBXScanViewAnimationStyle.LineMove /** * 动画效果的图像,如线条或网格的图像 */ public var animationImage:UIImage? // MARK: -非识别区域颜色,默认 RGBA (0,0,0,0.5),范围(0--1) public var color_NotRecoginitonArea:UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5); public init() { } }
mit
c0b9b1622a600915ca39e1a91523708e
16.104348
103
0.614642
3.317032
false
false
false
false
TwilioDevEd/api-snippets
video/rooms/video-constraints/video-constraints.swift
2
841
// Create camera object let camera = TVICameraCapturer() // Setup the video constraints let videoConstraints = TVIVideoConstraints { (constraints) in constraints.maxSize = TVIVideoConstraintsSize960x540; constraints.minSize = TVIVideoConstraintsSize960x540; constraints.maxFrameRate = TVIVideoConstraintsFrameRateNone; constraints.minFrameRate = TVIVideoConstraintsFrameRateNone; } // Add local video track with camera and video constraints var localVideoTrack = TVILocalVideoTrack.init(capturer: camera!, enabled: true, constraints: videoConstraints) // If the constraints are not satisfied, a nil track will be returned. if (localVideoTrack == nil) { print ("Error: Failed to create a video track using the local camera.") }
mit
ee7201cf4e4fae1863672d9902a91bb4
43.263158
76
0.703924
5.223602
false
false
false
false
RedMadRobot/input-mask-ios
Source/InputMask/InputMaskTests/Classes/Mask/EscapedCase.swift
1
5434
// // Project «InputMask» // Created by Jeorge Taflanidi // import XCTest @testable import InputMask class EscapedCase: MaskTestCase { override func format() -> String { return "\\{\\[[00]\\]{99}{\\}\\]}" // show: {[12]99}] // value: 1299}] } func testInit_correctFormat_maskInitialized() { XCTAssertNotNil(try self.mask()) } func testInit_correctFormat_measureTime() { self.measure { var masks: [Mask] = [] for _ in 1...1000 { masks.append( try! self.mask() ) } } } func testGetOrCreate_correctFormat_measureTime() { self.measure { var masks: [Mask] = [] for _ in 1...1000 { masks.append( try! Mask.getOrCreate(withFormat: self.format()) ) } } } func testGetPlaceholder_allSet_returnsCorrectPlaceholder() { let placeholder: String = try! self.mask().placeholder XCTAssertEqual(placeholder, "{[00]99}]") } func testAcceptableTextLength_allSet_returnsCorrectCount() { let acceptableTextLength: Int = try! self.mask().acceptableTextLength XCTAssertEqual(acceptableTextLength, 9) } func testTotalTextLength_allSet_returnsCorrectCount() { let totalTextLength: Int = try! self.mask().totalTextLength XCTAssertEqual(totalTextLength, 9) } func testAcceptableValueLength_allSet_returnsCorrectCount() { let acceptableValueLength: Int = try! self.mask().acceptableValueLength XCTAssertEqual(acceptableValueLength, 6) } func testTotalValueLength_allSet_returnsCorrectCount() { let totalValueLength: Int = try! self.mask().totalValueLength XCTAssertEqual(totalValueLength, 6) } func testApply_1_returns_bracket1() { let inputString: String = "1" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "{[1" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = "1" let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(false, result.complete) } func testApply_11_returns_bracket11() { let inputString: String = "11" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "{[11" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = "11" let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(false, result.complete) } func testApply_112_returns_bracket11bracket() { let inputString: String = "112" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "{[11]99}]" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = "1199}]" let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } func testApply_1122_returns_bracket11bracket() { let inputString: String = "1122" let inputCaret: String.Index = inputString.endIndex let expectedString: String = "{[11]99}]" let expectedCaret: String.Index = expectedString.endIndex let expectedValue: String = "1199}]" let result: Mask.Result = try! self.mask().apply( toText: CaretString( string: inputString, caretPosition: inputCaret, caretGravity: .forward(autocomplete: false) ) ) XCTAssertEqual(expectedString, result.formattedText.string) XCTAssertEqual(expectedCaret, result.formattedText.caretPosition) XCTAssertEqual(expectedValue, result.extractedValue) XCTAssertEqual(true, result.complete) } }
mit
77b650093672ede4a4ac8f75908c7433
32.530864
79
0.58634
5.25847
false
true
false
false
TwilioDevEd/api-snippets
guides/functions/calling-jokes-function-ios/calling-jokes-function-ios.swift
2
528
let functionURL = "https://yourdomain.twil.io/jokes" if let url = URL(string: functionURL) { let task = URLSession.shared.dataTask(with: url) { data, response, error in if error != nil { print(error!) } else { do { let responseObject = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]] print(responseObject) } catch let error as NSError { print(error) } } } task.resume() }
mit
465da1ee5a2c56e71b480e36e59be9b2
30.117647
101
0.526515
4.327869
false
false
false
false
jpchmura/JPCDataSourceController
JPCDataSourceControllerExamples/JPCDataSourceControllerExamples/MenuViewController.swift
1
1575
// // MenuViewController.swift // JPCDataSourceControllerExamples // // Created by Jon Chmura on 4/9/15. // Copyright (c) 2015 Jon Chmura. All rights reserved. // import UIKit class MenuViewController: JPCTableViewController { struct Constants { struct Segue { static let Twitter = "show_twitter" static let CoreData = "show_core_data" static let Embedded = "show_embedded" } } lazy var tableModel: BasicSectionModel = { let theModel = BasicSectionModel() theModel.items = ["Twitter Feed", "Core Data", "Embedded Collection Views"] theModel.footer = "Select a example to see DataSourceController in action. This table is also built using DataSourceController :)" return theModel }() override func viewDidLoad() { super.viewDidLoad() let factory = BasicTableViewCellFactory() self.dataSourceController.model = self.tableModel self.dataSourceController.cellFactory = CellFactory.Table(factory) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 0: self.performSegueWithIdentifier(Constants.Segue.Twitter, sender: nil) case 1: self.performSegueWithIdentifier(Constants.Segue.CoreData, sender: nil) case 2: self.performSegueWithIdentifier(Constants.Segue.Embedded, sender: nil) default: break } } }
mit
a8e837d362318dac2df00dea27624995
28.716981
138
0.64
5.113636
false
false
false
false
amdaza/HackerBooks
HackerBooks/HackerBooks/AsyncImage.swift
1
2221
// // AsyncImage.swift // HackerBooks // // Created by Alicia Daza on 16/07/16. // Copyright © 2016 Alicia Daza. All rights reserved. // import UIKit let ImageDidChangeNotification = "Book image did change" let ImageKey = "imageKey" class AsyncImage { var image: UIImage let url: URL var loaded: Bool init(remoteUrl url: URL, defaultImage image: UIImage){ self.url = url self.image = image self.loaded = false } func downloadImage() { let queue = DispatchQueue(label: "downloadImages", attributes: []) queue.async { if let data = try? Data(contentsOf: self.url), let img = UIImage(data: data){ DispatchQueue.main.async { self.image = img self.loaded = true // Notify let nc = NotificationCenter.default let notif = Notification(name: Notification.Name(rawValue: ImageDidChangeNotification), object: self, userInfo: [ImageKey: self.url.path]) nc.post(notif) } } else { //throw HackerBooksError.resourcePointedByUrLNotReachable } } } func getImage() { if (!loaded) { // Get cache url if let cacheUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first{ // First because it returns an array // Get image filename let imageFileName = url.lastPathComponent //{ let destination = cacheUrl.appendingPathComponent(imageFileName) // Check if image exists before downloading it if FileManager().fileExists(atPath: destination.path) { // File exists at path if let data = try? Data(contentsOf: destination), let img = UIImage(data: data){ self.image = img } } else { // File doesn't exists. Download downloadImage() } } } } }
gpl-3.0
fa6df578553f8091e5c2995c50b001f1
26.407407
121
0.517117
5.186916
false
false
false
false
KimDarren/allkfb
Allkdic/Controls/LabelButton.swift
1
1841
// The MIT License (MIT) // // Copyright (c) 2015 Suyeol Jeon (http://xoul.kr) // // 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 AppKit public class LabelButton: Label { public var normalTextColor: NSColor! = NSColor.blackColor() public var highlightedTextColor: NSColor! = NSColor(white: 0.5, alpha: 1) override public func mouseDown(theEvent: NSEvent?) { self.textColor = self.highlightedTextColor } override public func mouseUp(theEvent: NSEvent?) { self.textColor = self.normalTextColor if let event = theEvent { let point = event.locationInWindow let rect = CGRectInset(self.frame, -10, -30) if NSPointInRect(point, rect) { self.sendAction(self.action, to: self.target) } } } }
mit
11e1b7452e18aec200d125245648da28
39.043478
81
0.710483
4.568238
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Weather List Scene/Table View Cells/Alert Cell/WeatherListAlertTableViewCellViewModel.swift
1
2456
// // WeatherInformationAlertTableViewCellViewModel.swift // NearbyWeather // // Created by Erik Maximilian Martens on 05.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import RxSwift import RxCocoa // MARK: - Dependencies extension WeatherListAlertTableViewCellViewModel { struct Dependencies { let error: Error } } // MARK: - Class Definition final class WeatherListAlertTableViewCellViewModel: NSObject, BaseCellViewModel { let associatedCellReuseIdentifier = WeatherListAlertTableViewCell.reuseIdentifier // MARK: - Events lazy var cellModelDriver: Driver<WeatherListAlertTableViewCellModel> = Self.createCellModelDriver(error: dependencies.error) // MARK: - Properties let dependencies: Dependencies // MARK: - Initialization init(dependencies: Dependencies) { self.dependencies = dependencies } // MARK: - Functions func observeEvents() { observeDataSource() observeUserTapEvents() } } // MARK: - Observation Helpers private extension WeatherListAlertTableViewCellViewModel { static func createCellModelDriver(error: Error) -> Driver<WeatherListAlertTableViewCellModel> { var errorMessage: String if let error = error as? WeatherInformationService.DomainError { switch error { case .nearbyWeatherInformationMissing: errorMessage = R.string.localizable.empty_nearby_locations_message() case .bookmarkedWeatherInformationMissing: errorMessage = R.string.localizable.empty_bookmarks_message() } } else if let error = error as? UserLocationService.DomainError { switch error { case .locationAuthorizationError: errorMessage = R.string.localizable.location_denied_error() case .locationUndeterminableError: errorMessage = R.string.localizable.location_unavailable_error() } } else if let error = error as? ApiKeyService.DomainError { switch error { case .apiKeyMissingError: errorMessage = R.string.localizable.missing_api_key_error() case .apiKeyInvalidError: errorMessage = R.string.localizable.unauthorized_api_key_error() } } else { errorMessage = R.string.localizable.unknown_error() } let cellModel = WeatherListAlertTableViewCellModel(alertInformationText: errorMessage) return Observable .just(cellModel) .asDriver(onErrorJustReturn: cellModel) } }
mit
08c571b6c93ae0c6cf0376c3604f4b9c
27.546512
126
0.724644
4.813725
false
false
false
false
hejunbinlan/Nuke
Pod/Classes/Core/ImageTask.swift
2
1035
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import Foundation public enum ImageTaskState { case Suspended case Running case Cancelled case Completed } /** Abstract class */ public class ImageTask: Hashable { public let request: ImageRequest var completion: ImageTaskCompletion? public internal(set) var state: ImageTaskState = .Suspended public internal(set) var response: ImageResponse? public let progress: NSProgress init(request: ImageRequest, completion: ImageTaskCompletion?) { self.request = request self.completion = completion self.progress = NSProgress(totalUnitCount: -1) self.progress.cancellationHandler = { [weak self] in self?.cancel() } } public var hashValue: Int { return self.request.URL.hashValue } public func resume() {} public func cancel() {} } public func ==(lhs: ImageTask, rhs: ImageTask) -> Bool { return lhs === rhs }
mit
1b04def1b93e5c65b7f7abb029dada50
23.642857
67
0.658937
4.641256
false
false
false
false
izandotnet/ULAQ
ULAQ/Constant.swift
1
874
// // Constant.swift // ULAQ // // Created by Rohaizan Roosley on 07/05/2017. // Copyright © 2017 Rohaizan Roosley. All rights reserved. // import Foundation // Collision let headUnit: UInt32 = 0x1 << 0 let appleUnit: UInt32 = 0x1 << 1 let borderUnit: UInt32 = 0x1 << 2 let bodyUnit: UInt32 = 0x1 << 3 let obstacleUnit: UInt32 = 0x1 << 4 // UserDefault keys let difficultyConstant = "difficultySetting" let firstTimerConstant = "firstTimer" let currentLevelConstant = "currentLevel" let skinConstant = "skinSetting" let unlockConstant = "unlockSetting" // Scores let currentScoreConstant = "currentScore" let topScoreConstant = "topScore" //Purchase Constant let premiumPurchaseConstant = "premiumPurchase" let PREMIUM_PROD_ID = "my.rohaizan.ulaq.premium" // Purchase Message var BUY_MESSAGE = "" // Play Mode (1= Level mode, 2=Top Score Mode) var PLAY_MODE = 1
mit
377cf29aa26ff0a442e9c9905494457f
22.594595
59
0.73425
3.129032
false
false
false
false
nibty/skate-retro-tvos
RetroSkate/Player.swift
1
4517
// // Player.swift // Game // // Created by Nicholas Pettas on 11/10/15. // Copyright © 2015 Nicholas Pettas. All rights reserved. // import SpriteKit class Player: SKSpriteNode { // Character setup var charPushFrames = [SKTexture]() var charCrashFrames = [SKTexture]() var charOllieFrames = [SKTexture]() var charFlipFrames = [SKTexture]() var isJumping = false var isOllieTrick = false var isFlipTrick = false convenience init() { self.init(imageNamed: "push0") createCharacter() } override func update() { if isJumping { if floor((self.physicsBody?.velocity.dy)!) == 0 { isJumping = false isOllieTrick = false isFlipTrick = false } } } func createCharacter() { self.zPosition = GameManager.sharedInstance.PLAYER_Z_POSITION for var x = 0; x < 12; x++ { charPushFrames.append(SKTexture(imageNamed: "push\(x)")) } for var x = 0; x < 9; x++ { charCrashFrames.append(SKTexture(imageNamed: "crash\(x)")) } for var x = 0; x < 10; x++ { charOllieFrames.append(SKTexture(imageNamed: "ollie\(x)")) } for var x = 0; x < 12; x++ { charFlipFrames.append(SKTexture(imageNamed: "flip\(x)")) } self.position = CGPointMake(GameManager.sharedInstance.CHAR_X_POSITION, GameManager.sharedInstance.CHAR_Y_POSITION) self.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.size.width - 50, self.size.height - 20)) self.physicsBody?.restitution = 0 self.physicsBody?.linearDamping = 0.1 self.physicsBody?.allowsRotation = false self.physicsBody?.mass = 0.1 self.physicsBody?.dynamic = true self.physicsBody?.categoryBitMask = GameManager.sharedInstance.COLLIDER_PLAYER self.physicsBody?.contactTestBitMask = GameManager.sharedInstance.COLLIDER_OBSTACLE playPushAnim() } func jump() { if !isJumping && !GameManager.sharedInstance.gameOver { isJumping = true self.physicsBody?.applyImpulse(CGVectorMake(0.0, 55)) AudioManager.sharedInstance.playJumpSoundEffect(self) } } func ollie() { if isJumping && !GameManager.sharedInstance.gameOver && !isOllieTrick { isOllieTrick = true; playOllieAnim() AudioManager.sharedInstance.playJumpSoundEffect(self) self.physicsBody?.applyImpulse(CGVectorMake(0.0, 25)) GameManager.sharedInstance.score++ } } func flip() { if isJumping && !GameManager.sharedInstance.gameOver && !isFlipTrick { isFlipTrick = true; playFlipAnim() AudioManager.sharedInstance.playJumpSoundEffect(self) self.physicsBody?.applyImpulse(CGVectorMake(0.0, 25)) GameManager.sharedInstance.score++ } } func playFlipAnim() { if !GameManager.sharedInstance.gameOver { self.removeAllActions() self.runAction(SKAction.animateWithTextures(charFlipFrames, timePerFrame: 0.05)) let wait = SKAction.waitForDuration(0.55) self.runAction(wait, completion: {() -> Void in self.isOllieTrick = false self.isFlipTrick = false self.playPushAnim() }) } } func playCrashAnim() { if !GameManager.sharedInstance.gameOver { self.removeAllActions() AudioManager.sharedInstance.playGameOverSoundEffect(self) self.runAction(SKAction.animateWithTextures(charCrashFrames, timePerFrame: 0.05)) } } func playPushAnim() { self.removeAllActions() self.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(charPushFrames, timePerFrame: 0.1))) } func playOllieAnim() { self.removeAllActions() self.runAction(SKAction.animateWithTextures(charOllieFrames, timePerFrame: 0.04)) let wait = SKAction.waitForDuration(0.48) self.runAction(wait, completion: {() -> Void in self.isOllieTrick = false self.isFlipTrick = false self.playPushAnim() }) } }
mit
10346f72649ee4b130c86599ff45b4b5
30.368056
123
0.585695
4.694387
false
false
false
false
cocoascientist/Passengr
Passengr/HideDetailAnimator.swift
1
4738
// // HideDetailAnimator.swift // Passengr // // Created by Andrew Shepard on 10/19/14. // Copyright (c) 2014 Andrew Shepard. All rights reserved. // import UIKit final class HideDetailAnimator: NSObject, UIViewControllerAnimatedTransitioning { private let duration = 0.75 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as? UICollectionViewController else { return } guard let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as? UICollectionViewController else { return } guard let toCollectionView = toViewController.collectionView else { return } guard let fromCollectionView = fromViewController.collectionView else { return } let containerView = transitionContext.containerView containerView.backgroundColor = AppStyle.Color.lightBlue let itemSize = ListViewLayout.listLayoutItemSize(for: UIScreen.main.bounds) // Find origin rect guard let originIndexPath = fromCollectionView.indexPathsForVisibleItems.first else { return } let originAttributes = fromCollectionView.layoutAttributesForItem(at: originIndexPath) let originRect = self.originRect(from: originAttributes) let snapshotRect = CGRect(x: originRect.origin.x, y: originRect.origin.y, width: originRect.size.width, height: itemSize.height) // Find destination rect let destinationAttributes = toCollectionView.layoutAttributesForItem(at: originIndexPath) let destinationRect = self.destinationRect(from: destinationAttributes) let firstRect = CGRect(x: originRect.origin.x, y: originRect.origin.y, width: originRect.size.width, height: destinationRect.size.height) let secondRect = destinationRect let insets = UIEdgeInsets(top: itemSize.height - 2.0, left: 0.0, bottom: 1.0, right: 0.0) guard let snapshot = fromCollectionView.resizableSnapshotView(from: snapshotRect, afterScreenUpdates: false, withCapInsets: insets) else { return } let frame = containerView.convert(snapshotRect, from: fromCollectionView) let lineView = UIView() lineView.backgroundColor = UIColor.lightGray snapshot.addSubview(lineView) snapshot.clipsToBounds = true snapshot.frame = frame lineView.frame = lineViewFrame(with: snapshot.bounds) containerView.addSubview(toViewController.view) containerView.addSubview(snapshot) fromViewController.view.alpha = 0.0 toViewController.view.alpha = 0.0 let animations: () -> Void = { UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.3, animations: { snapshot.frame = containerView.convert(firstRect, from: fromCollectionView) lineView.frame = self.lineViewFrame(with: snapshot.bounds) }) UIView.addKeyframe(withRelativeStartTime: 0.3, relativeDuration: 0.3, animations: { snapshot.frame = secondRect lineView.frame = self.lineViewFrame(with: snapshot.bounds) }) UIView.addKeyframe(withRelativeStartTime: 0.6, relativeDuration: 0.3, animations: { toViewController.view.alpha = 1.0 }) } let completion: (_ finished: Bool) -> Void = { finished in snapshot.removeFromSuperview() fromViewController.view.removeFromSuperview() transitionContext.completeTransition(finished) } UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: [], animations: animations, completion: completion) } private func originRect(from attributes: UICollectionViewLayoutAttributes?) -> CGRect { return attributes?.frame ?? CGRect.zero } private func destinationRect(from attributes: UICollectionViewLayoutAttributes?) -> CGRect { guard let frame = attributes?.frame else { return CGRect.zero } return CGRect(x: frame.origin.x, y: frame.origin.y + 64.0, width: frame.size.width, height: frame.size.height) } private func lineViewFrame(with bounds: CGRect) -> CGRect { return CGRect(x: bounds.minX, y: bounds.maxY - 0.5, width: bounds.width, height: 1.0) } }
mit
7f44833f53a20064bee378865ec6937e
45.910891
169
0.680034
5.402509
false
false
false
false
roecrew/AudioKit
AudioKit/iOS/AudioKit/User Interface/AKPresetLoaderView.swift
2
6778
// // AKPresetLoaderView.swift // AudioKit for iOS // // Created by Aurelius Prochazka on 7/30/16. // Copyright © 2016 AudioKit. All rights reserved. // public class AKPresetLoaderView: UIView { var player: AKAudioPlayer? var presetOuterPath = UIBezierPath() var upOuterPath = UIBezierPath() var downOuterPath = UIBezierPath() var currentIndex = 0 var presets = [String]() var callback: String -> () var isPresetLoaded = false override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { isPresetLoaded = false let touchLocation = touch.locationInView(self) if upOuterPath.containsPoint(touchLocation) { currentIndex -= 1 isPresetLoaded = true } if downOuterPath.containsPoint(touchLocation) { currentIndex += 1 isPresetLoaded = true } if currentIndex < 0 { currentIndex = presets.count - 1 } if currentIndex >= presets.count { currentIndex = 0 } if isPresetLoaded { callback(presets[currentIndex]) setNeedsDisplay() } } } public init(presets: [String], frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60), callback: String -> ()) { self.callback = callback self.presets = presets super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func drawPresetLoader(presetName presetName: String = "None", isPresetLoaded: Bool = false) { //// General Declarations let context = UIGraphicsGetCurrentContext() //// Color Declarations let red = UIColor(red: 1.000, green: 0.000, blue: 0.062, alpha: 1.000) let gray = UIColor(red: 0.835, green: 0.842, blue: 0.836, alpha: 0.925) let green = UIColor(red: 0.029, green: 1.000, blue: 0.000, alpha: 1.000) let dark = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Variable Declarations let expression = isPresetLoaded ? green : red //// background Drawing let backgroundPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 440, height: 60)) gray.setFill() backgroundPath.fill() //// presetButton //// presetOuter Drawing presetOuterPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 95, height: 60)) expression.setFill() presetOuterPath.fill() //// presetLabel Drawing let presetLabelRect = CGRect(x: 0, y: 0, width: 95, height: 60) let presetLabelTextContent = NSString(string: "Preset") let presetLabelStyle = NSMutableParagraphStyle() presetLabelStyle.alignment = .Left let presetLabelFontAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(24), NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: presetLabelStyle] let presetLabelInset: CGRect = CGRectInset(presetLabelRect, 10, 0) let presetLabelTextHeight: CGFloat = presetLabelTextContent.boundingRectWithSize(CGSize(width: presetLabelInset.width, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: presetLabelFontAttributes, context: nil).size.height CGContextSaveGState(context) CGContextClipToRect(context, presetLabelInset) presetLabelTextContent.drawInRect(CGRect(x: presetLabelInset.minX, y: presetLabelInset.minY + (presetLabelInset.height - presetLabelTextHeight) / 2, width: presetLabelInset.width, height: presetLabelTextHeight), withAttributes: presetLabelFontAttributes) CGContextRestoreGState(context) //// upButton //// upOuter Drawing upOuterPath = UIBezierPath(rect: CGRect(x: 381, y: 0, width: 59, height: 30)) gray.setFill() upOuterPath.fill() //// upInner Drawing let upInnerPath = UIBezierPath() upInnerPath.moveToPoint(CGPoint(x: 395.75, y: 22.5)) upInnerPath.addLineToPoint(CGPoint(x: 425.25, y: 22.5)) upInnerPath.addLineToPoint(CGPoint(x: 410.5, y: 7.5)) upInnerPath.addLineToPoint(CGPoint(x: 410.5, y: 7.5)) upInnerPath.addLineToPoint(CGPoint(x: 395.75, y: 22.5)) upInnerPath.closePath() dark.setFill() upInnerPath.fill() //// downButton //// downOuter Drawing downOuterPath = UIBezierPath(rect: CGRect(x: 381, y: 30, width: 59, height: 30)) gray.setFill() downOuterPath.fill() //// downInner Drawing let downInnerPath = UIBezierPath() downInnerPath.moveToPoint(CGPoint(x: 410.5, y: 52.5)) downInnerPath.addLineToPoint(CGPoint(x: 410.5, y: 52.5)) downInnerPath.addLineToPoint(CGPoint(x: 425.25, y: 37.5)) downInnerPath.addLineToPoint(CGPoint(x: 395.75, y: 37.5)) downInnerPath.addLineToPoint(CGPoint(x: 410.5, y: 52.5)) downInnerPath.closePath() dark.setFill() downInnerPath.fill() //// nameLabel Drawing let nameLabelRect = CGRect(x: 95, y: 0, width: 345, height: 60) let nameLabelStyle = NSMutableParagraphStyle() nameLabelStyle.alignment = .Left let nameLabelFontAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(24), NSForegroundColorAttributeName: UIColor.blackColor(), NSParagraphStyleAttributeName: nameLabelStyle] let nameLabelInset: CGRect = CGRectInset(nameLabelRect, 10, 0) let nameLabelTextHeight: CGFloat = NSString(string: presetName).boundingRectWithSize(CGSize(width: nameLabelInset.width, height: CGFloat.infinity), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: nameLabelFontAttributes, context: nil).size.height CGContextSaveGState(context) CGContextClipToRect(context, nameLabelInset) NSString(string: presetName).drawInRect(CGRect(x: nameLabelInset.minX, y: nameLabelInset.minY + (nameLabelInset.height - nameLabelTextHeight) / 2, width: nameLabelInset.width, height: nameLabelTextHeight), withAttributes: nameLabelFontAttributes) CGContextRestoreGState(context) } override public func drawRect(rect: CGRect) { let presetName = isPresetLoaded ? presets[currentIndex] : "None" drawPresetLoader(presetName: presetName, isPresetLoaded: isPresetLoaded) } }
mit
04b8ce464ffbdde2b20d344c17384255
41.892405
274
0.640549
4.786017
false
false
false
false
juliangrosshauser/ImageCache
ImageCacheTests/Source/Classes/RemovingImageTests.swift
1
3839
// // RemovingImageTests.swift // ImageCacheTests // // Created by Julian Grosshauser on 13/07/15. // Copyright © 2015 Julian Grosshauser. All rights reserved. // import XCTest import ImageCache import DiskCache class RemovingImageTests: XCTestCase { override func setUp() { super.setUp() clearAllCachedImages() } func testRemoveAllImagesFromDiskRemovesDiskCacheDirectory() { let key = "TestRemovingAllImages" let image = testImageWithName("Square", fileExtension: .PNG) createImageInDiskCache(image, forKey: key) let completionExpectation = expectationWithDescription("completionHandler called") let completionHandler: Result<Void> -> Void = { result in if case .Failure(let error) = result { XCTFail("Removing all images failed: \(error)") } completionExpectation.fulfill() } imageCache.removeAllImagesFromDisk(true, completionHandler: completionHandler) waitForExpectationsWithTimeout(expectationTimeout, handler: nil) XCTAssertFalse(imageCacheFileManager.fileExistsAtPath(imageCache.diskCachePath), "Disk cache directory shouldn't exist anymore") } func testRemoveImageForKeyFromDiskRemovesCachedImage() { let key = "TestRemovingImage" let image = testImageWithName("Square", fileExtension: .PNG) createImageInDiskCache(image, forKey: key) let completionExpectation = expectationWithDescription("completionHandler called") let completionHandler: Result<Void> -> Void = { result in if case .Failure(let error) = result { XCTFail("Removing cached image failed: \(error)") } completionExpectation.fulfill() } do { try imageCache.removeImageForKey(key, fromDisk: true, completionHandler: completionHandler) } catch { XCTFail("Removing cached image failed: \(error)") } waitForExpectationsWithTimeout(expectationTimeout, handler: nil) XCTAssertFalse(cachedImageExistsOnDiskForKey(key), "Cached image shouldn't exist anymore") } func testRemoveImageForKeyFromDiskRemovesOnlyCachedImageForKey() { let keyThatShouldBeRemoved = "ImageShouldBeRemoved" let imageThatShouldBeRemoved = testImageWithName("Square", fileExtension: .PNG) let keyThatShouldntBeRemoved = "ImageShouldntBeRemoved" let imageThatShouldntBeRemoved = testImageWithName("Square", fileExtension: .PNG) createImageInDiskCache(imageThatShouldBeRemoved, forKey: keyThatShouldBeRemoved) createImageInDiskCache(imageThatShouldntBeRemoved, forKey: keyThatShouldntBeRemoved) let completionExpectation = expectationWithDescription("completionHandler called") let completionHandler: Result<Void> -> Void = { result in if case .Failure(let error) = result { XCTFail("Removing cached image failed: \(error)") } completionExpectation.fulfill() } do { try imageCache.removeImageForKey(keyThatShouldBeRemoved, fromDisk: true, completionHandler: completionHandler) } catch { XCTFail("Removing cached image failed: \(error)") } waitForExpectationsWithTimeout(expectationTimeout, handler: nil) XCTAssertFalse(cachedImageExistsOnDiskForKey(keyThatShouldBeRemoved), "Cached image shouldn't exist anymore") XCTAssertTrue(cachedImageExistsOnDiskForKey(keyThatShouldntBeRemoved), "Cached image shouldn't be removed") } }
mit
91e83f5d9b1df368b4218203f4b983e3
36.627451
136
0.655029
5.941176
false
true
false
false
Piwigo/Piwigo-Mobile
piwigo/Album/Extensions/AlbumViewController+DataSource.swift
1
17920
// // AlbumViewController+DataSource.swift // piwigo // // Created by Eddy Lelièvre-Berna on 29/07/2022. // Copyright © 2022 Piwigo.org. All rights reserved. // import Foundation import UIKit import piwigoKit extension AlbumViewController { func reloginAndReloadAlbumData(completion: @escaping () -> Void) { /// - Pause upload operations /// - Perform relogin /// - Reload album data /// - Resume upload operations in background queue /// and update badge, upload button of album navigator UploadManager.shared.isPaused = true // Display HUD when loading album data for the first time if AppVars.shared.nberOfAlbumsInCache == 0 { let title = NSLocalizedString("login_loggingIn", comment: "Logging In...") let detail = NSLocalizedString("login_connecting", comment: "Connecting") DispatchQueue.main.async { [unowned self] in navigationController?.showPiwigoHUD( withTitle: title, detail: detail, buttonTitle: NSLocalizedString("internetCancelledConnection_button", comment: "Cancel Connection"), buttonTarget: self, buttonSelector: #selector(cancelLoggingIn), inMode: .indeterminate) } } // Request server methods LoginUtilities.requestServerMethods { [unowned self] in // Known methods, pursue logging in… performLogin() { completion() } } didRejectCertificate: { [unowned self] error in requestCertificateApproval(afterError: error) { completion() } } didFailHTTPauthentication: { [unowned self] error in showErrorAndReturnToLoginView(error) } didFailSecureConnection: { [unowned self] error in showErrorAndReturnToLoginView(error) } failure: { [unowned self] error in showErrorAndReturnToLoginView(error) } } func requestCertificateApproval(afterError error: Error?, completion: @escaping () -> Void) { DispatchQueue.main.async { [unowned self] in let title = NSLocalizedString("loginCertFailed_title", comment: "Connection Not Private") let message = "\(NSLocalizedString("loginCertFailed_message", comment: "Piwigo warns you when a website has a certificate that is not valid. Do you still want to accept this certificate?"))\r\r\(NetworkVars.certificateInformation)" let cancelAction = UIAlertAction( title: NSLocalizedString("alertCancelButton", comment: "Cancel"), style: .cancel, handler: { [self] action in // Should forget certificate NetworkVars.didApproveCertificate = false // Report error showErrorAndReturnToLoginView(error) }) let acceptAction = UIAlertAction( title: NSLocalizedString("alertOkButton", comment: "OK"), style: .default, handler: { [self] action in // Will accept certificate NetworkVars.didApproveCertificate = true // Try logging in with approved certificate performLogin { completion() } }) presentPiwigoAlert(withTitle: title, message: message, actions: [cancelAction, acceptAction]) } } func performLogin(completion: @escaping () -> Void) { // Did the user cancel communication? if NetworkVars.userCancelledCommunication { showErrorAndReturnToLoginView(nil) return } // Perform login if username exists let username = NetworkVars.username if username.isEmpty { // Check Piwigo version, get token, available sizes, etc. getCommunityStatus() { completion() } } else { // Display HUD when loading album data for the first time if AppVars.shared.nberOfAlbumsInCache == 0 { DispatchQueue.main.async { [unowned self] in navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("login_loggingIn", comment: "Logging In..."), detail: NSLocalizedString("login_newSession", comment: "Opening Session"), buttonTitle: NSLocalizedString("internetCancelledConnection_button", comment: "Cancel Connection"), buttonTarget: self, buttonSelector: #selector(cancelLoggingIn), inMode: .indeterminate) } } // Perform login let password = KeychainUtilities.password(forService: NetworkVars.serverPath, account: username) LoginUtilities.sessionLogin(withUsername: NetworkVars.username, password: password) { [self] in // Session now opened // First determine user rights if Community extension installed getCommunityStatus() { completion() } } failure: { [unowned self] error in // Login request failed showErrorAndReturnToLoginView(NetworkVars.userCancelledCommunication ? nil : error) } } } func getCommunityStatus(completion: @escaping () -> Void) { // Did the user cancel communication? if NetworkVars.userCancelledCommunication { showErrorAndReturnToLoginView(nil) return } if NetworkVars.usesCommunityPluginV29 { // Display HUD when loading album data for the first time if AppVars.shared.nberOfAlbumsInCache == 0 { DispatchQueue.main.async { [unowned self] in navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("login_loggingIn", comment: "Logging In..."), detail: NSLocalizedString("login_communityParameters", comment: "Community Parameters"), buttonTitle: NSLocalizedString("internetCancelledConnection_button", comment: "Cancel Connection"), buttonTarget: self, buttonSelector: #selector(cancelLoggingIn), inMode: .indeterminate) } } // Community extension installed LoginUtilities.communityGetStatus { [unowned self] in // Check Piwigo version, get token, available sizes, etc. getSessionStatus() { completion() } } failure: { [unowned self] error in // Inform user that server failed to retrieve Community parameters showErrorAndReturnToLoginView(NetworkVars.userCancelledCommunication ? nil : error) } } else { // Community extension not installed // Check Piwigo version, get token, available sizes, etc. getSessionStatus() { completion() } } } func getSessionStatus(completion: @escaping () -> Void) { // Did the user cancel communication? if NetworkVars.userCancelledCommunication { showErrorAndReturnToLoginView(nil) return } // Display HUD when loading album data for the first time if AppVars.shared.nberOfAlbumsInCache == 0 { DispatchQueue.main.async { [unowned self] in navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("login_loggingIn", comment: "Logging In..."), detail: NSLocalizedString("login_serverParameters", comment: "Piwigo Parameters"), buttonTitle: NSLocalizedString("internetCancelledConnection_button", comment: "Cancel Connection"), buttonTarget: self, buttonSelector: #selector(cancelLoggingIn), inMode: .indeterminate) } } LoginUtilities.sessionGetStatus { [unowned self] in DispatchQueue.main.async { [unowned self] in print("••> Reload album data…") reloadAlbumData { // Resume upload operations in background queue // and update badge, upload button of album navigator UploadManager.shared.backgroundQueue.async { UploadManager.shared.resumeAll() } completion() } } } failure: { [self] error in showErrorAndReturnToLoginView(error) } } func reloadAlbumData(completion: @escaping () -> Void) { // Display HUD while downloading albums data recursively navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("loadingHUD_label", comment: "Loading…"), detail: NSLocalizedString("tabBar_albums", comment: "Albums"), buttonTitle: "", buttonTarget: nil, buttonSelector: nil, inMode: .indeterminate) // Load category data in recursive mode AlbumUtilities.getAlbums { didUpdateCats in DispatchQueue.main.async { [self] in // Check data source and reload collection if needed checkDataSource(withChangedCategories: didUpdateCats) { [self] in // Hide HUD navigationController?.hidePiwigoHUD() { completion() } // Update other album views if #available(iOS 13.0, *) { // Refresh other album views if any DispatchQueue.main.async { [self] in // Loop over all other active scenes let sessionID = view.window?.windowScene?.session.persistentIdentifier ?? "" let connectedScenes = UIApplication.shared.connectedScenes .filter({[.foregroundActive].contains($0.activationState)}) .filter({$0.session.persistentIdentifier != sessionID}) for scene in connectedScenes { if let windowScene = scene as? UIWindowScene, let albumVC = windowScene.topMostViewController() as? AlbumViewController { albumVC.checkDataSource(withChangedCategories: didUpdateCats) { } } } } } // Load favorites in the background if necessary AlbumUtilities.loadFavoritesInBckg() } } } failure: { error in DispatchQueue.main.async { [self] in // Set navigation bar buttons initButtonsInSelectionMode() // Hide HUD if needed navigationController?.hidePiwigoHUD() { [self] in dismissPiwigoError(withTitle: "", message: error.localizedDescription) { } } completion() } } } func checkDataSource(withChangedCategories didChange: Bool, completion: @escaping () -> Void) { print(String(format: "checkDataSource...=> ID:%ld - Categories did change:%@", categoryId, didChange ? "YES" : "NO")) // Does this album still exist? let album = CategoriesData.sharedInstance().getCategoryById(categoryId) if categoryId > 0, album == nil { // This album does not exist anymore let VCs = navigationController?.children var index = (VCs?.count ?? 0) - 1 while index >= 0 { if let vc = VCs?[index] as? AlbumViewController { if vc.categoryId == 0 || CategoriesData.sharedInstance().getCategoryById(vc.categoryId) != nil { // Present the album navigationController?.popToViewController(vc, animated: true) completion() return } } index -= 1 } // We did not find a parent album — should never happen… completion() return } // Root album -> reload collection if categoryId == 0 { if didChange { // Reload album collection imagesCollection?.reloadData() // Set navigation bar buttons updateButtonsInPreviewMode() } completion() return } // Non root or smart album if didChange, categoryId >= 0 { // Loop over all displayed albums to set titles and therefore back buttons for parentAlbumVC in navigationController?.children ?? [] { if let parentVC = parentAlbumVC as? AlbumViewController, parentVC.categoryId != categoryId { print("••> Update buttons in album #\(parentVC.categoryId) from album #\(categoryId)") if parentVC.categoryId == 0 { parentVC.title = NSLocalizedString("tabBar_albums", comment: "Albums") } else { parentVC.title = CategoriesData.sharedInstance().getCategoryById(parentVC.categoryId)?.name ?? NSLocalizedString("categorySelection_title", comment: "Album") } } } // Reload album collection imagesCollection?.reloadSections(IndexSet(integer: 0)) // Set navigation bar buttons updateButtonsInPreviewMode() } // Other album —> If the number of images in cache is null, reload collection if album == nil || album?.imageList?.count == 0 { // Something did change… reset album data albumData = AlbumData(categoryId: categoryId, andQuery: "") // Reload collection if categoryId < 0 { // Load, sort images and reload collection albumData?.updateImageSort(kPiwigoSortObjc(rawValue: UInt32(AlbumVars.shared.defaultSort)), onCompletion: { [self] in // Reset navigation bar buttons after image load updateButtonsInPreviewMode() imagesCollection?.reloadData() }, onFailure: { [unowned self] _, error in dismissPiwigoError(withTitle: NSLocalizedString("albumPhotoError_title", comment: "Get Album Photos Error"), message: NSLocalizedString("albumPhotoError_message", comment: "Failed to get album photos (corrupt image in your album?)"), errorMessage: error?.localizedDescription ?? "") { } }) } else { imagesCollection?.reloadSections(IndexSet(integer: 1)) } // Cancel selection cancelSelect() } completion() } @objc func cancelLoggingIn() { // Propagate user's request NetworkVars.userCancelledCommunication = true PwgSession.shared.dataSession.getAllTasks(completionHandler: { tasks in tasks.forEach { task in task.cancel() } }) NetworkVarsObjc.sessionManager!.tasks.forEach { task in task.cancel() } // Update login HUD navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("login_loggingIn", comment: "Logging In..."), detail: NSLocalizedString("internetCancellingConnection_button", comment: "Cancelling Connection…"), buttonTitle: NSLocalizedString("internetCancelledConnection_button", comment: "Cancel Connection"), buttonTarget: self, buttonSelector: #selector(cancelLoggingIn), inMode: .indeterminate) } private func showErrorAndReturnToLoginView(_ error: Error?) { DispatchQueue.main.async { [self] in if error == nil { navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("internetCancelledConnection_title", comment: "Connection Cancelled"), detail: " ", buttonTitle: NSLocalizedString("alertDismissButton", comment: "Dismiss"), buttonTarget: self, buttonSelector: #selector(hideLoading), inMode: .text) } else { var detail = error?.localizedDescription ?? "" if detail.isEmpty { detail = String(format: "%ld", (error as NSError?)?.code ?? 0) } navigationController?.showPiwigoHUD( withTitle: NSLocalizedString("internetErrorGeneral_title", comment: "Connection Error"), detail: detail, buttonTitle: NSLocalizedString("alertDismissButton", comment: "Dismiss"), buttonTarget: self, buttonSelector: #selector(hideLoading), inMode: .text) } } } @objc func hideLoading() { // Reinitialise flag NetworkVars.userCancelledCommunication = false // Hide HUD navigationController?.hidePiwigoHUD() { // Return to login view ClearCache.closeSessionAndClearCache { } } } }
mit
93e9c386413f4cd30c2d8e6b4b849a77
44.882051
306
0.558511
5.911463
false
false
false
false
S-Shimotori/Chalcedony
Chalcedony/Pods/PromiseKit/Categories/UIKit/UIActionSheet+Promise.swift
2
1372
import PromiseKit import UIKit.UIActionSheet /** To import the `UIActionSheet` category: use_frameworks! pod "PromiseKit/UIKit" Or `UIKit` is one of the categories imported by the umbrella pod: use_frameworks! pod "PromiseKit" And then in your sources: import PromiseKit */ extension UIActionSheet { public func promiseInView(view: UIView) -> Promise<Int> { let proxy = PMKActionSheetDelegate() delegate = proxy proxy.retainCycle = proxy showInView(view) if numberOfButtons == 1 && cancelButtonIndex == 0 { NSLog("PromiseKit: An action sheet is being promised with a single button that is set as the cancelButtonIndex. The promise *will* be cancelled which may result in unexpected behavior. See http://promisekit.org/PromiseKit-2.0-Released/ for cancellation documentation.") } return proxy.promise } } private class PMKActionSheetDelegate: NSObject, UIActionSheetDelegate { let (promise, fulfill, reject) = Promise<Int>.defer() var retainCycle: NSObject? @objc func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) { if buttonIndex != actionSheet.cancelButtonIndex { fulfill(buttonIndex) } else { reject(NSError.cancelledError()) } retainCycle = nil } }
mit
c83b07b37014cb91b2d7308a1b7dfb0c
28.826087
281
0.685131
4.953069
false
false
false
false
JiachengZheng/JCWebView
JCWebViewDemo/Swift/JCWebViewDemo/JCWebViewDemo/ViewController.swift
1
4398
// // ViewController.swift // JCWebViewDemo // // Created by 郑嘉成 on 2017/9/28. // Copyright © 2017年 zhengjiacheng. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController { public var webView :JCWebViewProtocol? var progressView: JCWebProgressView? fileprivate var forceUseWKWebView = true fileprivate var loadProgress: CGFloat = 0.0 fileprivate var timer: DispatchSourceTimer? open func createProgressView(_ frame: CGRect){ if self.progressView != nil { return } progressView = JCWebProgressView(frame: frame) self.view.addSubview(progressView!) } fileprivate func startWebLoadProgress(){ stopTimer() loadProgress = 0.4 timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main) timer!.scheduleRepeating(deadline: .now(), interval: .milliseconds(100)) timer!.setEventHandler( handler: { [weak self] in self?.addWebViewLoadProgress() }) timer!.resume() } fileprivate func addWebViewLoadProgress(){ let step: CGFloat = 0.1 if loadProgress < 0.8 { loadProgress += step } progressView?.progress = loadProgress } fileprivate func stopWebViewLoadProgress(){ progressView?.progress = 1 stopTimer() } fileprivate func stopTimer(){ timer?.cancel() timer = nil } func createUIWebView(_ frame: CGRect) -> JCWebViewProtocol{ let webView = UIWebView(frame: frame) webView.autoresizingMask = [UIViewAutoresizing.flexibleWidth,UIViewAutoresizing.flexibleHeight] webView.allowsInlineMediaPlayback = true webView.backgroundColor = UIColor.white return webView } func createWKWebView(_ frame: CGRect) -> JCWebViewProtocol{ let config = WKWebViewConfiguration() let preference = WKPreferences() config.preferences = preference config.allowsInlineMediaPlayback = true let contentController = WKUserContentController() config.userContentController = contentController let webView = WKWebView(frame: frame) webView.backgroundColor = UIColor.white webView.allowsBackForwardNavigationGestures = true webView.autoresizingMask = [UIViewAutoresizing.flexibleWidth,UIViewAutoresizing.flexibleHeight] return webView } open func createWebView(_ frame: CGRect){ webView = forceUseWKWebView ? createWKWebView(frame) : createUIWebView(frame) webView?.innerScrollView.delegate = self webView?.webDelegate = self if let view = webView as? UIView { self.view.addSubview(view) } } override open func viewDidLoad() { super.viewDidLoad() createWebView(CGRect(x: 0, y: 20, width: self.view.frame.size.width, height: self.view.frame.size.height - 20)) createProgressView(CGRect(x: 0, y: 20, width: 0, height: 2)) if let url = URL(string: "http://www.jianshu.com/u/3d8439db292b"){ loadURL(url) } } open func loadURL(_ URL: URL){ var request = URLRequest(url: URL) loadRequest(&request) } open func loadRequest(_ request: inout URLRequest){ webView?.loadUrlRequest(&request) } deinit { stopWebViewLoadProgress() webView?.stopLoadingWeb() webView?.webDelegate = nil webView?.innerScrollView.delegate = nil } } extension ViewController: JCWebViewDelegate{ public func webView(_ webView: JCWebViewProtocol, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{ return true } public func webViewDidStartLoad(_ webView: JCWebViewProtocol){ startWebLoadProgress() } public func webViewDidFinishLoad(_ webView: JCWebViewProtocol){ stopWebViewLoadProgress() } public func webView(_ webView: JCWebViewProtocol, didFailLoadWithError error: Error){ stopWebViewLoadProgress() } } extension ViewController: UIScrollViewDelegate{ public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { scrollView.decelerationRate = UIScrollViewDecelerationRateNormal } }
mit
1fd6e7b235a89db46e51134649020c3d
30.57554
144
0.65573
5.206406
false
false
false
false
modocache/swift
test/Prototypes/TextFormatting.swift
3
9938
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // Text Formatting Prototype // // This file demonstrates the concepts proposed in TextFormatting.rst // FIXME: Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. infix operator ~> { precedence 255 } /// \brief A thing into which we can stream text protocol XOutputStream { mutating func append(_ text: String) } /// \brief Strings are XOutputStreams extension String: XOutputStream { mutating func append(_ text: String) { self += text } } /// \brief A thing that can be written to an XOutputStream protocol XStreamable { func writeTo<Target: XOutputStream>(_ target: inout Target) } /// \brief A thing that can be printed in the REPL and the Debugger /// /// Everything compiler-magically conforms to this protocol. To /// change the debug representation for a type, you don't need to /// declare conformance: simply give the type a debugFormat(). protocol XDebugPrintable { associatedtype DebugRepresentation : XStreamable // = String /// \brief Produce a textual representation for the REPL and /// Debugger. /// /// Because String is a XStreamable, your implementation of /// debugRepresentation can just return a String. If you want to write /// directly to the XOutputStream for efficiency reasons, /// (e.g. if your representation is huge), you can return a custom /// DebugRepresentation type. /// /// NOTE: producing a representation that can be consumed by the /// REPL to produce an equivalent object is strongly encouraged /// where possible! For example, String.debugFormat() produces a /// representation containing quotes, where special characters are /// escaped, etc. A struct Point { var x, y: Int } might be /// represented as "Point(x: 3, y: 5)". func debugFormat() -> DebugRepresentation } /// \brief Strings are XStreamable extension String : XStreamable { func writeTo<Target: XOutputStream>(_ target: inout Target) { target.append(self) } } // FIXME: Should be a method of XDebugPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled func toDebugString <T:XDebugPrintable> (_ x: T) -> String { var result = "" x.debugFormat().writeTo(&result) return result } // FIXME: The following should be a method of XPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled struct __PrintedFormat {} func format() -> __PrintedFormat { return __PrintedFormat() } func ~> <T:XDebugPrintable> (x: T, _: __PrintedFormat) -> T.DebugRepresentation { return x.debugFormat() } /// \brief A thing that can be xprint()ed and toString()ed. /// /// Conformance to XPrintable is explicit, but if you want to use the /// debugFormat() results for your type's format(), all you need /// to do is declare conformance to XPrintable, and there's nothing to /// implement. protocol XPrintable: XDebugPrintable { associatedtype PrintRepresentation: XStreamable = DebugRepresentation /// \brief produce a "pretty" textual representation that can be /// distinct from the debug format. For example, /// String.printRepresentation returns the string itself, without quoting. /// /// In general you can return a String here, but if you need more /// control, we strongly recommend returning a custom Representation /// type, e.g. a nested struct of your type. If you're lazy, you /// can conform to XStreamable directly and just implement its /// write() func. func ~> (x: Self, _: __PrintedFormat) -> PrintRepresentation } // FIXME: The following should be a method of XPrintable once // <rdar://problem/14692224> (Default Implementations in Protocols) is // handled /// \brief Simply convert to String /// /// Don't reimplement this: the default implementation always works. /// If you must reimplement toString(), make sure its results are /// consistent with those of format() (i.e. you shouldn't /// change the behavior). func toString<T: XPrintable>(_ x: T) -> String { var result = "" (x~>format()).writeTo(&result) return result } // \brief Streamer for the debug representation of String. When an // EscapedStringFormat is written to a XOutputStream, it adds // surrounding quotes and escapes special characters. struct EscapedStringFormat : XStreamable { init(_ s: String) { self._value = s } func writeTo<Target: XOutputStream>(_ target: inout Target) { target.append("\"") for c in _value.unicodeScalars { target.append(c.escaped(asASCII: true)) } target.append("\"") } var _value: String } // FIXME: In theory, this shouldn't be needed extension String: XDebugPrintable {} extension String : XPrintable { func debugFormat() -> EscapedStringFormat { return EscapedStringFormat(self) } func format() -> String { return self } } /// \brief An integral type that can be printed protocol XPrintableInteger : ExpressibleByIntegerLiteral, Comparable, SignedNumber, XPrintable { func %(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self // FIXME: Stand-in for constructor pending <rdar://problem/13695680> // (Constructor requirements in protocols) static func fromInt(_ x: Int) -> Self func toInt() -> Int } extension Int : XDebugPrintable { func debugFormat() -> String { return String(self) } } extension Int : XPrintableInteger { static func fromInt(_ x: Int) -> Int { return x } func toInt() -> Int { return self } func getValue() -> Int { return self } } struct _formatArgs { var radix: Int, fill: String, width: Int } func format(radix radix: Int = 10, fill: String = " ", width: Int = 0) -> _formatArgs { return _formatArgs(radix: radix, fill: fill, width: width) } // FIXME: this function was a member of RadixFormat, but // <rdar://problem/15525229> (SIL verification failed: operand of // 'apply' doesn't match function input type) changed all that. func _writePositive<T:XPrintableInteger, S: XOutputStream>( _ value: T, _ stream: inout S, _ args: _formatArgs) -> Int { if value == 0 { return 0 } var radix: T = T.fromInt(args.radix) var rest: T = value / radix var nDigits = _writePositive(rest, &stream, args) var digit = UInt32((value % radix).toInt()) var baseCharOrd : UInt32 = digit <= 9 ? UnicodeScalar("0").value : UnicodeScalar("A").value - 10 stream.append(String(UnicodeScalar(baseCharOrd + digit)!)) return nDigits + 1 } // FIXME: this function was a member of RadixFormat, but // <rdar://problem/15525229> (SIL verification failed: operand of // 'apply' doesn't match function input type) changed all that. func _writeSigned<T:XPrintableInteger, S: XOutputStream>( _ value: T, _ target: inout S, _ args: _formatArgs ) { var width = 0 var result = "" if value == 0 { result = "0" width += 1 } else { var absVal = abs(value) if (value < 0) { target.append("-") width += 1 } width += _writePositive(absVal, &result, args) } while width < args.width { width += 1 target.append(args.fill) } target.append(result) } struct RadixFormat<T: XPrintableInteger> : XStreamable { init(value: T, args: _formatArgs) { self.value = value self.args = args } func writeTo<S: XOutputStream>(_ target: inout S) { _writeSigned(value, &target, args) } typealias DebugRepresentation = String func debugFormat() -> String { return "RadixFormat(" + toDebugString(value) + ", " + toDebugString(args.radix) + ")" } var value: T var args: _formatArgs } func ~> <T:XPrintableInteger> (x: T, _: __PrintedFormat) -> RadixFormat<T> { return RadixFormat(value: x, args: format()) } func ~> <T:XPrintableInteger> (x: T, args: _formatArgs) -> RadixFormat<T> { return RadixFormat(value: x, args: args) } // ========== // // xprint and xprintln // struct StdoutStream : XOutputStream { func append(_ text: String) { Swift.print(text, terminator: "") } // debugging only func dump() -> String { return "<StdoutStream>" } } func xprint<Target: XOutputStream, T: XStreamable>(_ target: inout Target, _ x: T) { x.writeTo(&target) } func xprint<Target: XOutputStream, T: XPrintable>(_ target: inout Target, _ x: T) { xprint(&target, x~>format()) } func xprint<T: XPrintable>(_ x: T) { var target = StdoutStream() xprint(&target, x) } func xprint<T: XStreamable>(_ x: T) { var target = StdoutStream() xprint(&target, x) } func xprintln<Target: XOutputStream, T: XPrintable>(_ target: inout Target, _ x: T) { xprint(&target, x) target.append("\n") } func xprintln<Target: XOutputStream, T: XStreamable>(_ target: inout Target, _ x: T) { xprint(&target, x) target.append("\n") } func xprintln<T: XPrintable>(_ x: T) { var target = StdoutStream() xprintln(&target, x) } func xprintln<T: XStreamable>(_ x: T) { var target = StdoutStream() xprintln(&target, x) } func xprintln(_ x: String) { var target = StdoutStream() x.writeTo(&target) "\n".writeTo(&target) } extension String { init <T: XStreamable>(_ x: T) { self = "" xprint(&self, x) } } func toPrettyString<T: XStreamable>(_ x: T) -> String { var result = "|" xprint(&result, x) result += "|" return result } // =========== var x = "fubar\n\tbaz" xprintln(x) // CHECK: fubar // CHECK-NEXT: baz xprintln(toDebugString(x)) // CHECK-NEXT: "fubar\n\tbaz" xprintln(toPrettyString(424242~>format(radix:16, width:8))) // CHECK-NEXT: | 67932| var zero = "0" xprintln(toPrettyString(-434343~>format(fill:zero, width:8))) // CHECK-NEXT: |-0434343| xprintln(toPrettyString(-42~>format(radix:13, width:8))) // CHECK-NEXT: |- 33| xprintln(0x1EADBEEF~>format(radix:16)) // CHECK-NEXT: 1EADBEEF // FIXME: rdar://16168414 this doesn't work in 32-bit // xprintln(0xDEADBEEF~>format(radix:16)) // CHECK-NEXT-not: DEADBEEF
apache-2.0
e190ac21bca09cc904ddd597ffa33963
26.37741
96
0.677702
3.579971
false
false
false
false
ashfurrow/eidolon
Kiosk/Sale Artwork Details/SaleArtworkDetailsViewController.swift
2
19063
import UIKit import ORStackView import Artsy_UILabels import Artsy_UIFonts import RxSwift import Artsy_UIButtons import SDWebImage import Action class SaleArtworkDetailsViewController: UIViewController { var allowAnimations = true var auctionID = AppSetup.sharedState.auctionID var saleArtwork: SaleArtwork! var provider: Networking! var showBuyersPremiumCommand = { () -> CocoaAction in appDelegate().showBuyersPremiumCommand() } class func instantiateFromStoryboard(_ storyboard: UIStoryboard) -> SaleArtworkDetailsViewController { return storyboard.viewController(withID: .SaleArtworkDetail) as! SaleArtworkDetailsViewController } lazy var artistInfo: Observable<Any> = { let artistInfo = self.provider.request(.artwork(id: self.saleArtwork.artwork.id)).filterSuccessfulStatusCodes().mapJSON() return artistInfo.share(replay: 1) }() @IBOutlet weak var metadataStackView: ORTagBasedAutoStackView! @IBOutlet weak var additionalDetailScrollView: ORStackScrollView! var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium } let layoutSubviews = PublishSubject<Void>() let viewWillAppear = PublishSubject<Void>() override func viewDidLoad() { super.viewDidLoad() setupMetadataView() setupAdditionalDetailStackView() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // OK, so this is pretty weird, eh? So basically we need to be notified of layout changes _just after_ the layout // is actually done. For whatever reason, the UIKit hack to get the labels to adhere to their proper width only // works if we defer recalculating their geometry to the next runloop. // This wasn't an issue with RAC's rac_signalForSelector because that invoked the signal _after_ this method completed. // So that's what I've done here. DispatchQueue.main.async { self.layoutSubviews.onNext(Void()) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewWillAppear.onCompleted() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue == .ZoomIntoArtwork { let nextViewController = segue.destination as! SaleArtworkZoomViewController nextViewController.saleArtwork = saleArtwork } } enum MetadataStackViewTag: Int { case lotNumberLabel = 1 case artistNameLabel case artworkNameLabel case artworkMediumLabel case artworkDimensionsLabel case imageRightsLabel case estimateTopBorder case estimateLabel case estimateBottomBorder case currentBidLabel case currentBidValueLabel case numberOfBidsPlacedLabel case bidButton case buyersPremium } @IBAction func backWasPressed(_ sender: AnyObject) { _ = navigationController?.popViewController(animated: true) } fileprivate func setupMetadataView() { enum LabelType { case serif case sansSerif case italicsSerif case bold } func label(_ type: LabelType, tag: MetadataStackViewTag, fontSize: CGFloat = 16.0) -> UILabel { let label: UILabel = { () -> UILabel in switch type { case .serif: return ARSerifLabel() case .sansSerif: return ARSansSerifLabel() case .italicsSerif: return ARItalicsSerifLabel() case .bold: let label = ARSerifLabel() label.font = UIFont.sansSerifFont(withSize: label.font.pointSize) return label } }() label.lineBreakMode = .byWordWrapping label.font = label.font.withSize(fontSize) label.tag = tag.rawValue label.preferredMaxLayoutWidth = 276 return label } let hasLotNumber = (saleArtwork.lotLabel != nil) if let _ = saleArtwork.lotLabel { let lotNumberLabel = label(.sansSerif, tag: .lotNumberLabel) lotNumberLabel.font = lotNumberLabel.font.withSize(12) metadataStackView.addSubview(lotNumberLabel, withTopMargin: "0", sideMargin: "0") saleArtwork .viewModel .lotLabel() .filterNil() .mapToOptional() .bind(to: lotNumberLabel.rx.text) .disposed(by: rx.disposeBag) } if let artist = artist() { let artistNameLabel = label(.sansSerif, tag: .artistNameLabel) artistNameLabel.text = artist.name metadataStackView.addSubview(artistNameLabel, withTopMargin: hasLotNumber ? "10" : "0", sideMargin: "0") } let artworkNameLabel = label(.italicsSerif, tag: .artworkNameLabel) artworkNameLabel.text = "\(saleArtwork.artwork.title), \(saleArtwork.artwork.date)" metadataStackView.addSubview(artworkNameLabel, withTopMargin: "10", sideMargin: "0") if let medium = saleArtwork.artwork.medium { if medium.isNotEmpty { let mediumLabel = label(.serif, tag: .artworkMediumLabel) mediumLabel.text = medium metadataStackView.addSubview(mediumLabel, withTopMargin: "22", sideMargin: "0") } } if saleArtwork.artwork.dimensions.count > 0 { let dimensionsLabel = label(.serif, tag: .artworkDimensionsLabel) dimensionsLabel.text = (saleArtwork.artwork.dimensions as NSArray).componentsJoined(by: "\n") metadataStackView.addSubview(dimensionsLabel, withTopMargin: "5", sideMargin: "0") } retrieveImageRights() .filter { imageRights -> Bool in return imageRights.isNotEmpty }.subscribe(onNext: { [weak self] imageRights in let rightsLabel = label(.serif, tag: .imageRightsLabel) rightsLabel.text = imageRights self?.metadataStackView.addSubview(rightsLabel, withTopMargin: "22", sideMargin: "0") }) .disposed(by: rx.disposeBag) let estimateTopBorder = UIView() estimateTopBorder.constrainHeight("1") estimateTopBorder.tag = MetadataStackViewTag.estimateTopBorder.rawValue metadataStackView.addSubview(estimateTopBorder, withTopMargin: "22", sideMargin: "0") var estimateBottomBorder: UIView? let estimateString = saleArtwork.viewModel.estimateString if estimateString.isNotEmpty { let estimateLabel = label(.serif, tag: .estimateLabel) estimateLabel.text = estimateString metadataStackView.addSubview(estimateLabel, withTopMargin: "15", sideMargin: "0") estimateBottomBorder = UIView() _ = estimateBottomBorder?.constrainHeight("1") estimateBottomBorder?.tag = MetadataStackViewTag.estimateBottomBorder.rawValue metadataStackView.addSubview(estimateBottomBorder, withTopMargin: "10", sideMargin: "0") } viewWillAppear .subscribe(onCompleted: { [weak estimateTopBorder, weak estimateBottomBorder] in estimateTopBorder?.drawDottedBorders() estimateBottomBorder?.drawDottedBorders() }) .disposed(by: rx.disposeBag) let hasBids = saleArtwork .rx.observe(NSNumber.self, "highestBidCents") .map { observeredCents -> Bool in guard let cents = observeredCents as? Int else { return false } return cents > 0 } let currentBidLabel = label(.serif, tag: .currentBidLabel) hasBids .flatMap { hasBids -> Observable<String> in if hasBids { return .just("Current Bid:") } else { return .just("Starting Bid:") } } .mapToOptional() .bind(to: currentBidLabel.rx.text) .disposed(by: rx.disposeBag) metadataStackView.addSubview(currentBidLabel, withTopMargin: "22", sideMargin: "0") let currentBidValueLabel = label(.bold, tag: .currentBidValueLabel, fontSize: 27) saleArtwork .viewModel .currentBid() .mapToOptional() .bind(to: currentBidValueLabel.rx.text) .disposed(by: rx.disposeBag) metadataStackView.addSubview(currentBidValueLabel, withTopMargin: "10", sideMargin: "0") let numberOfBidsPlacedLabel = label(.serif, tag: .numberOfBidsPlacedLabel) saleArtwork .viewModel .numberOfBidsWithReserve .mapToOptional() .bind(to: numberOfBidsPlacedLabel.rx.text) .disposed(by: rx.disposeBag) metadataStackView.addSubview(numberOfBidsPlacedLabel, withTopMargin: "10", sideMargin: "0") let bidButton = ActionButton() bidButton .rx.tap .asObservable() .subscribe(onNext: { [weak self] _ in guard let me = self else { return } me.bid(auctionID: me.auctionID, saleArtwork: me.saleArtwork, allowAnimations: me.allowAnimations, provider: me.provider) }) .disposed(by: rx.disposeBag) saleArtwork .viewModel .forSale() .subscribe(onNext: { [weak bidButton] forSale in let forSale = forSale let title = forSale ? "BID" : "SOLD" bidButton?.setTitle(title, for: .normal) }) .disposed(by: rx.disposeBag) saleArtwork .viewModel .forSale() .bind(to: bidButton.rx.isEnabled) .disposed(by: rx.disposeBag) bidButton.tag = MetadataStackViewTag.bidButton.rawValue metadataStackView.addSubview(bidButton, withTopMargin: "40", sideMargin: "0") if let _ = buyersPremium() { let buyersPremiumView = UIView() buyersPremiumView.tag = MetadataStackViewTag.buyersPremium.rawValue let buyersPremiumLabel = ARSerifLabel() buyersPremiumLabel.font = buyersPremiumLabel.font.withSize(16) buyersPremiumLabel.text = "This work has a " buyersPremiumLabel.textColor = .artsyGrayBold() var buyersPremiumButton = ARButton() let title = "buyers premium" let attributes: [NSAttributedStringKey: Any] = [ NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.font: buyersPremiumLabel.font ] let attributedTitle = NSAttributedString(string: title, attributes: attributes) buyersPremiumButton.setTitle(title, for: .normal) buyersPremiumButton.titleLabel?.attributedText = attributedTitle; buyersPremiumButton.setTitleColor(.artsyGrayBold(), for: .normal) buyersPremiumButton.rx.action = showBuyersPremiumCommand() buyersPremiumView.addSubview(buyersPremiumLabel) buyersPremiumView.addSubview(buyersPremiumButton) buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, to: buyersPremiumView) buyersPremiumLabel.alignBaseline(with: buyersPremiumButton, predicate: nil) buyersPremiumButton.alignAttribute(.left, to: .right, of: buyersPremiumLabel, predicate: "0") metadataStackView.addSubview(buyersPremiumView, withTopMargin: "30", sideMargin: "0") } metadataStackView.bottomMarginHeight = CGFloat(NSNotFound) } fileprivate func setupImageView(_ imageView: UIImageView) { if let image = saleArtwork.artwork.defaultImage { // We'll try to retrieve the thumbnail image from the cache. If we don't have it, we'll set the background colour to grey to indicate that we're downloading it. let key = SDWebImageManager.shared().cacheKey(for: image.thumbnailURL() as URL!) let thumbnailImage = SDImageCache.shared().imageFromDiskCache(forKey: key) if thumbnailImage == nil { imageView.backgroundColor = .artsyGrayLight() } imageView.sd_setImage(with: image.fullsizeURL(), placeholderImage: thumbnailImage, options: [], completed: { (image, _, _, _) in // If the image was successfully downloaded, make sure we aren't still displaying grey. if image != nil { imageView.backgroundColor = .clear } }) let heightConstraintNumber = { () -> CGFloat in if let aspectRatio = image.aspectRatio { if aspectRatio != 0 { return min(400, CGFloat(538) / aspectRatio) } } return 400 }() imageView.constrainHeight( "\(heightConstraintNumber)" ) imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true let recognizer = UITapGestureRecognizer() imageView.addGestureRecognizer(recognizer) recognizer .rx.event .asObservable() .subscribe(onNext: { [weak self] _ in self?.performSegue(.ZoomIntoArtwork) }) .disposed(by: rx.disposeBag) } } fileprivate func setupAdditionalDetailStackView() { enum LabelType { case header case body } func label(_ type: LabelType, layout: Observable<Void>? = nil) -> UILabel { let (label, fontSize) = { () -> (UILabel, CGFloat) in switch type { case .header: return (ARSansSerifLabel(), 14) case .body: return (ARSerifLabel(), 16) } }() label.font = label.font.withSize(fontSize) label.lineBreakMode = .byWordWrapping layout? .take(1) .subscribe(onNext: { [weak label] (_) in if let label = label { label.preferredMaxLayoutWidth = label.frame.width } }) .disposed(by: rx.disposeBag) return label } additionalDetailScrollView.stackView.bottomMarginHeight = 40 let imageView = UIImageView() additionalDetailScrollView.stackView.addSubview(imageView, withTopMargin: "0", sideMargin: "40") setupImageView(imageView) let additionalInfoHeaderLabel = label(.header) additionalInfoHeaderLabel.text = "Additional Information" additionalDetailScrollView.stackView.addSubview(additionalInfoHeaderLabel, withTopMargin: "20", sideMargin: "40") if let blurb = saleArtwork.artwork.blurb { let blurbLabel = label(.body, layout: layoutSubviews) blurbLabel.attributedText = MarkdownParser().attributedString( fromMarkdownString: blurb ) additionalDetailScrollView.stackView.addSubview(blurbLabel, withTopMargin: "22", sideMargin: "40") } let additionalInfoLabel = label(.body, layout: layoutSubviews) additionalInfoLabel.attributedText = MarkdownParser().attributedString( fromMarkdownString: saleArtwork.artwork.additionalInfo ) additionalDetailScrollView.stackView.addSubview(additionalInfoLabel, withTopMargin: "22", sideMargin: "40") retrieveAdditionalInfo() .filter { info in return info.isNotEmpty }.subscribe(onNext: { [weak self] info in additionalInfoLabel.attributedText = MarkdownParser().attributedString(fromMarkdownString: info) self?.view.setNeedsLayout() self?.view.layoutIfNeeded() }) .disposed(by: rx.disposeBag) if let artist = artist() { retrieveArtistBlurb() .filter { blurb in return blurb.isNotEmpty } .subscribe(onNext: { [weak self] blurb in guard let me = self else { return } let aboutArtistHeaderLabel = label(.header) aboutArtistHeaderLabel.text = "About \(artist.name)" me.additionalDetailScrollView.stackView.addSubview(aboutArtistHeaderLabel, withTopMargin: "22", sideMargin: "40") let aboutAristLabel = label(.body, layout: me.layoutSubviews) aboutAristLabel.attributedText = MarkdownParser().attributedString(fromMarkdownString: blurb) me.additionalDetailScrollView.stackView.addSubview(aboutAristLabel, withTopMargin: "22", sideMargin: "40") }) .disposed(by: rx.disposeBag) } } fileprivate func artist() -> Artist? { return saleArtwork.artwork.artists?.first } fileprivate func retrieveImageRights() -> Observable<String> { let artwork = saleArtwork.artwork if let imageRights = artwork.imageRights { return .just(imageRights) } else { return artistInfo.map{ json in return (json as AnyObject)["image_rights"] as? String } .filterNil() .do(onNext: { imageRights in artwork.imageRights = imageRights }) } } fileprivate func retrieveAdditionalInfo() -> Observable<String> { let artwork = saleArtwork.artwork if let additionalInfo = artwork.additionalInfo { return .just(additionalInfo) } else { return artistInfo.map{ json in return (json as AnyObject)["additional_information"] as? String } .filterNil() .do(onNext: { info in artwork.additionalInfo = info }) } } fileprivate func retrieveArtistBlurb() -> Observable<String> { guard let artist = artist() else { return .empty() } if let blurb = artist.blurb { return .just(blurb) } else { let retrieveArtist = provider.request(.artist(id: artist.id)) .filterSuccessfulStatusCodes() .mapJSON() return retrieveArtist.map{ json in return (json as AnyObject)["blurb"] as? String } .filterNil() .do(onNext: { blurb in artist.blurb = blurb }) } } }
mit
8a6d45cb1ec262e5d37c83a0db40f9e9
38.22428
172
0.600692
5.710905
false
false
false
false
nataliq/TripCheckins
TripCheckins/Checkin List/CheckinListViewController.swift
1
4015
// // CheckinListViewController.swift // TripCheckins // // Created by Nataliya on 8/9/17. // Copyright © 2017 Nataliya Patsovska. All rights reserved. // import Foundation protocol CheckinListViewControllerDelegate: class { } extension CheckinListViewController: DateFiltering { func filter(withDateFilter dateFilter: DateFilter) { if let controller = controller as? DateFiltering { controller.filter(withDateFilter: dateFilter) } } } class CheckinListViewController: UITableViewController { private(set) var controller: CheckinListController private var listViewModels: [CheckinListItemViewModel]? { didSet { self.tableView.reloadData() } } weak var delegate: CheckinListViewControllerDelegate? init(controller: CheckinListController) { self.controller = controller super.init(nibName: nil, bundle: nil) self.controller.onViewModelUpdate = { [weak self] in guard let listViewModel = self?.controller.currentListViewModel else { return } self?.configureWithViewModel(listViewModel) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.allowsSelection = false tableView.tableFooterView = UIView() let refreshAction = #selector(refresh(_:)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: refreshAction) let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: refreshAction, for: .valueChanged) tableView.addSubview(refreshControl) self.refreshControl = refreshControl controller.reloadListItems() } private func revealRefreshControlIfContentIsNotScrolled() { guard let refreshControl = refreshControl else { return } guard tableView.contentOffset.y <= 0 else { return } let yOffset = tableView.contentOffset.y - refreshControl.frame.size.height tableView.setContentOffset(CGPoint(x: tableView.contentOffset.x, y: yOffset), animated: true) } // MARK: - Actions @objc func refresh(_ sender: Any) { controller.reloadListItems() } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listViewModels?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CheckinTableViewCell cell.configure(withViewModel: listViewModels![indexPath.row]) return cell } // MARK: - View-model configuration private func configureWithViewModel(_ viewModel: CheckinListViewModel) { title = viewModel.title let nib = UINib(nibName: "CompactCheckinTableViewCell", bundle: Bundle(for: self.classForCoder)) tableView.register(nib, forCellReuseIdentifier: "Cell") switch viewModel.listItemViewsType { case .compact: tableView.rowHeight = 80 case .normal: tableView.rowHeight = 120 } updateViewsForViewModelState(viewModel.state) } private func updateViewsForViewModelState(_ state: ListViewModelState) { guard isViewLoaded else { return } switch state { case .loadingItems: refreshControl?.beginRefreshing() revealRefreshControlIfContentIsNotScrolled() case .error(_): refreshControl?.endRefreshing() case .loadedListItemViewModels(let viewModels): listViewModels = viewModels refreshControl?.endRefreshing() } } }
mit
499e2385fe871e2449df105b768d88ea
32.45
127
0.660189
5.424324
false
false
false
false
kthomas/KTSwiftExtensions
Source/ios/controllers/KTCameraViewController.swift
1
7944
// // KTCameraViewController.swift // KTSwiftExtensions // // Created by Kyle Thomas on 6/27/16. // Copyright © 2016 Kyle Thomas. All rights reserved. // import UIKit import AVFoundation public protocol KTCameraViewControllerDelegate: class { func outputModeForCameraViewController(_ viewController: KTCameraViewController) -> CameraOutputMode func cameraViewControllerCanceled(_ viewController: KTCameraViewController) func cameraViewControllerDidBeginAsyncStillImageCapture(_ viewController: KTCameraViewController) func cameraViewController(_ viewController: KTCameraViewController, didCaptureStillImage image: UIImage) func cameraViewController(_ viewController: KTCameraViewController, didSelectImageFromCameraRoll image: UIImage) func cameraViewController(_ KTCameraViewController: KTCameraViewController, didStartVideoCaptureAtURL fileURL: URL) func cameraViewController(_ KTCameraViewController: KTCameraViewController, didFinishVideoCaptureAtURL fileURL: URL) func cameraViewControllerShouldOutputFaceMetadata(_ viewController: KTCameraViewController) -> Bool func cameraViewControllerShouldRenderFacialRecognition(_ viewController: KTCameraViewController) -> Bool func cameraViewControllerDidOutputFaceMetadata(_ viewController: KTCameraViewController, metadataFaceObject: AVMetadataFaceObject) func cameraViewController(_ viewController: KTCameraViewController, didRecognizeText text: String!) } public class KTCameraViewController: UIViewController, KTCameraViewDelegate { weak var delegate: KTCameraViewControllerDelegate? var mode: ActiveDeviceCapturePosition = .back var outputMode: CameraOutputMode = .photo @IBOutlet public weak var backCameraView: KTCameraView! @IBOutlet public weak var frontCameraView: KTCameraView! @IBOutlet public weak var button: UIButton! private var activeCameraView: KTCameraView { switch mode { case .back: return backCameraView case .front: return frontCameraView } } var isRunning: Bool { if let backCameraView = backCameraView, backCameraView.isRunning { return true } if let frontCameraView = frontCameraView, frontCameraView.isRunning { return true } return false } override public func viewDidLoad() { super.viewDidLoad() let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(dismiss)) view.addGestureRecognizer(swipeGestureRecognizer) view.backgroundColor = UIColor.black.withAlphaComponent(0.5) setupCameraUI() setupBackCameraView() } func setupCameraUI() { guard let button = button else { return } view.bringSubview(toFront: button) button.addTarget(self, action: #selector(capture), for: .touchUpInside) let events = UIControl.Event.touchUpInside.union(.touchUpOutside).union(.touchCancel).union(.touchDragExit) button.addTarget(self, action: #selector(renderDefaultButtonAppearance), for: events) button.addTarget(self, action: #selector(renderTappedButtonAppearance), for: .touchDown) button.addBorder(5.0, color: UIColor.white) button.makeCircular() renderDefaultButtonAppearance() } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if !isRunning { setupBackCameraView() } button?.isEnabled = true DispatchQueue.main.async { self.button?.frame.origin.y = self.view.frame.size.height - 8.0 - self.button.frame.height } } deinit { activeCameraView.stopCapture() } @objc func capture() { button?.isEnabled = false activeCameraView.capture() } func setupBackCameraView() { mode = .back if let backCameraView = backCameraView { backCameraView.frame = view.frame backCameraView.delegate = self backCameraView.startBackCameraCapture() backCameraView.setCapturePreviewOrientationWithDeviceOrientation(UIDevice.current.orientation, size: view.frame.size) view.bringSubview(toFront: backCameraView) } if let button = button { view.bringSubview(toFront: button) } } func setupFrontCameraView() { mode = .front if let frontCameraView = frontCameraView { frontCameraView.frame = view.frame frontCameraView.delegate = self frontCameraView.startFrontCameraCapture() frontCameraView.setCapturePreviewOrientationWithDeviceOrientation(UIDevice.current.orientation, size: view.frame.size) view.bringSubview(toFront: frontCameraView) } if let button = button { view.bringSubview(toFront: button) } } func teardownBackCameraView() { backCameraView?.stopCapture() } func teardownFrontCameraView() { frontCameraView?.stopCapture() } @objc func dismiss(_ sender: UIBarButtonItem) { delegate?.cameraViewControllerCanceled(self) } @objc func renderDefaultButtonAppearance() { } @objc func renderTappedButtonAppearance() { } override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) DispatchQueue.main.async { self.button?.frame.origin.y = self.view.frame.height - 8.0 - self.button.frame.height self.activeCameraView.setCapturePreviewOrientationWithDeviceOrientation(UIDevice.current.orientation, size: size) } } // MARK: KTCameraViewDelegate public func outputModeForCameraView(_ cameraView: KTCameraView) -> CameraOutputMode { return delegate?.outputModeForCameraViewController(self) ?? outputMode } public func cameraViewCaptureSessionFailedToInitializeWithError(_ error: NSError) { delegate?.cameraViewControllerCanceled(self) } public func cameraViewBeganAsyncStillImageCapture(_ cameraView: KTCameraView) { delegate?.cameraViewControllerDidBeginAsyncStillImageCapture(self) } public func cameraView(_ cameraView: KTCameraView, didCaptureStillImage image: UIImage) { delegate?.cameraViewController(self, didCaptureStillImage: image) } public func cameraView(_ cameraView: KTCameraView, didStartVideoCaptureAtURL fileURL: URL) { delegate?.cameraViewController(self, didStartVideoCaptureAtURL: fileURL) } public func cameraView(_ cameraView: KTCameraView, didFinishVideoCaptureAtURL fileURL: URL) { delegate?.cameraViewController(self, didFinishVideoCaptureAtURL: fileURL) } public func cameraView(_ cameraView: KTCameraView, didMeasureAveragePower avgPower: Float, peakHold: Float, forAudioChannel channel: AVCaptureAudioChannel) { } public func cameraView(_ cameraView: KTCameraView, didOutputMetadataFaceObject metadataFaceObject: AVMetadataFaceObject) { delegate?.cameraViewControllerDidOutputFaceMetadata(self, metadataFaceObject: metadataFaceObject) } public func cameraViewShouldEstablishAudioSession(_ cameraView: KTCameraView) -> Bool { return false } public func cameraViewShouldEstablishVideoSession(_ cameraView: KTCameraView) -> Bool { return outputModeForCameraView(cameraView) == .videoSampleBuffer } public func cameraViewShouldOutputFaceMetadata(_ cameraView: KTCameraView) -> Bool { return delegate?.cameraViewControllerShouldOutputFaceMetadata(self) ?? false } public func cameraViewShouldRenderFacialRecognition(_ cameraView: KTCameraView) -> Bool { return delegate?.cameraViewControllerShouldRenderFacialRecognition(self) ?? false } }
mit
f956deb88e6c337589653eb1741cfcf5
34.146018
161
0.720635
5.309492
false
false
false
false
jlrodv/WWDC15-Scholarship
JoseLuis Rodriguez/JoseLuis Rodriguez/ViewController.swift
1
7956
// // ViewController.swift // JoseLuis Rodriguez // // Created by Jose Luis Rodriguez on 21/04/15. // Copyright (c) 2015 jlrodv. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let PROFILE_IMAGE_SIZE : CGFloat = 150.0; var profileImage: UIImageView! var welcomeLabel: UILabel! var welcomeInfoLabel: UILabel! var tableMenu: UITableView! let menuStrings:[String] = ["Jose Luis Rodriguez", "About me", "Education", "iOS Dev"] override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true self.createUI() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if(self.tableMenu == nil){ UIView.animateWithDuration(1.0, delay: 0.5, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveEaseInOut, animations: { self.profileImage.alpha = 1.0 self.welcomeLabel.alpha = 1.0 self.welcomeLabel.center = CGPointMake(self.welcomeLabel.center.x, self.profileImage.frame.origin.y/2) }, completion:{(finished: Bool) in if(finished){ UIView.animateWithDuration(0.3, animations: { self.welcomeInfoLabel.alpha = 1.0 }) } }) } } func createUI(){ self.profileImage = UIImageView(frame: CGRectMake(0.0, 0.0, PROFILE_IMAGE_SIZE, PROFILE_IMAGE_SIZE)) self.profileImage.image = UIImage(named: "Profile") self.profileImage.center = self.view.center; self.profileImage.layer.cornerRadius = profileImage.frame.size.height/2; self.profileImage.layer.borderWidth = 2; self.profileImage.layer.borderColor = UIColor.whiteColor().CGColor; self.profileImage.layer.masksToBounds = true; self.profileImage.alpha = 0.0; self.profileImage.userInteractionEnabled = true self.view.addSubview(self.profileImage) let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:Selector("profilePressed:")) self.profileImage.addGestureRecognizer(tapGesture) self.welcomeLabel = UILabel(frame: CGRectMake(0.0, 0.0, self.view.frame.size.width - 20, 80)) self.welcomeLabel.font = UIFont(name: "Avenir Medium", size: 23) self.welcomeLabel.textColor = UIColor.whiteColor() self.welcomeLabel.text = "Welcome to Jose Luis WWDC 15 Scholarship App" self.welcomeLabel.numberOfLines = 3; self.welcomeLabel.textAlignment = NSTextAlignment.Center self.welcomeLabel.sizeToFit() self.welcomeLabel.alpha = 0.0; self.welcomeLabel.center = CGPointMake(self.view.center.x, -self.welcomeLabel.frame.size.height) self.view.addSubview(self.welcomeLabel) self.welcomeInfoLabel = UILabel (frame: CGRectMake(0.0, 0.0, 200.0, 50.0)) self.welcomeInfoLabel.font = UIFont(name: "Avenir-LightOblique", size: 17) self.welcomeInfoLabel.textColor = UIColor.whiteColor() self.welcomeInfoLabel.text = "Tap Jose Luis face to start" self.welcomeInfoLabel.textAlignment = NSTextAlignment.Center self.welcomeInfoLabel.sizeToFit() self.welcomeInfoLabel.alpha = 0.0; self.welcomeInfoLabel.center = CGPointMake(self.view.center.x, self.profileImage.frame.origin.y+self.profileImage.frame.size.height + 8 + (self.welcomeInfoLabel.frame.size.height/2)) self.view.addSubview(self.welcomeInfoLabel) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func profilePressed(recognizer: UITapGestureRecognizer){ NSLog("Pressed" ) if(self.tableMenu == nil){ self.addTableToView() self.animateTransition() } } func addTableToView(){ self.tableMenu = UITableView(frame: CGRectMake(self.view.frame.origin.x + 10, self.view.frame.size.height, self.view.frame.size.width - 20, self.view.frame.size.height - PROFILE_IMAGE_SIZE - 8 - 20), style: UITableViewStyle.Plain) self.tableMenu.delegate = self self.tableMenu.dataSource = self self.tableMenu.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) self.tableMenu.backgroundView = nil self.tableMenu.layer.cornerRadius = 8; self.tableMenu.layer.masksToBounds = true; self.view.addSubview(self.tableMenu) } func animateTransition(){ UIView.animateWithDuration(0.7, animations: { self.welcomeInfoLabel.alpha = 0.0 self.welcomeLabel.frame = CGRectMake(self.welcomeLabel.frame.origin.x, self.welcomeLabel.frame.origin.y, 0, self.welcomeLabel.frame.size.height) self.profileImage.center = CGPointMake(self.profileImage.center.x, 20 + 8 + self.profileImage.frame.size.height/2) self.tableMenu.center = CGPointMake(self.view.center.x, self.PROFILE_IMAGE_SIZE + 16 + 20 + self.tableMenu.frame.size.height/2) }) } func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return menuStrings.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("reuseCell") as! UITableViewCell! if (cell == nil) { cell = UITableViewCell(style:.Default, reuseIdentifier: "reuseCell") cell.textLabel?.font = UIFont(name: "Avenir-Medium", size: 20) cell.backgroundView = nil cell.backgroundColor = UIColor.clearColor() } if(indexPath.row == 0){ cell.selectionStyle = UITableViewCellSelectionStyle.None; cell.accessoryType = UITableViewCellAccessoryType.None cell.textLabel?.textAlignment = NSTextAlignment.Center } else{ cell.selectionStyle = UITableViewCellSelectionStyle.Default; cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.textAlignment = NSTextAlignment.Left } cell.textLabel?.textColor = UIColor.whiteColor() cell.textLabel?.text = menuStrings[indexPath.row] return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if(indexPath.row==0){ return } tableView.deselectRowAtIndexPath(indexPath, animated: false) let segueIdentifier :String! = "about" self.performSegueWithIdentifier(segueIdentifier, sender: indexPath) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destinationController : AboutMeViewController = segue.destinationViewController as! AboutMeViewController let index : NSIndexPath = sender as! NSIndexPath destinationController.selectedMenu = index.row } }
mit
6be966f1e8ef0663b31cef1cc5f5975b
38.58209
238
0.639769
4.938547
false
false
false
false
mrlegowatch/RolePlayingCore
RolePlayingCore/RolePlayingCore/Currency/Money.swift
1
3502
// // Money.swift // RolePlayingCore // // Created by Brian Arnold on 2/11/17. // Copyright © 2017 Brian Arnold. All rights reserved. // import Foundation /// A measurement of currency. public typealias Money = Measurement<UnitCurrency> public extension String { /// Parses numbers with currency symbols into money. var parseMoney: Money? { var value: Double? var unit: UnitCurrency = .baseUnit() for currency in Currencies.allCurrencies { if let range = self.range(of: currency.symbol), range.upperBound == self.endIndex { value = Double(self[..<range.lowerBound].trimmingCharacters(in: .whitespaces))! unit = currency break } } // Try converting string to number. if value == nil { value = Double(self) } // Bail if the value could not be parsed. guard value != nil else { return nil } return Money(value: value!, unit: unit) } } public extension KeyedDecodingContainer { /// Decodes either a number or a string into Money. /// /// - throws `DecodingError.dataCorrupted` if the money could not be decoded. func decode(_ type: Money.Type, forKey key: K) throws -> Money { let money: Money? if let double = try? self.decode(Double.self, forKey: key) { money = Money(value: double, unit: .baseUnit()) } else { money = try self.decode(String.self, forKey: key).parseMoney } // Throw if we were unsuccessful parsing. guard money != nil else { let context = DecodingError.Context(codingPath: self.codingPath, debugDescription: "Missing string or number for Money value") throw DecodingError.dataCorrupted(context) } return money! } /// Decodes either a number or a string into Money, if present. /// /// - throws `DecodingError.dataCorrupted` if the money could not be decoded. func decodeIfPresent(_ type: Money.Type, forKey key: K) throws -> Money? { let money: Money? if let double = try? self.decode(Double.self, forKey: key) { money = Money(value: double, unit: .baseUnit()) } else if let string = try self.decodeIfPresent(String.self, forKey: key) { money = string.parseMoney } else { money = nil } return money } } extension MeasurementFormatter { /// The formatter requires a specialization that knows how to find UnitCurrency's baseUnit() and /// long name; otherwise, the default formatting (naturalScale) will return an empty string. public func string<UnitType: UnitCurrency>(from measurement: Measurement<UnitType>) -> String { let unitToUse = unitOptions == .naturalScale ? UnitCurrency.baseUnit() : measurement.unit let value = unitOptions == .naturalScale ? measurement.converted(to: UnitCurrency.baseUnit() as! UnitType).value : measurement.value let unitsString = unitStyle == .short || unitStyle == .medium ? unitToUse.symbol : value == 1.0 ? unitToUse.name : unitToUse.plural let valueString = numberFormatter.string(from: NSNumber(value: value))! let formatString = unitStyle == .short ? "%@%@" : "%@ %@" return String(format: formatString, valueString, unitsString!) } }
mit
03b8583a51eea6d4db5df9bf8fba992c
34.363636
140
0.609826
4.699329
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/common/Constants.swift
1
7013
// // Constants.swift // light_guide // 全局常数类 // Created by Chance on 15/8/29. // Copyright (c) 2015年 wetasty. All rights reserved. // import Foundation import UIKit ///MARK: - 结构体 struct CHWalletsKeys { static let prefix = "" //前续头 /** 钱包设置类 **/ static let UserNickname = prefix + "btc_user_nickname" //用户昵称 static let BTCAddress = prefix + "btc_address" //用户地址 static let BTCRedeemScript = prefix + "btc_redeem_script" //用户赎回脚本 static let BTCSecretPhrase = prefix + "btc_secret_phrase" //用户恢复密语 static let BTCWalletSeed = prefix + "btc_wallet_seed" //钱包种子 static let BTCPrivateKey = prefix + "btc_private_key" //用户私钥 static let BTCPubkey = prefix + "btc_pubkey" //用户公钥 static let BTCExtendedPrivateKey = prefix + "btc_extended_private_key" //用户私钥 static let BTCExtendedPubkey = prefix + "btc_extended_pubkey" //用户公钥 static let BTCWalletPassword = prefix + "btc_wallet_password" //用户密码 static let BTCWalletAccountsCount = prefix + "btc_wallet_account_count" //钱包账户个数 static let BTCWalletAccountsJSON = prefix + "btc_wallet_accounts_json" //钱包账户地址的json数组 /** 系统设置类 **/ static let EnableTouchID = prefix + "enable_touchid" //是否开启指纹验证 static let SelectedAccount = prefix + "selected_account" //选择的账户地址 static let SelectedBlockchainNode = prefix + "selected_blockchain_node" //选择的云节点 static let SelectedBlockchainNetwork = prefix + "selected_blockchain_network" //选择的网络 static let EnableICloud = prefix + "enable_icloud" //是否开启icloud自动同步 } /// 系统版本号 let kIOSVersion : NSString? = UIDevice.current.systemVersion as NSString? /** * 确认是否 */ public enum Confirm: String { case NO = "0" case YES = "1" } /** API返回结果代码 */ public enum ApiResultCode: String { /** * 操作成功(success) */ case Success = "1000" /** * 需求继续签名 */ case NeedOtherSignature = "1101" /** * 一般错误提示(Error Tips) */ case ErrorTips = "1001" /** * 内部错误(Internal Error) */ case InternalError = "1002" /** * 应用授权失败(Auth No Pass) */ case AuthNoPass = "1003" /** * token失效(Token No Pass) */ case TokenNoPass = "1004" /** * 接口访问失败(APIResponseError) */ case APIResponseError = "90000" } /** 货币种类 - BTC: 比特币 - LTC: 莱特币 - CNY: 人民币 */ public enum CurrencyType: String { /** * 比特币 */ case BTC = "BTC" /** * 莱特币 */ case LTC = "LTC" /** * 人民币 */ case CNY = "CNY" /** * 美元 */ case USD = "USD" /// 货币标识 var symbol: String { var s = "" switch self { case .CNY: s = "¥" case .USD: s = "$" case .BTC: s = "฿" case .LTC: s = "Ł" } return s } /** 返回类型名称 - returns: 返回类型名称 */ func coinName() -> String { switch self { case .BTC: return NSLocalizedString("BTC", comment: "比特币") case .LTC: return NSLocalizedString("LTC", comment: "比特币") case .CNY: return NSLocalizedString("CNY", comment: "人民币") case .USD: return NSLocalizedString("USD", comment: "美元") } } /// 地址前缀 var addressPrefix: String { switch self { case .BTC: return "bitcoin:" case .LTC: return "litecoin:" case .CNY: return "" case .USD: return "" } } } /** 多签脚本 - PrivateKey: 私钥 - PublicKey: 公钥 - RedeemScript: 多重签名赎回脚本 */ public enum ExportKeyType: String { case PrivateKey = "1" case PublicKey = "2" case RedeemScript = "3" } /** 账户类型 - Normal: 单签HD - MultiSig: 多签账户 */ public enum CHAccountType: String { case normal = "1" case multiSig = "2" /// 账户类型名 var typeName: String { switch self { case .normal: return "Normal".localized() case .multiSig: return "Multi-Sig".localized() } } /// 卡片背景色 var cardBGColor: UIColor { switch self { case .normal: return UIColor(hex: 0x1E74CA) case .multiSig: return UIColor(hex: 0x7956B6) } } } /** 传输类型 - Request: 发送 - Response: 返回 */ public enum WSDataType: String { case Request = "1" //发送 case Response = "2" //返回 } /** * 语言 */ enum Language { case english case chinese_Simple //短字 var shortName: String { switch self { case .english: return "en" case .chinese_Simple: return "cn" } } /// 语言类型 var langType: String { switch self { case .english: return "2" case .chinese_Simple: return "1" } } } /** 故事板资源 - main: - welcome: - wallet: - setting: */ enum StoryBoard { case main case welcome case wallet case setting case account /// board实体 var board: UIStoryboard { switch self { case .main: return UIStoryboard.init(name: "Main", bundle: nil) case .welcome: return UIStoryboard.init(name: "Welcome", bundle: nil) case .wallet: return UIStoryboard.init(name: "Wallet", bundle: nil) case .setting: return UIStoryboard.init(name: "Setting", bundle: nil) case .account: return UIStoryboard.init(name: "Account", bundle: nil) } } /// 初始界面 /// /// - Parameter type: 类 func initView<T : UIViewController>(type: T.Type) -> T? { let fullName: String = String(describing: type) let vc = self.board.instantiateViewController(withIdentifier: fullName) return vc as? T } /// 初始界面 /// /// - Parameter name: id名字 func initView(name: String) -> UIViewController? { let vc = self.board.instantiateViewController(withIdentifier: name) return vc } }
mit
e7561929e3a052fd6b9bb464e706b2f8
19.50641
100
0.517505
3.702546
false
false
false
false
rzrasel/iOS-Swift-2016-01
SwiftDropdownSelectBoxOne/SwiftDropdownSelectBoxOne/DropDownSelectBox/DropDownSelectBoxCell.swift
2
1726
// // DropDownSelectBoxCell.swift // SwiftDropdownSelectBoxOne // // Created by NextDot on 2/2/16. // Copyright © 2016 RzRasel. All rights reserved. // import Foundation import UIKit internal final class DropDownSelectBoxCell: UITableViewCell { //MARK: - Properties static let Nib = UINib(nibName: "DropDownSelectBoxCell", bundle: NSBundle(forClass: DropDownSelectBoxCell.self)) //UI @IBOutlet weak var optionLabel: UILabel! var selectedBackgroundColor: UIColor? } //MARK: - UI internal extension DropDownSelectBoxCell { override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clearColor() } override var selected: Bool { willSet { setSelected(newValue, animated: false) } } override var highlighted: Bool { willSet { setSelected(newValue, animated: false) } } override func setHighlighted(highlighted: Bool, animated: Bool) { setSelected(highlighted, animated: animated) } override func setSelected(selected: Bool, animated: Bool) { let executeSelection: () -> Void = { [unowned self] in if let selectedBackgroundColor = self.selectedBackgroundColor { if selected { self.backgroundColor = selectedBackgroundColor } else { self.backgroundColor = UIColor.clearColor() } } } if animated { UIView.animateWithDuration(0.3, animations: { executeSelection() }) } else { executeSelection() } } }
apache-2.0
c55a5cf8444df8606000a19797721944
24.014493
116
0.587246
5.149254
false
false
false
false
rzrasel/iOS-Swift-2016-01
SwiftLocalNotificationTwo/SwiftLocalNotificationTwo/AppDelegate.swift
2
8509
// // AppDelegate.swift // SwiftLocalNotificationTwo // // Created by NextDot on 1/31/16. // Copyright © 2016 RzRasel. 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. // Register for notification: This will prompt for the user's consent to receive notifications from this app. /*let notificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Sound, UIUserNotificationType.Badge], categories: nil) //--*NOTE* // Registering UIUserNotificationSettings more than once results in previous settings being overwritten. UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)*/ let notificationActionOk: UIMutableUserNotificationAction = UIMutableUserNotificationAction() notificationActionOk.identifier = "ACCEPT_IDENTIFIER" notificationActionOk.title = "Ok" notificationActionOk.destructive = false notificationActionOk.authenticationRequired = false notificationActionOk.activationMode = UIUserNotificationActivationMode.Background let notificationActionCancel: UIMutableUserNotificationAction = UIMutableUserNotificationAction() notificationActionCancel.identifier = "NOT_NOW_IDENTIFIER" notificationActionCancel.title = "Not Now" notificationActionCancel.destructive = true notificationActionCancel.authenticationRequired = false notificationActionCancel.activationMode = UIUserNotificationActivationMode.Background let notificationCategory: UIMutableUserNotificationCategory = UIMutableUserNotificationCategory() notificationCategory.identifier = "INVITE_CATEGORY" notificationCategory.setActions([notificationActionOk,notificationActionCancel], forContext: UIUserNotificationActionContext.Default) notificationCategory.setActions([notificationActionOk,notificationActionCancel], forContext: UIUserNotificationActionContext.Minimal) /*application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: NSSet(array:[notificationCategory]) ))*/ application.registerUserNotificationSettings( UIUserNotificationSettings( forTypes: [.Alert, .Badge, .Sound], categories: (NSSet(array: [notificationCategory])) as? Set<UIUserNotificationCategory>)) 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 "rz.rasel.SwiftLocalNotificationTwo" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() 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("SwiftLocalNotificationTwo", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns 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 let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // 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 as NSError let wrappedError = 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 \(wrappedError), \(wrappedError.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 var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // 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. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
4cbf15870c246f41354aebb8aab4be7c
58.083333
291
0.733075
6.19214
false
false
false
false
victorchee/QRCode
QRCode/QRCode/GeneratorViewController.swift
1
4039
// // GeneratorViewController.swift // QRCode // // Created by qihaijun on 11/3/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit import CoreImage class GeneratorViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var button: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textField.text = textField.placeholder if let text = textField.text { let image = generateQRCode(text) button.setBackgroundImage(image, forState: .Normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tap(sender: UITapGestureRecognizer) { textField.resignFirstResponder() } @IBAction func buttonTapped(sender: UIButton) { guard let image = sender.backgroundImageForState(.Normal) else { return } guard let text = readQRCode(image) else { return } let alert = UIAlertController(title: "Read QRCode From Image", message: text, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default) { (action) -> Void in } alert.addAction(action) presentViewController(alert, animated: true, completion: nil) } @IBAction func generate(sender: UIButton) { if let text = textField.text { let image = generateQRCode(text) button.setBackgroundImage(image, forState: .Normal) } else { button.setBackgroundImage(nil, forState: .Normal) } } private func generateQRCode(text: String) -> UIImage? { var filterName: String! switch segmentedControl.selectedSegmentIndex { case 1 : filterName = "CIAztecCodeGenerator" case 2 : filterName = "CICode128BarcodeGenerator" default : filterName = "CIQRCodeGenerator" } guard let filter = CIFilter(name: filterName) else { return nil } filter.setDefaults() guard let data = text.dataUsingEncoding(NSUTF8StringEncoding) else { return nil } filter.setValue(data, forKey: "inputMessage") guard let outputImage = filter.outputImage else { return nil } let context = CIContext() let cgImage = context.createCGImage(outputImage, fromRect: outputImage.extent) let image = UIImage(CGImage: cgImage, scale: 1.0, orientation: UIImageOrientation.Up) let resizedImage = resizeImage(image, quality: .None, rate: 5.0) return resizedImage } private func resizeImage(image: UIImage, quality: CGInterpolationQuality, rate: CGFloat) -> UIImage { let size = CGSize(width: image.size.width * rate, height: image.size.height * rate) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() CGContextSetInterpolationQuality(context, quality) image.drawInRect(CGRect(origin: CGPoint.zero, size: size)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return resizedImage } private func readQRCode(image: UIImage) -> String? { let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh]) guard let ciImage = CIImage(image: image) else { return nil } let features = detector.featuresInImage(ciImage) guard let feature = features.first as? CIQRCodeFeature else { return nil } return feature.messageString } }
mit
73ef6c7c451a1acdf9ee52abc32997ff
32.65
133
0.629272
5.292267
false
false
false
false
ming1016/smck
smck/Lib/RxSwift/Filter.swift
47
1723
// // Filter.swift // RxSwift // // Created by Krunoslav Zaher on 2/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // final class FilterSink<O : ObserverType>: Sink<O>, ObserverType { typealias Predicate = (Element) throws -> Bool typealias Element = O.E private let _predicate: Predicate init(predicate: @escaping Predicate, observer: O, cancel: Cancelable) { _predicate = predicate super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let satisfies = try _predicate(value) if satisfies { forwardOn(.next(value)) } } catch let e { forwardOn(.error(e)) dispose() } case .completed, .error: forwardOn(event) dispose() } } } final class Filter<Element> : Producer<Element> { typealias Predicate = (Element) throws -> Bool private let _source: Observable<Element> private let _predicate: Predicate init(source: Observable<Element>, predicate: @escaping Predicate) { _source = source _predicate = predicate } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = FilterSink(predicate: _predicate, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
a4b211ff2249d592caa7c2b1e7676ddc
29.75
144
0.562137
4.770083
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/EventDetailComponent/Calendar/EventKit/EventKitEventStore.swift
1
4989
import EventKit import EventKitUI import UIKit public class EventKitEventStore: NSObject, EventStore { private let window: UIWindow private let eventStore: EKEventStore private var eventStoreChangedSubscription: NSObjectProtocol? public init(window: UIWindow) { self.window = window self.eventStore = EKEventStore() super.init() eventStoreChangedSubscription = NotificationCenter.default.addObserver( forName: .EKEventStoreChanged, object: eventStore, queue: .main, using: { [weak self] _ in if let strongSelf = self { strongSelf.delegate?.eventStoreChanged(strongSelf) } }) } public var delegate: EventStoreDelegate? public func editEvent(definition event: EventStoreEventDefinition, sender: Any?) { attemptCalendarStoreEdit { [weak self, eventStore] in let calendarEvent = EKEvent(eventStore: eventStore) calendarEvent.title = event.title calendarEvent.location = event.room calendarEvent.startDate = event.startDate calendarEvent.endDate = event.endDate calendarEvent.url = event.deeplinkURL calendarEvent.notes = event.shortDescription calendarEvent.addAlarm(EKAlarm(relativeOffset: -1800)) let editingViewController = EKEventEditViewController() editingViewController.editViewDelegate = self editingViewController.eventStore = eventStore editingViewController.event = calendarEvent switch sender { case let sender as UIBarButtonItem: editingViewController.popoverPresentationController?.barButtonItem = sender case let sender as UIView: editingViewController.popoverPresentationController?.sourceView = sender editingViewController.popoverPresentationController?.sourceRect = sender.bounds default: break } self?.window.rootViewController?.present(editingViewController, animated: true) } } public func removeEvent(identifiedBy eventDefinition: EventStoreEventDefinition) { attemptCalendarStoreEdit { [weak self] in if let event = self?.storeEvent(for: eventDefinition) { do { try self?.eventStore.remove(event, span: .thisEvent) } catch { print("Failed to remove event \(eventDefinition) from calendar. Error=\(error)") } } } } public func contains(eventDefinition: EventStoreEventDefinition) -> Bool { return storeEvent(for: eventDefinition) != nil } private func storeEvent(for eventDefinition: EventStoreEventDefinition) -> EKEvent? { let predicate = eventStore.predicateForEvents( withStart: eventDefinition.startDate, end: eventDefinition.endDate, calendars: nil ) let events = eventStore.events(matching: predicate) return events.first(where: { $0.url == eventDefinition.deeplinkURL }) } private func attemptCalendarStoreEdit(edit: @escaping () -> Void) { if EKEventStore.authorizationStatus(for: .event) == .authorized { edit() } else { requestCalendarEditingAuthorisation(success: edit) } } private func requestCalendarEditingAuthorisation(success: @escaping () -> Void) { eventStore.requestAccess(to: .event) { [weak self] granted, _ in DispatchQueue.main.async { if granted { success() } else { self?.presentNotAuthorizedAlert() } } } } private func presentNotAuthorizedAlert() { let alert = UIAlertController( title: "Not Authorised", message: "Grant Calendar access to Eurofurence in Settings to add events to Calendar.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { _ in if let settingsURL = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(settingsURL) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel)) window.rootViewController?.present(alert, animated: true) } } extension EventKitEventStore: EKEventEditViewDelegate { public func eventEditViewController( _ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction ) { controller.presentingViewController?.dismiss(animated: true) } }
mit
4e287bf2dbbafccdbfb05884ecf19cbc
35.416058
100
0.607136
5.794425
false
false
false
false
soleiltw/ios-swift-basic
Swift-Advance/OptionalChaining-lite.playground/Contents.swift
1
1233
//: Playground - noun: a place where people can play class Person { var residence : Residence? } class Residence { var numberOfRooms = 1 var address: Address? } class Address { var street : String? func printStreetName() -> String? { if street != nil { return "Current street name is: \(street!)" } else { return nil } } } let john = Person() print("John residence info: \(john.residence?.numberOfRooms)") func printResidenceInfo(person: Person) { if let roomCount = person.residence?.numberOfRooms { print("Current person residence info: \(roomCount)") } else { print("Unable to retrieve any numbers of room.") } } printResidenceInfo(person: john) let residence = Residence() residence.numberOfRooms = 3 john.residence = residence printResidenceInfo(person: john) let howard = Person() let howardResidence = Residence() let howardLivingAddress = Address() howardLivingAddress.street = "英專路" howardResidence.address = howardLivingAddress howard.residence = howardResidence if let address = howard.residence?.address { print("Howard \(address.printStreetName()!)") } else { print("Unable to find address.") }
mit
f65eabddd47fea173833275fb259ead6
21.722222
62
0.676447
3.932692
false
false
false
false
CatchChat/Yep
Yep/ViewControllers/TabBar/YepTabBarController.swift
1
8862
// // YepTabBarController.swift // Yep // // Created by kevinzhow on 15/3/28. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit import Proposer final class YepTabBarController: UITabBarController { enum Tab: Int { case Conversations case Contacts case Feeds case Discover case Profile var title: String { switch self { case .Conversations: return String.trans_titleChats case .Contacts: return String.trans_titleContacts case .Feeds: return NSLocalizedString("Feeds", comment: "") case .Discover: return NSLocalizedString("Discover", comment: "") case .Profile: return NSLocalizedString("Profile", comment: "") } } } private var previousTab: Tab = .Conversations var tab: Tab? { didSet { if let tab = tab { self.selectedIndex = tab.rawValue } } } private var checkDoubleTapOnFeedsTimer: NSTimer? private var hasFirstTapOnFeedsWhenItIsAtTop = false { willSet { checkDoubleTapOnFeedsTimer?.invalidate() if newValue { let timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(YepTabBarController.checkDoubleTapOnFeeds(_:)), userInfo: nil, repeats: false) checkDoubleTapOnFeedsTimer = timer } } } @objc private func checkDoubleTapOnFeeds(timer: NSTimer) { hasFirstTapOnFeedsWhenItIsAtTop = false } private struct Listener { static let lauchStyle = "YepTabBarController.lauchStyle" } private let tabBarItemTextEnabledListenerName = "YepTabBarController.tabBarItemTextEnabled" deinit { checkDoubleTapOnFeedsTimer?.invalidate() if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.lauchStyle.removeListenerWithName(Listener.lauchStyle) } YepUserDefaults.tabBarItemTextEnabled.removeListenerWithName(tabBarItemTextEnabledListenerName) println("deinit YepTabBar") } override func viewDidLoad() { super.viewDidLoad() delegate = self view.backgroundColor = UIColor.whiteColor() YepUserDefaults.tabBarItemTextEnabled.bindAndFireListener(tabBarItemTextEnabledListenerName) { [weak self] _ in self?.adjustTabBarItems() } // 处理启动切换 if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.lauchStyle.bindListener(Listener.lauchStyle) { [weak self] style in if style == .Message { self?.selectedIndex = 0 } } } delay(3) { if PrivateResource.Location(.WhenInUse).isAuthorized { YepLocationService.turnOn() } } } func adjustTabBarItems() { let noNeedTitle: Bool if let tabBarItemTextEnabled = YepUserDefaults.tabBarItemTextEnabled.value { noNeedTitle = !tabBarItemTextEnabled } else { noNeedTitle = YepUserDefaults.appLaunchCount.value > YepUserDefaults.appLaunchCountThresholdForTabBarItemTextEnabled } if noNeedTitle { // 将 UITabBarItem 的 image 下移一些,也不显示 title 了 if let items = tabBar.items { for item in items { item.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0) item.title = nil } } } else { // Set Titles if let items = tabBar.items { for i in 0..<items.count { let item = items[i] item.imageInsets = UIEdgeInsetsZero item.title = Tab(rawValue: i)?.title } } } } var isTabBarVisible: Bool { return self.tabBar.frame.origin.y < CGRectGetMaxY(view.frame) } func setTabBarHidden(hidden: Bool, animated: Bool) { guard isTabBarVisible == hidden else { return } let height = self.tabBar.frame.size.height let offsetY = (hidden ? height : -height) let duration = (animated ? 0.25 : 0.0) UIView.animateWithDuration(duration, animations: { [weak self] in guard let strongSelf = self else { return } let frame = strongSelf.tabBar.frame strongSelf.tabBar.frame = CGRectOffset(frame, 0, offsetY) }, completion: nil) } } // MARK: - UITabBarControllerDelegate extension YepTabBarController: UITabBarControllerDelegate { func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { guard let tab = Tab(rawValue: selectedIndex), let nvc = viewController as? UINavigationController else { return false } if tab != previousTab { return true } if case .Feeds = tab { if let vc = nvc.topViewController as? FeedsViewController { guard let feedsTableView = vc.feedsTableView else { return true } if feedsTableView.yep_isAtTop { if !hasFirstTapOnFeedsWhenItIsAtTop { hasFirstTapOnFeedsWhenItIsAtTop = true return false } } } } return true } func tryScrollsToTopOfFeedsViewController(vc: FeedsViewController) { guard let scrollView = vc.feedsTableView else { return } if !scrollView.yep_isAtTop { scrollView.yep_scrollsToTop() } else { if !vc.feeds.isEmpty && !vc.pullToRefreshView.isRefreshing { scrollView.setContentOffset(CGPoint(x: 0, y: -150), animated: true) hasFirstTapOnFeedsWhenItIsAtTop = false } } } func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) { guard let tab = Tab(rawValue: selectedIndex), let nvc = viewController as? UINavigationController else { return } if tab != .Contacts { NSNotificationCenter.defaultCenter().postNotificationName(YepConfig.Notification.switchedToOthersFromContactsTab, object: nil) } // 不相等才继续,确保第一次 tap 不做事 if tab != previousTab { previousTab = tab return } switch tab { case .Conversations: if let vc = nvc.topViewController as? ConversationsViewController { guard let scrollView = vc.conversationsTableView else { break } if !scrollView.yep_isAtTop { scrollView.yep_scrollsToTop() } } case .Contacts: if let vc = nvc.topViewController as? ContactsViewController { guard let scrollView = vc.contactsTableView else { break } if !scrollView.yep_isAtTop { scrollView.yep_scrollsToTop() } } case .Feeds: if let vc = nvc.topViewController as? FeedsViewController { tryScrollsToTopOfFeedsViewController(vc) } case .Discover: if let vc = nvc.topViewController as? DiscoverContainerViewController { var _scrollView: UIScrollView? if let mvc = vc.viewControllers?.first as? MeetGeniusViewController { _scrollView = mvc.tableView } else if let dvc = vc.viewControllers?.first as? DiscoverViewController { _scrollView = dvc.discoveredUsersCollectionView } guard let scrollView = _scrollView else { break } if !scrollView.yep_isAtTop { scrollView.yep_scrollsToTop() } } case .Profile: if let vc = nvc.topViewController as? ProfileViewController { guard let scrollView = vc.profileCollectionView else { break } if !scrollView.yep_isAtTop { scrollView.yep_scrollsToTop() } } } } }
mit
78cdde5c7449f2d6633059dd3ab2f1a1
29.219931
184
0.561519
5.527341
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/BaseTest/BaseTest/Codable/RayTestCodableViewController.swift
1
2292
// // RayTestCodableViewController.swift // BaseTest // // Created by 邬勇鹏 on 2018/5/29. // Copyright © 2018年 raymond. All rights reserved. // import UIKit class RayTestCodableViewController: UIViewController { private lazy var gesView: UIView = { let v = UIView(frame: CGRect(x: 50, y: 100, width: 100, height: 100)) v.backgroundColor = .purple let gesture_1 = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction_1(gesture:))) v.addGestureRecognizer(gesture_1) let gesture_2 = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction_2(gesture:))) v.addGestureRecognizer(gesture_2) return v }() override func viewDidLoad() { super.viewDidLoad() self.title = "Codable test" self.view.addSubview(gesView) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("---touch begin") // YYSummary.dictArrayJson() testCodableSummary() // testMirror() } //MARK: testing private func testCodableSummary() { CodableSummary.testSingleObjc() // CodableSummary.customKey() // CodableSummary.testArrayObjc() // CodableSummary.testClassObj() // CodableSummary.testOutOfProperty() // RayCodeSummary.testContainerObject() // RayCodableInheritSummary.testInherit() } private func testMirror() { RayMirrorSummary.testMirror() } } extension RayTestCodableViewController { fileprivate func add<T: Equatable>(a: T, b: T) -> Bool { return a == b } fileprivate func test1<T: Equatable>() -> T? { let a: Int = 2 return a as? T } @discardableResult fileprivate func convert<T: Codable>(response: [String:Any]?) -> T? { return nil } } // MARK: - Gesture test extension RayTestCodableViewController { @objc private func tapGestureAction_1(gesture: UITapGestureRecognizer) { print("----gesture1") } @objc private func tapGestureAction_2(gesture: UITapGestureRecognizer) { print("----gesture2") } }
apache-2.0
6e7072c885ad8bc9627c2159a273d755
27.185185
109
0.604906
4.485265
false
true
false
false
andersonlucasg3/Swift.Json
Sources/Utils/CasePatternConverter.swift
1
4227
// // CasePatternConverter.swift // SwiftJson // // Created by Jorge Luis on 31/12/17. // import Foundation /** * CasePatternConversionBlock is the block which is called just before the convert(_:) method return the key converted to the JsonConfig. * - Parameter key: the field name String, provenient from a json file or an object * - Parameter field: the key converted to the designated pattern by the converToField(_:) method. */ public typealias CasePatternConversionBlock = ((_ key: String, _ field: String) -> String) /// Protocol used by JsonConfig to automatically convert the naming conventions on swift object's properties name to match the json's properties name, and vice versa public protocol CasePatternConverter: class { ///Called only in the convert(_:) method, just after the key field become converted by the converToField method, and then its return is used as the real converted value. var complementaryConversion: CasePatternConversionBlock? {get set} ///Convert the key to designated case pattern without calling the complementary conversion method func convertToField(_ key: String) -> String } public extension CasePatternConverter { ///Convert the key to designated case pattern calling the complementary conversion method public func convert(_ key: String) -> String { let field = self.convertToField(key) return self.complementaryConversion?(key,field) ?? field } } /** * Default implementation to convert any swift's object field name to camelCase convention (all words Capitalized, except for the first, without any separator character) * Example: "sadistic_sociopath" and "full_fake_name" will become, respectively: "sadisticSociopath" and "fullFakeName" */ open class CamelCaseConverter: CasePatternConverter { private static let regex = try? NSRegularExpression.init(pattern: "[^a-z^A-Z]+(.)", options: .useUnixLineSeparators) public var complementaryConversion: CasePatternConversionBlock? public init(_ block: CasePatternConversionBlock? = nil) { self.complementaryConversion = block } public func convertToField(_ key: String) -> String { var nsTarget = NSString(string:key) CamelCaseConverter.regex?.matches(in: key, options: .reportCompletion, range: NSMakeRange(0, key.count)).reversed().forEach({ func range(for result: NSTextCheckingResult, at index: Int) -> NSRange { #if swift(>=4.0) return result.range(at: index) #else return result.rangeAt(index) #endif } nsTarget = NSString(string:nsTarget.replacingCharacters(in: $0.range, with: nsTarget.substring(with: range(for: $0, at: 1)).uppercased())) }) return nsTarget.replacingCharacters(in: NSMakeRange(0, 1), with: nsTarget.substring(with: NSMakeRange(0, 1)).lowercased()) } } /** * Default implementation to convert any swift's object field name to snake_case convention (all letter lowercase, separated by underscore) * Example: "sadisticSociopath" and "fullFakeName" will become, respectively: "sadistic_sociopath" and "full_fake_name" */ open class SnakeCaseConverter: CasePatternConverter { private static let firstStepPattern = try? NSRegularExpression.init(pattern: "[- _]+(.)", options: .useUnixLineSeparators) private static let secondStepPattern = try? NSRegularExpression.init(pattern: "([^-^_^ ])([A-Z])", options: .useUnixLineSeparators) public var complementaryConversion: CasePatternConversionBlock? public init(_ block: CasePatternConversionBlock? = nil) { self.complementaryConversion = block } public func convertToField(_ key: String) -> String { let nsTarget = NSMutableString(string:key) SnakeCaseConverter.firstStepPattern?.replaceMatches(in: nsTarget, options: .reportCompletion, range: NSMakeRange(0, nsTarget.length), withTemplate: "_$1") SnakeCaseConverter.secondStepPattern?.replaceMatches(in: nsTarget, options: .reportCompletion, range: NSMakeRange(0, nsTarget.length), withTemplate: "$1_$2") return (nsTarget as String).lowercased() } }
mit
a6253c366424e5e630a749047b9924e2
49.321429
173
0.711616
4.458861
false
false
false
false
ciiqr/contakt
contakt/contakt/OrderedDictionaryIndex.swift
1
1642
// // OrderedDictionaryIndex.swift // contakt // // Created by William Villeneuve on 2016-01-19. // Copyright © 2016 William Villeneuve. All rights reserved. // import Foundation func ==(lhs: OrderedDictionaryIndex, rhs: OrderedDictionaryIndex) -> Bool { return lhs.index == rhs.index } // NOTE: This is a utility class for OrderedDictionary, this is necessary because if we used Int directly as the Index // type then we wouldn't be able to have a subscript overload for returning the TValue when the TKey is Int struct OrderedDictionaryIndex : ForwardIndexType, RandomAccessIndexType { let index: Int init(_ index: Int) { self.index = index } // MARK: - Protocols // MARK: ForwardIndexType func successor() -> OrderedDictionaryIndex { return OrderedDictionaryIndex(self.index.successor()) } // MARK: RandomAccessIndexType @warn_unused_result func distanceTo(other: OrderedDictionaryIndex) -> OrderedDictionaryIndex.Distance { return self.index.distanceTo(other.index) } @warn_unused_result func advancedBy(n: OrderedDictionaryIndex.Distance) -> OrderedDictionaryIndex { return OrderedDictionaryIndex(self.index.advancedBy(n)) } @warn_unused_result func advancedBy(n: OrderedDictionaryIndex.Distance, limit: OrderedDictionaryIndex) -> OrderedDictionaryIndex { return OrderedDictionaryIndex(self.index.advancedBy(n, limit: limit.index)) } // MARK: BidirectionalIndexType @warn_unused_result func predecessor() -> OrderedDictionaryIndex { return OrderedDictionaryIndex(self.index - 1) } }
unlicense
7cefc3d6cfb8861c04564a25262231c9
31.84
118
0.716027
4.622535
false
false
false
false
apple/swift
test/DebugInfo/closure.swift
36
793
// RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s func markUsed<T>(_ t: T) {} func foldl1<T>(_ list: [T], _ function: (_ a: T, _ b: T) -> T) -> T { assert(list.count > 1) var accumulator = list[0] for i in 1 ..< list.count { accumulator = function(accumulator, list[i]) } return accumulator } var a = [Int64](repeating: 0, count: 10) for i in 0..<10 { a[i] = Int64(i) } // A closure is not an artificial function (the last i32 0). // CHECK: !DISubprogram({{.*}}linkageName: "$s7closures5Int64VAC_ACtXEfU_",{{.*}} line: 20,{{.*}} scopeLine: 20, // CHECK: !DILocalVariable(name: "$0", arg: 1{{.*}} line: [[@LINE+2]], // CHECK: !DILocalVariable(name: "$1", arg: 2{{.*}} line: [[@LINE+1]], var sum:Int64 = foldl1(a, { $0 + $1 }) markUsed(sum)
apache-2.0
af09ffd09f7db0643add8e9341ade4ee
36.761905
112
0.572509
2.947955
false
false
false
false
tkremenek/swift
test/Concurrency/Runtime/async_task_locals_prevent_illegal_use.swift
1
1559
// RUN: %target-fail-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) 2>&1 | %FileCheck %s // // // TODO: could not figure out how to use 'not --crash' it never is used with target-run-simple-swift // This test is intended to *crash*, so we're using target-fail-simple-swift // which expects the exit code of the program to be non-zero; // We then check stderr for the expected error message using filecheck as usual. // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime @available(SwiftStdlib 5.5, *) enum TL { @TaskLocal static var number: Int = 2 } // ==== ------------------------------------------------------------------------ @available(SwiftStdlib 5.5, *) func bindAroundGroupSpawn() async { await TL.$number.withValue(1111) { // ok await withTaskGroup(of: Int.self) { group in // CHECK: error: task-local: detected illegal task-local value binding at {{.*}}illegal_use.swift:[[# @LINE + 1]] TL.$number.withValue(2222) { // bad! print("Survived, inside withValue!") // CHECK-NOT: Survived, inside withValue! group.spawn { 0 // don't actually perform the read, it would be unsafe. } } print("Survived the illegal call!") // CHECK-NOT: Survived the illegal call! } } } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await bindAroundGroupSpawn() } }
apache-2.0
c02417e24dad3a63135aad4166331a36
34.431818
179
0.650417
3.8975
false
false
false
false
dn-m/Collections
CollectionsTests/MutableTreeProtocolTests.swift
1
10377
// // MutableTreeProtocolTests.swift // Collections // // Created by James Bean on 1/16/17. // // import XCTest import Collections final class Node: MutableTreeProtocol { weak var parent: Node? var children: [Node] = [] } class MutableTreeProtocolTests: XCTestCase { func testAddChild() { let parent = Node() let child = Node() parent.addChild(child) XCTAssertEqual(parent.children.count, 1) XCTAssert(child.parent! === parent) } func testAddChildrenVariadic() { let parent = Node() parent.addChildren([Node(), Node(), Node()]) XCTAssertEqual(parent.children.count, 3) } func testAddChildrenArray() { let parent = Node() parent.addChildren([Node(), Node(), Node()]) XCTAssertEqual(parent.children.count, 3) } func testInsertChildAtIndexThrows() { let parent = Node() let child = Node() do { try parent.insertChild(child, at: 1) XCTFail() } catch { } } func testInsertChildAtIndexValidEmpty() { let parent = Node() do { try parent.insertChild(Node(), at: 0) } catch { XCTFail() } } func testInsertChildAtIndexValidNotEmpty() { let parent = Node() parent.addChild(Node()) do { try parent.insertChild(Node(), at: 0) } catch { XCTFail() } } func testRemoveChildAtIndexThrows() { let parent = Node() do { try parent.removeChild(at: 0) XCTFail() } catch { } } func testRemoveChildAtIndexValid() { let parent = Node() parent.addChild(Node()) do { try parent.removeChild(at: 0) } catch { XCTFail() } } func testRemoveChildThrows() { let parent = Node() let child = Node() do { try parent.removeChild(child) XCTFail() } catch { } } func testRemoveChildValid() { let parent = Node() let child = Node() parent.addChild(child) do { try parent.removeChild(child) } catch { XCTFail() } } func testHasChildFalseEmpty() { let parent = Node() XCTAssertFalse(parent.hasChild(Node())) } func testHasChildFalse() { let parent = Node() parent.addChild(Node()) XCTAssertFalse(parent.hasChild(Node())) } func testHasChildTrue() { let parent = Node() let child = Node() parent.addChild(child) XCTAssert(parent.hasChild(child)) } func testChildAtIndexNilEmpty() { let parent = Node() XCTAssertNil(parent.child(at: 0)) } func testChildAtIndexNil() { let parent = Node() parent.addChild(Node()) XCTAssertNil(parent.child(at: 1)) } func testChildAtIndexValidSingle() { let parent = Node() let child = Node() parent.addChild(child) XCTAssert(parent.child(at: 0) === child) } func testChildAtIndexValidMultiple() { let parent = Node() let child1 = Node() let child2 = Node() parent.addChild(child1) parent.addChild(child2) XCTAssert(parent.child(at: 1) === child2) } func testLeafAtIndexSelf() { let leaf = Node() XCTAssert(leaf.leaf(at: 0) === leaf) } func testLeafAtIndexNilLeaf() { let leaf = Node() XCTAssertNil(leaf.leaf(at: 1)) } func testLeafAtIndexNilSingleDepth() { let parent = Node() for _ in 0..<5 { parent.addChild(Node()) } XCTAssertNil(parent.leaf(at: 5)) } func testLeafAtIndexNilMultipleDepth() { let root = Node() let internal1 = Node() for _ in 0..<2 { internal1.addChild(Node()) } let internal2 = Node() for _ in 0..<2 { internal2.addChild(Node()) } root.addChild(internal1) root.addChild(internal2) XCTAssertNil(root.leaf(at: 4)) } func testLeafAtIndexValidSingleDepth() { let parent = Node() let child1 = Node() let child2 = Node() parent.addChildren([child1, child2]) XCTAssert(parent.leaf(at: 1) === child2) } func testLeafAtIndexValidMultipleDepth() { let root = Node() let internal1 = Node() let leaf1 = Node() let leaf2 = Node() internal1.addChildren([leaf1, leaf2]) let internal2 = Node() let leaf3 = Node() let leaf4 = Node() internal2.addChildren([leaf3, leaf4]) root.addChildren([internal1, internal2]) XCTAssert(root.leaf(at: 3) === leaf4) } func testIsRootTrueSingleNode() { let root = Node() XCTAssert(root.isRoot) } func testIsRootTrueContainer() { let root = Node() root.addChildren([Node(), Node(), Node()]) XCTAssert(root.isRoot) } func testIsLeafTrueRoot() { let root = Node() XCTAssert(root.isLeaf) } func testIsLeafTrueLeaf() { let root = Node() let child = Node() root.addChild(child) XCTAssert(child.isLeaf) } func testIsLeafFalse() { let root = Node() let child = Node() root.addChild(child) XCTAssertFalse(root.isLeaf) } func testIsContainerTrue() { let root = Node() let child = Node() root.addChild(child) XCTAssert(root.isContainer) } func testRootSelfSingleNode() { let root = Node() XCTAssert(root.root === root) } func testRootOnlyChild() { let root = Node() let child = Node() root.addChild(child) XCTAssert(child.root === root) } func testRootGrandchild() { let root = Node() let child = Node() let grandchild = Node() child.addChild(grandchild) root.addChild(child) XCTAssert(grandchild.root === root) } func testIsContainerFalse() { let root = Node() let child = Node() root.addChild(child) XCTAssertFalse(child.isContainer) } func testPathToRootSingleNode() { let root = Node() XCTAssert(root.pathToRoot == [root]) } func testPathToRootOnlyChild() { let root = Node() let child = Node() root.addChild(child) XCTAssert(child.pathToRoot == [child, root]) } func testPathToRootGrandchild() { let root = Node() let child = Node() let grandchild = Node() child.addChild(grandchild) root.addChild(child) XCTAssert(grandchild.pathToRoot == [grandchild, child, root]) } func testHasAncestorSingleNode() { let root = Node() XCTAssertFalse(root.hasAncestor(root)) } func testHasAncestorOnlyChild() { let root = Node() let child = Node() root.addChild(child) XCTAssert(child.hasAncestor(root)) } func testHasAncestorGrandchild() { let root = Node() let child = Node() let grandchild = Node() child.addChild(grandchild) root.addChild(child) XCTAssert(grandchild.hasAncestor(root)) XCTAssert(child.hasAncestor(root)) } func testAncestorAtDistanceSingleValid() { let root = Node() XCTAssert(root.ancestor(at: 0) === root) } func testAncestorAtDistanceSingleNil() { let root = Node() XCTAssertNil(root.ancestor(at: 1)) } func testAncestorAtDistanceOnlyChild() { let root = Node() let child = Node() root.addChild(child) XCTAssert(child.ancestor(at: 1) === root) } func testAncestorAtDistanceGrandchild() { let root = Node() let child = Node() let grandchild = Node() child.addChild(grandchild) root.addChild(child) XCTAssert(grandchild.ancestor(at: 1) === child) XCTAssert(grandchild.ancestor(at: 2) === root) } func testDepthRoot_1() { let root = Node() XCTAssertEqual(root.depth, 0) } func testDepthOnlyChild_1() { let root = Node() let child = Node() root.addChild(child) XCTAssertEqual(child.depth, 1) } func testDepthGrandchild_2() { let root = Node() let child = Node() let grandchild = Node() child.addChild(grandchild) root.addChild(child) XCTAssertEqual(grandchild.depth, 2) } func testHeightSingleNode_0() { let root = Node() XCTAssertEqual(root.height, 0) } func testHeightParent_1() { let parent = Node() parent.addChild(Node()) XCTAssertEqual(parent.height, 1) } func testHeightGrandparent_2() { let grandparent = Node() let parent = Node() parent.addChild(Node()) grandparent.addChild(parent) XCTAssertEqual(grandparent.height, 2) XCTAssertEqual(parent.height, 1) } func testUnbalancedGrandParent_2() { let grandparent = Node() let parent1 = Node() let parent2 = Node() parent1.addChild(Node()) grandparent.addChild(parent1) grandparent.addChild(parent2) XCTAssertEqual(grandparent.height, 2) XCTAssertEqual(parent2.heightOfTree, 2) } func testHasDescendentFalseSingleNode() { let root = Node() let other = Node() XCTAssertFalse(root.hasDescendent(other)) } func testHasDescendentParent() { let parent = Node() let child = Node() parent.addChild(child) XCTAssert(parent.hasDescendent(child)) XCTAssertFalse(child.hasDescendent(parent)) } func testHasDescendentGrandparent() { let grandparent = Node() let parent = Node() let child = Node() parent.addChild(child) grandparent.addChild(parent) XCTAssert(grandparent.hasDescendent(child)) XCTAssertFalse(child.hasDescendent(grandparent)) } func testLeafAtIndexNilNoLeaves() { let root = Node() XCTAssertNil(root.leaf(at: 2)) } } private func == <T: AnyObject>(lhs: [T], rhs: [T]) -> Bool { for (a,b) in zip(lhs, rhs) { if a !== b { return false } } return true }
mit
067589902ba6fad35740bda389117994
24.186893
69
0.568565
4.228606
false
true
false
false
Vugla/PSCellStyleButton
PSCellStyleButtonSample/ViewController.swift
1
773
// // ViewController.swift // PSCellStyleHighlightButton // // Created by Predrag Samardzic on 08/11/15. // Copyright © 2015 pedja. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var secondButton: PSCellStyleButton! @IBOutlet weak var thirdButton: PSCellStyleButton! override func viewDidLoad() { super.viewDidLoad() secondButton.showBottomLine = false; thirdButton.bottomLineColor = UIColor.black thirdButton.bottomLineLeftInset = 0.0 thirdButton.bottomLineRightInset = 0.0 thirdButton.tintColor = UIColor.red thirdButton.setTitleColor(UIColor.blue, for: .normal) thirdButton.backgroundColor = UIColor.magenta } }
mit
67cd87e0161e45230df28012c6ef5fb7
24.733333
61
0.690415
4.51462
false
false
false
false
airbnb/lottie-ios
Sources/Private/MainThread/NodeRenderSystem/Nodes/RenderNodes/GradientFillNode.swift
3
2903
// // GradientFillNode.swift // lottie-swift // // Created by Brandon Withrow on 1/22/19. // import Foundation import QuartzCore // MARK: - GradientFillProperties final class GradientFillProperties: NodePropertyMap, KeypathSearchable { // MARK: Lifecycle init(gradientfill: GradientFill) { keypathName = gradientfill.name opacity = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.opacity.keyframes)) startPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.startPoint.keyframes)) endPoint = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.endPoint.keyframes)) colors = NodeProperty(provider: KeyframeInterpolator(keyframes: gradientfill.colors.keyframes)) gradientType = gradientfill.gradientType numberOfColors = gradientfill.numberOfColors fillRule = gradientfill.fillRule keypathProperties = [ "Opacity" : opacity, "Start Point" : startPoint, "End Point" : endPoint, "Colors" : colors, ] properties = Array(keypathProperties.values) } // MARK: Internal var keypathName: String let opacity: NodeProperty<LottieVector1D> let startPoint: NodeProperty<LottieVector3D> let endPoint: NodeProperty<LottieVector3D> let colors: NodeProperty<[Double]> let gradientType: GradientType let numberOfColors: Int let fillRule: FillRule let keypathProperties: [String: AnyNodeProperty] let properties: [AnyNodeProperty] } // MARK: - GradientFillNode final class GradientFillNode: AnimatorNode, RenderNode { // MARK: Lifecycle init(parentNode: AnimatorNode?, gradientFill: GradientFill) { fillRender = GradientFillRenderer(parent: parentNode?.outputNode) fillProperties = GradientFillProperties(gradientfill: gradientFill) self.parentNode = parentNode } // MARK: Internal let fillRender: GradientFillRenderer let fillProperties: GradientFillProperties let parentNode: AnimatorNode? var hasLocalUpdates = false var hasUpstreamUpdates = false var lastUpdateFrame: CGFloat? = nil var renderer: NodeOutput & Renderable { fillRender } // MARK: Animator Node Protocol var propertyMap: NodePropertyMap & KeypathSearchable { fillProperties } var isEnabled = true { didSet { fillRender.isEnabled = isEnabled } } func localUpdatesPermeateDownstream() -> Bool { false } func rebuildOutputs(frame _: CGFloat) { fillRender.start = fillProperties.startPoint.value.pointValue fillRender.end = fillProperties.endPoint.value.pointValue fillRender.opacity = fillProperties.opacity.value.cgFloatValue * 0.01 fillRender.colors = fillProperties.colors.value.map { CGFloat($0) } fillRender.type = fillProperties.gradientType fillRender.numberOfColors = fillProperties.numberOfColors fillRender.fillRule = fillProperties.fillRule.caFillRule } }
apache-2.0
4d1c273150d34d8e1c1acaf00e938e4a
26.647619
107
0.751636
4.674718
false
false
false
false
phatblat/Butler
Tests/ButlerTests/FolderSpec.swift
1
2550
// // FolderSpec.swift // Butler // // Created by Ben Chatelain on 6/4/17. // // @testable import Butler import Quick import Nimble import Foundation class FolderSpec: QuickSpec { override func spec() { describe("folder") { let jsonFile: NSString = "Folder.json" var project: Folder! = nil beforeEach { let bundle = Bundle(for: type(of: self)) let url = bundle.url(forResource: jsonFile.deletingPathExtension, withExtension: jsonFile.pathExtension, subdirectory: "JSON/Job")! let data = try! Data(contentsOf: url) let decoder = JSONDecoder() project = try! decoder.decode(Folder.self, from: data) } it("has class") { expect(project._class) == JavaClass.folder } it("has a url") { expect(project.url) == URL(string: "http://jenkins.log-g.co/job/Job%20Types/") } it("has an empty description") { expect(project.description).to(beNil()) } it("has a name") { expect(project.name) == "Job Types" } it("has a full name") { expect(project.fullName) == "Job Types" } it("has a display name") { expect(project.displayName) == "Job Types" } it("has a display name or null?") { expect(project.displayNameOrNull).to(beNil()) } it("has a full display name") { expect(project.fullDisplayName) == "Job Types" } it("has 8 jobs") { expect(project.jobs.count) == 8 } it("has no health reports") { expect(project.healthReport).notTo(beNil()) expect(project.healthReport.count) == 0 } it("has a primary view") { expect(project.primaryView["name"]) == "All" } it("has a view") { expect(project.views).notTo(beNil()) expect(project.views.count) == 1 } it("has actions") { expect(project.actions).notTo(beNil()) expect(project.actions.count) == 2 expect(project.actions.last!["_class"]) == "com.cloudbees.plugins.credentials.ViewCredentialsAction" } } } }
mit
1ab2eadb03693fd3f6e77d38a07f627d
33
116
0.480784
4.653285
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCAssetsSearchResultViewController.swift
2
4579
// // NCAssetsSearchResultViewController.swift // Neocom // // Created by Artem Shimanski on 09.06.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI import CoreData import Futures class NCAssetsSearchResultViewController: NCTreeViewController, UISearchResultsUpdating { var items: [Int64: NCAsset]? var typeIDs: Set<Int>? var locations: [Int64: NCLocation]? var contents: [Int64: [NCAsset]]? override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCHeaderTableViewCell.default, Prototype.NCHeaderTableViewCell.image, Prototype.NCDefaultTableViewCell.default]) } private let root = TreeNode() override func content() -> Future<TreeNode?> { return .init(root) } //MARK: - UISearchResultsUpdating private let gate = NCGate() public func updateSearchResults(for searchController: UISearchController) { guard let text = searchController.searchBar.text, let items = items, let contents = contents, let typeIDs = typeIDs, !text.isEmpty else { return } let locations = self.locations ?? [:] gate.perform { NCDatabase.sharedDatabase?.performTaskAndWait { managedObjectContext in var types = [Int: NCDBInvType]() var filtered: [NCAsset] = [] let filteredLocations = Set(locations.filter {$0.value.displayName.string.range(of: text, options: [.caseInsensitive], range: nil, locale: nil) != nil}.map {$0.key}) if typeIDs.count > 0 { let request = NSFetchRequest<NSDictionary>(entityName: "InvType") request.predicate = NSPredicate(format: "typeID in %@ AND (typeName CONTAINS [C] %@ OR group.groupName CONTAINS [C] %@ OR group.category.categoryName CONTAINS [C] %@)", typeIDs, text, text, text) request.propertiesToFetch = [NSEntityDescription.entity(forEntityName: "InvType", in: managedObjectContext)!.propertiesByName["typeID"]!] request.resultType = .dictionaryResultType let result = Set((try? managedObjectContext.fetch(request))?.compactMap {$0["typeID"] as? Int} ?? []) var array = Array(items.values.filter { result.contains($0.typeID) || filteredLocations.contains($0.locationID) }) var array2 = array filtered.append(contentsOf: array) while !array.isEmpty { array = array.compactMap {items[$0.locationID]} filtered.append(contentsOf: array) } while !array2.isEmpty { array2 = Array(array2.compactMap {contents[$0.itemID]}.joined()) filtered.append(contentsOf: array2) } } var items: [Int64: NCAsset] = [:] var filteredContents: [Int64: [NCAsset]] = [:] var typeIDs = Set<Int>() filtered.forEach { _ = (filteredContents[$0.locationID]?.append($0)) ?? (filteredContents[$0.locationID] = [$0]) items[$0.itemID] = $0 typeIDs.insert($0.typeID) } if typeIDs.count > 0 { let result: [NCDBInvType]? = managedObjectContext.fetch("InvType", where: "typeID in %@", typeIDs) result?.forEach {types[Int($0.typeID)] = $0} } var sections = [DefaultTreeSection]() for locationID in Set(locations.keys).subtracting(Set(items.keys)) { guard var rows = filteredContents[locationID]?.map ({NCAssetRow(asset: $0, contents: filteredContents, types: types)}) else {continue} rows.sort { ($0.attributedTitle?.string ?? "") < ($1.attributedTitle?.string ?? "") } let location = locations[locationID] let title = location?.displayName ?? NSAttributedString(string: NSLocalizedString("Unknown Location", comment: "")) let nodeIdentifier = "\(locationID)" sections.append(DefaultTreeSection(nodeIdentifier: nodeIdentifier, attributedTitle: title.uppercased(), children: rows)) } sections.sort {$0.nodeIdentifier! < $1.nodeIdentifier!} DispatchQueue.main.async { self.root.children = sections self.tableView.backgroundView = sections.isEmpty ? NCTableViewBackgroundLabel(text: NSLocalizedString("No Results", comment: "")) : nil } } } } }
lgpl-2.1
52091c2de2e3ac75945f738c8da7dfc0
35.047244
200
0.605068
4.661914
false
false
false
false
moltin/ios-sdk
Sources/SDK/Models/Product.swift
1
5969
// // Product.swift // moltin // // Created by Craig Tweedy on 22/02/2018. // import Foundation /// Represents a price on a `Product` public struct ProductPrice: Codable { /// The amount this product can sell for public let amount: Int /// The currency this price is in public let currency: String /// Whether this price includes tax public let includesTax: Bool enum CodingKeys: String, CodingKey { case includesTax = "includes_tax" case amount case currency } } /// Represents stock levels on a `Product` public struct ProductStock: Codable { /// The level of stock a product has public let level: Int /// in-stock / out-stock public let availability: String } /// Represents variation options on a `Product` public class ProductVariationOption: Codable { /// The id of this option public let id: String /// The name of this option public let name: String /// The description of this option public let description: String } /// Represents variations on a `Product` public class ProductVariation: Codable { /// The id of this variation public let id: String /// The options this variation has public let options: [ProductVariationOption] } /// Represents the meta properties of a `Product` public class ProductMeta: Codable { /// The timestamps of this product public let timestamps: Timestamps /// The stock information of this product public let stock: ProductStock /// The display price information of this product public let displayPrice: DisplayPrices? /// The variations this product has public let variations: [ProductVariation]? /// The variation matrix of this product public let variationMatrix: [[String: String]]? enum CodingKeys: String, CodingKey { case displayPrice = "display_price" case variationMatrix = "variation_matrix" case timestamps case stock case variations } } /// Represents a `Product` in moltin open class Product: Codable, HasRelationship { /// The id of this product public let id: String /// The type of this object public let type: String /// The name of this product public let name: String /// The slug of this product public let slug: String /// The SKU of this product public let sku: String /// Whether or not moltin manages the stock of this product public let manageStock: Bool /// The description of this product public let description: String /// The price information for this product public let price: [ProductPrice]? /// draft / live public let status: String /// Physical / Digital public let commodityType: String /// The meta information for this product public let meta: ProductMeta /// The relationships this product has public let relationships: Relationships? /// The main image of this product public var mainImage: File? /// The files this product has public var files: [File]? /// The categories this product belongs to public var categories: [Category]? /// The brands this product belongs to public var brands: [Brand]? /// The collections this product belongs to public var collections: [Collection]? enum CodingKeys: String, CodingKey { case manageStock = "manage_stock" case commodityType = "commodity_type" case id case type case name case slug case sku case description case price case status case meta case relationships } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let includes: IncludesContainer = decoder.userInfo[.includes] as? IncludesContainer ?? [:] self.id = try container.decode(String.self, forKey: .id) self.type = try container.decode(String.self, forKey: .type) self.name = try container.decode(String.self, forKey: .name) self.slug = try container.decode(String.self, forKey: .slug) self.sku = try container.decode(String.self, forKey: .sku) self.description = try container.decode(String.self, forKey: .description) self.price = try container.decode([ProductPrice].self, forKey: .price) self.status = try container.decode(String.self, forKey: .status) self.meta = try container.decode(ProductMeta.self, forKey: .meta) self.relationships = try container.decodeIfPresent(Relationships.self, forKey: .relationships) self.manageStock = try container.decode(Bool.self, forKey: .manageStock) self.commodityType = try container.decode(String.self, forKey: .commodityType) try self.decodeRelationships(fromRelationships: self.relationships, withIncludes: includes) } } extension Product { func decodeRelationships( fromRelationships relationships: Relationships?, withIncludes includes: IncludesContainer ) throws { self.mainImage = try self.decodeSingle( fromRelationships: relationships?[keyPath: \Relationships.mainImage], withIncludes: includes["main_images"]) self.files = try self.decodeMany( fromRelationships: relationships?[keyPath: \Relationships.files], withIncludes: includes["files"]) self.categories = try self.decodeMany( fromRelationships: relationships?[keyPath: \Relationships.categories], withIncludes: includes["categories"]) self.brands = try self.decodeMany( fromRelationships: relationships?[keyPath: \Relationships.brands], withIncludes: includes["brands"]) self.collections = try self.decodeMany( fromRelationships: relationships?[keyPath: \Relationships.collections], withIncludes: includes["collections"]) } }
mit
c18b3b84f02f8a4a461d6c3e1d5adb1e
31.977901
102
0.674317
4.786688
false
false
false
false
mozilla-mobile/firefox-ios
Sync/Keys.swift
2
6103
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Account import Shared import SwiftyJSON /** * Swift can't do functional factories. I would like to have one of the following * approaches be viable: * * 1. Derive the constructor from the consumer of the factory. * 2. Accept a type as input. * * Neither of these are viable, so we instead pass an explicit constructor closure. * * Most of these approaches produce either odd compiler errors, or -- worse -- * compile and then yield runtime EXC_BAD_ACCESS (see Radar 20230159). * * For this reason, be careful trying to simplify or improve this code. */ public func keysPayloadFactory<T: CleartextPayloadJSON>(keyBundle: KeyBundle, _ f: @escaping (JSON) -> T) -> (String) -> T? { return { (payload: String) -> T? in let potential = EncryptedJSON(json: payload, keyBundle: keyBundle) if !potential.isValid() { return nil } let cleartext = potential.cleartext if cleartext == nil { return nil } return f(cleartext!) } } // TODO: how much do we want to move this into EncryptedJSON? public func keysPayloadSerializer<T: CleartextPayloadJSON>(keyBundle: KeyBundle, _ f: @escaping (T) -> JSON) -> (Record<T>) -> JSON? { return { (record: Record<T>) -> JSON? in let json = f(record.payload) if json.isNull() { // This should never happen, but if it does, we don't want to leak this // record to the server! return nil } // Get the most basic kind of encoding: no pretty printing. // This can throw; if so, we return nil. // `rawData` simply calls JSONSerialization.dataWithJSONObject:options:error, which // guarantees UTF-8 encoded output. guard let bytes: Data = try? json.rawData(options: []) else { return nil } // Given a valid non-null JSON object, we don't ever expect a round-trip to fail. assert(!JSON(bytes).isNull()) // We pass a null IV, which means "generate me a new one". // We then include the generated IV in the resulting record. if let (ciphertext, iv) = keyBundle.encrypt(bytes, iv: nil) { // So we have the encrypted payload. Now let's build the envelope around it. let ciphertext = ciphertext.base64EncodedString // The HMAC is computed over the base64 string. As bytes. Yes, I know. if let encodedCiphertextBytes = ciphertext.data(using: .ascii, allowLossyConversion: false) { let hmac = keyBundle.hmacString(encodedCiphertextBytes) let iv = iv.base64EncodedString // The payload is stringified JSON. Yes, I know. let payload: Any = JSON(["ciphertext": ciphertext, "IV": iv, "hmac": hmac]).stringify()! as Any let obj = ["id": record.id, "sortindex": record.sortindex, // This is how SwiftyJSON wants us to express a null that we want to // serialize. Yes, this is gross. "ttl": record.ttl ?? NSNull(), "payload": payload] return JSON(obj) } } return nil } } open class Keys: Equatable { let valid: Bool let defaultBundle: KeyBundle var collectionKeys: [String: KeyBundle] = [String: KeyBundle]() public init(defaultBundle: KeyBundle) { self.defaultBundle = defaultBundle self.valid = true } public init(payload: KeysPayload?) { if let payload = payload, payload.isValid(), let keys = payload.defaultKeys { self.defaultBundle = keys self.collectionKeys = payload.collectionKeys self.valid = true return } self.defaultBundle = KeyBundle.invalid self.valid = false } public convenience init(downloaded: EnvelopeJSON, main: KeyBundle) { let f: (JSON) -> KeysPayload = { KeysPayload($0) } let keysRecord = Record<KeysPayload>.fromEnvelope(downloaded, payloadFactory: keysPayloadFactory(keyBundle: main, f)) self.init(payload: keysRecord?.payload) } open class func random() -> Keys { return Keys(defaultBundle: KeyBundle.random()) } open func forCollection(_ collection: String) -> KeyBundle { if let bundle = collectionKeys[collection] { return bundle } return defaultBundle } open func encrypter<T>(_ collection: String, encoder: RecordEncoder<T>) -> RecordEncrypter<T> { return RecordEncrypter(bundle: forCollection(collection), encoder: encoder) } open func asPayload() -> KeysPayload { let json = JSON([ "id": "keys", "collection": "crypto", "default": self.defaultBundle.asPair(), "collections": mapValues(self.collectionKeys, f: { $0.asPair() }) ]) return KeysPayload(json) } public static func == (lhs: Keys, rhs: Keys) -> Bool { return lhs.valid == rhs.valid && lhs.defaultBundle == rhs.defaultBundle && lhs.collectionKeys == rhs.collectionKeys } } /** * Yup, these are basically typed tuples. */ public struct RecordEncoder<T: CleartextPayloadJSON> { let decode: (JSON) -> T let encode: (T) -> JSON } public struct RecordEncrypter<T: CleartextPayloadJSON> { let serializer: (Record<T>) -> JSON? let factory: (String) -> T? init(bundle: KeyBundle, encoder: RecordEncoder<T>) { self.serializer = keysPayloadSerializer(keyBundle: bundle, encoder.encode) self.factory = keysPayloadFactory(keyBundle: bundle, encoder.decode) } init(serializer: @escaping (Record<T>) -> JSON?, factory: @escaping (String) -> T?) { self.serializer = serializer self.factory = factory } }
mpl-2.0
d38f2fbfc189c7216a31fcdc14b535d5
35.76506
134
0.617401
4.494109
false
false
false
false
DylanModesitt/Picryption_iOS
Picryption/Image.swift
1
1884
// // Image.swift // Picryption // // Created by Dylan Modesitt on 4/21/17. // Copyright © 2017 Modesitt Systems. All rights reserved. // import Foundation import CoreImage import UIKit /* * The Image Class for Picryption * * Involves the changing of least significant bit of images * to encode data inside them. Notably, text. * */ enum SteganographyMethod { case StandardLSBSteganography } class Image: UIImage { // ToDo: Impliment this func encryptMessage(withMethod method: SteganographyMethod, withData data: [[Int]]?) { switch method { case .StandardLSBSteganography: encryptMessageWithLSB(withData: data) return } } private func encryptMessageWithLSB(withData data: [[Int]]?) { // iterate through every pixel // ajust pixel color to encode 3-bits of data // ajust the data array to represent chagnes // continue print("called") let pixelData = self.cgImage?.dataProvider?.data let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData) let height = Int(self.size.height) let width = Int(self.size.width) let zArry = [Int](repeating: 0, count:3) let yArry = [[Int]](repeating: zArry, count:width) let xArry = [[[Int]]](repeating: yArry, count:height) for (index, value) in xArry.enumerated() { for (index1, value1) in value.enumerated() { for (index2, var value2) in value1.enumerated() { let pixelInfo: Int = ((width * index) + index1) * 4 + index2 value2 = Int(data[pixelInfo]) print(value2) } } } } }
mit
7a1cdf3baa04447e60323ceea27afaa3
24.794521
90
0.55231
4.37907
false
false
false
false
connienguyen/volunteers-iOS
VOLA/VOLA/Helpers/Util/InputValidation.swift
1
3115
// // InputValidation.swift // VOLA // // Created by Connie Nguyen on 6/7/17. // Copyright © 2017 Systers-Opensource. All rights reserved. // import Foundation /// Struct to manage regexes used to validate text input struct ValidationRegex { static let email = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" static let name = "^([ \\u00c0-\\u01ffa-zA-Z'\\-]){2,}$" // Regex allows alphabetic unicode characters, e.g. ëøå static let password = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$" } /** Input validation rules to apply to text - email: Follows proper email format - name: Follows naming conventions - required: Text is not empty - none: No validation rule, input is always valid */ enum InputValidation: String { case email = "error.invalid-email" case name = "error.invalid-name" case password = "error.invalid-password" case required = "error.invalid-required" case none = "" /// Error description for when text fails validation var error: String { return self.rawValue } /** Validates text input according to validation rule - Parameters: - input: Text to validate */ func isValid(_ input: String?) -> Bool { guard let input = input else { return false } switch self { case .email: return NSPredicate(format: "SELF MATCHES %@", ValidationRegex.email).evaluate(with: input) case .name: return NSPredicate(format: "SELF MATCHES %@", ValidationRegex.name).evaluate(with: input) case .password: return NSPredicate(format: "SELF MATCHES %@", ValidationRegex.password).evaluate(with: input) case .required: return input.trimmed.characters.count >= 1 case .none: return true } } } protocol Validatable { var fieldsToValidate: [VLTextField] { get } } /// Additional wrapper protocol to avoid #selector objc error in setUpValidatableFields() protocol Validator { func textFieldEditingDidEnd(_ textField: VLTextField) } extension Validatable where Self: UIViewController { /// Array of strings describing input validation errors on view controller var validationErrorDescriptions: [String] { var errorDescriptions: [String] = [] for field in fieldsToValidate { field.validate() if !field.isValid { errorDescriptions.append(field.validator.error) } } return errorDescriptions } /** Set up each validatable field to do validation at the end of editing */ func setUpValidatableFields() { for field in fieldsToValidate { field.addTarget(self, action: #selector(textFieldEditingDidEnd(_:)), for: .editingDidEnd) } } } // MARK: - Validator extension UIViewController: Validator { /** Validate text field at end of editing - Parameters: - textField: Text field to validate */ func textFieldEditingDidEnd(_ textField: VLTextField) { textField.validate() } }
gpl-2.0
407c0b638332fc7512a65de202c04c51
27.805556
120
0.630665
4.31484
false
false
false
false
harlanhaskins/swift
stdlib/public/Differentiation/ArrayDifferentiation.swift
1
11285
//===--- ArrayDifferentiation.swift ---------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift //===----------------------------------------------------------------------===// // Protocol conformances //===----------------------------------------------------------------------===// // TODO(TF-938): Add `Element: Differentiable` requirement. extension Array { /// The view of an array as the differentiable product manifold of `Element` /// multiplied with itself `count` times. @frozen public struct DifferentiableView { var _base: [Element] } } extension Array.DifferentiableView: Differentiable where Element: Differentiable { /// The viewed array. public var base: [Element] { get { return _base } _modify { yield &_base } } @usableFromInline @derivative(of: base) func _vjpBase() -> ( value: [Element], pullback: (Array<Element>.TangentVector) -> TangentVector ) { return (base, { $0 }) } /// Creates a differentiable view of the given array. public init(_ base: [Element]) { self._base = base } @usableFromInline @derivative(of: init(_:)) static func _vjpInit(_ base: [Element]) -> ( value: Array.DifferentiableView, pullback: (TangentVector) -> TangentVector ) { return (Array.DifferentiableView(base), { $0 }) } public typealias TangentVector = Array<Element.TangentVector>.DifferentiableView public mutating func move(along direction: TangentVector) { precondition( base.count == direction.base.count, "cannot move Array.DifferentiableView with count \(base.count) along " + "direction with different count \(direction.base.count)") for i in base.indices { base[i].move(along: direction.base[i]) } } } extension Array.DifferentiableView: Equatable where Element: Differentiable & Equatable { public static func == ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Bool { return lhs.base == rhs.base } } extension Array.DifferentiableView: ExpressibleByArrayLiteral where Element: Differentiable { public init(arrayLiteral elements: Element...) { self.init(elements) } } extension Array.DifferentiableView: CustomStringConvertible where Element: Differentiable { public var description: String { return base.description } } /// Makes `Array.DifferentiableView` additive as the product space. /// /// Note that `Array.DifferentiableView([])` is the zero in the product spaces /// of all counts. extension Array.DifferentiableView: AdditiveArithmetic where Element: AdditiveArithmetic & Differentiable { public static var zero: Array.DifferentiableView { return Array.DifferentiableView([]) } public static func + ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Array.DifferentiableView { precondition( lhs.base.count == 0 || rhs.base.count == 0 || lhs.base.count == rhs.base.count, "cannot add Array.DifferentiableViews with different counts: " + "\(lhs.base.count) and \(rhs.base.count)") if lhs.base.count == 0 { return rhs } if rhs.base.count == 0 { return lhs } return Array.DifferentiableView(zip(lhs.base, rhs.base).map(+)) } public static func - ( lhs: Array.DifferentiableView, rhs: Array.DifferentiableView ) -> Array.DifferentiableView { precondition( lhs.base.count == 0 || rhs.base.count == 0 || lhs.base.count == rhs.base.count, "cannot subtract Array.DifferentiableViews with different counts: " + "\(lhs.base.count) and \(rhs.base.count)") if lhs.base.count == 0 { return rhs } if rhs.base.count == 0 { return lhs } return Array.DifferentiableView(zip(lhs.base, rhs.base).map(-)) } @inlinable public subscript(_ index: Int) -> Element { if index < base.count { return base[index] } else { return Element.zero } } } /// Makes `Array` differentiable as the product manifold of `Element` /// multiplied with itself `count` times. extension Array: Differentiable where Element: Differentiable { // In an ideal world, `TangentVector` would be `[Element.TangentVector]`. // Unfortunately, we cannot conform `Array` to `AdditiveArithmetic` for // `TangentVector` because `Array` already has a static `+` method with // different semantics from `AdditiveArithmetic.+`. So we use // `Array.DifferentiableView` for all these associated types. public typealias TangentVector = Array<Element.TangentVector>.DifferentiableView public mutating func move(along direction: TangentVector) { var view = DifferentiableView(self) view.move(along: direction) self = view.base } /// A closure that produces a `TangentVector` of zeros with the same /// `count` as `self`. public var zeroTangentVectorInitializer: () -> TangentVector { { [count = self.count] in TangentVector(.init(repeating: .zero, count: count)) } } } //===----------------------------------------------------------------------===// // Derivatives //===----------------------------------------------------------------------===// extension Array where Element: Differentiable { @usableFromInline @derivative(of: subscript) func _vjpSubscript(index: Int) -> ( value: Element, pullback: (Element.TangentVector) -> TangentVector ) { func pullback(_ v: Element.TangentVector) -> TangentVector { var dSelf = [Element.TangentVector]( repeating: .zero, count: count) dSelf[index] = v return TangentVector(dSelf) } return (self[index], pullback) } @usableFromInline @derivative(of: +) static func _vjpConcatenate(_ lhs: Self, _ rhs: Self) -> ( value: Self, pullback: (TangentVector) -> (TangentVector, TangentVector) ) { func pullback(_ v: TangentVector) -> (TangentVector, TangentVector) { precondition( v.base.count == lhs.count + rhs.count, "+ should receive gradient with count equal to sum of operand " + "counts, but counts are: gradient \(v.base.count), " + "lhs \(lhs.count), rhs \(rhs.count)") return ( TangentVector([Element.TangentVector](v.base[0..<lhs.count])), TangentVector([Element.TangentVector](v.base[lhs.count...])) ) } return (lhs + rhs, pullback) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: append) mutating func _vjpAppend(_ element: Element) -> ( value: Void, pullback: (inout TangentVector) -> Element.TangentVector ) { let appendedElementIndex = count append(element) return ((), { v in defer { v.base.removeLast() } return v.base[appendedElementIndex] }) } @usableFromInline @derivative(of: append) mutating func _jvpAppend(_ element: Element) -> ( value: Void, differential: (inout TangentVector, Element.TangentVector) -> Void ) { append(element) return ((), { $0.base.append($1) }) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: +=) static func _vjpAppend(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, pullback: (inout TangentVector) -> TangentVector ) { let lhsCount = lhs.count lhs += rhs return ((), { v in let drhs = TangentVector(.init(v.base.dropFirst(lhsCount))) let rhsCount = drhs.base.count v.base.removeLast(rhsCount) return drhs }) } @usableFromInline @derivative(of: +=) static func _jvpAppend(_ lhs: inout Self, _ rhs: Self) -> ( value: Void, differential: (inout TangentVector, TangentVector) -> Void ) { lhs += rhs return ((), { $0.base += $1.base }) } } extension Array where Element: Differentiable { @usableFromInline @derivative(of: init(repeating:count:)) static func _vjpInit(repeating repeatedValue: Element, count: Int) -> ( value: Self, pullback: (TangentVector) -> Element.TangentVector ) { ( value: Self(repeating: repeatedValue, count: count), pullback: { v in v.base.reduce(.zero, +) } ) } } //===----------------------------------------------------------------------===// // Differentiable higher order functions for collections //===----------------------------------------------------------------------===// extension Array where Element: Differentiable { @inlinable @differentiable(wrt: self) public func differentiableMap<Result: Differentiable>( _ body: @differentiable (Element) -> Result ) -> [Result] { map(body) } @inlinable @derivative(of: differentiableMap) internal func _vjpDifferentiableMap<Result: Differentiable>( _ body: @differentiable (Element) -> Result ) -> ( value: [Result], pullback: (Array<Result>.TangentVector) -> Array.TangentVector ) { var values: [Result] = [] var pullbacks: [(Result.TangentVector) -> Element.TangentVector] = [] for x in self { let (y, pb) = valueWithPullback(at: x, in: body) values.append(y) pullbacks.append(pb) } func pullback(_ tans: Array<Result>.TangentVector) -> Array.TangentVector { .init(zip(tans.base, pullbacks).map { tan, pb in pb(tan) }) } return (value: values, pullback: pullback) } } extension Array where Element: Differentiable { @inlinable @differentiable(wrt: (self, initialResult)) public func differentiableReduce<Result: Differentiable>( _ initialResult: Result, _ nextPartialResult: @differentiable (Result, Element) -> Result ) -> Result { reduce(initialResult, nextPartialResult) } @inlinable @derivative(of: differentiableReduce) internal func _vjpDifferentiableReduce<Result: Differentiable>( _ initialResult: Result, _ nextPartialResult: @differentiable (Result, Element) -> Result ) -> ( value: Result, pullback: (Result.TangentVector) -> (Array.TangentVector, Result.TangentVector) ) { var pullbacks: [(Result.TangentVector) -> (Result.TangentVector, Element.TangentVector)] = [] let count = self.count pullbacks.reserveCapacity(count) var result = initialResult for element in self { let (y, pb) = valueWithPullback(at: result, element, in: nextPartialResult) result = y pullbacks.append(pb) } return ( value: result, pullback: { tangent in var resultTangent = tangent var elementTangents = TangentVector([]) elementTangents.base.reserveCapacity(count) for pullback in pullbacks.reversed() { let (newResultTangent, elementTangent) = pullback(resultTangent) resultTangent = newResultTangent elementTangents.base.append(elementTangent) } return (TangentVector(elementTangents.base.reversed()), resultTangent) } ) } }
apache-2.0
508f17f84ae1a87b426bbf5e035ed548
29.749319
81
0.630837
4.449921
false
false
false
false
themonki/onebusaway-iphone
Carthage/Checkouts/swift-protobuf/Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift
1
14766
// Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift - A helper that generates SwiftProtobuf names. // // Copyright (c) 2014 - 2017 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// A helper that can generate SwiftProtobuf names from types. /// // ----------------------------------------------------------------------------- import Foundation public final class SwiftProtobufNamer { var filePrefixCache = [String:String]() var enumValueRelativeNameCache = [String:String]() var mappings: ProtoFileToModuleMappings var targetModule: String /// Initializes a a new namer, assuming everything will be in the same Swift module. public convenience init() { self.init(protoFileToModuleMappings: ProtoFileToModuleMappings(), targetModule: "") } /// Initializes a a new namer. All names will be generated as from the pov of the /// given file using the provided file to module mapper. public convenience init( currentFile file: FileDescriptor, protoFileToModuleMappings mappings: ProtoFileToModuleMappings ) { let targetModule = mappings.moduleName(forFile: file) ?? "" self.init(protoFileToModuleMappings: mappings, targetModule: targetModule) } /// Internal initializer. init( protoFileToModuleMappings mappings: ProtoFileToModuleMappings, targetModule: String ) { self.mappings = mappings self.targetModule = targetModule } /// Calculate the relative name for the given message. public func relativeName(message: Descriptor) -> String { if message.containingType != nil { return NamingUtils.sanitize(messageName: message.name) } else { let prefix = typePrefix(forFile: message.file) return NamingUtils.sanitize(messageName: prefix + message.name) } } /// Calculate the full name for the given message. public func fullName(message: Descriptor) -> String { let relativeName = self.relativeName(message: message) guard let containingType = message.containingType else { return modulePrefix(file: message.file) + relativeName } return fullName(message:containingType) + "." + relativeName } /// Calculate the relative name for the given enum. public func relativeName(enum e: EnumDescriptor) -> String { if e.containingType != nil { return NamingUtils.sanitize(enumName: e.name) } else { let prefix = typePrefix(forFile: e.file) return NamingUtils.sanitize(enumName: prefix + e.name) } } /// Calculate the full name for the given enum. public func fullName(enum e: EnumDescriptor) -> String { let relativeName = self.relativeName(enum: e) guard let containingType = e.containingType else { return modulePrefix(file: e.file) + relativeName } return fullName(message: containingType) + "." + relativeName } /// Compute the short names to use for the values of this enum. private func computeRelativeNames(enum e: EnumDescriptor) { let stripper = NamingUtils.PrefixStripper(prefix: e.name) /// Determine the initial canidate name for the name before /// doing duplicate checks. func canidateName(_ enumValue: EnumValueDescriptor) -> String { let baseName = enumValue.name if let stripped = stripper.strip(from: baseName) { let camelCased = NamingUtils.toLowerCamelCase(stripped) if isValidSwiftIdentifier(camelCased) { return camelCased } } return NamingUtils.toLowerCamelCase(baseName) } // Bucketed based on candidate names to check for duplicates. var canidates = [String:[EnumValueDescriptor]]() for enumValue in e.values { let canidate = canidateName(enumValue) if var existing = canidates[canidate] { existing.append(enumValue) canidates[canidate] = existing } else { canidates[canidate] = [enumValue] } } for (camelCased, enumValues) in canidates { // If there is only one, sanitize and cache it. guard enumValues.count > 1 else { enumValueRelativeNameCache[enumValues.first!.fullName] = NamingUtils.sanitize(enumCaseName: camelCased) continue } // There are two possible cases: // 1. There is the main entry and then all aliases for it that // happen to be the same after the prefix was stripped. // 2. There are atleast two values (there could also be aliases). // // For the first case, there's no need to do anything, we'll go // with just one Swift version. For the second, append "_#" to // the names to help make the different Swift versions clear // which they are. let firstValue = enumValues.first!.number let hasMultipleValues = enumValues.contains(where: { return $0.number != firstValue }) guard hasMultipleValues else { // Was the first case, all one value, just aliases that mapped // to the same name. let name = NamingUtils.sanitize(enumCaseName: camelCased) for e in enumValues { enumValueRelativeNameCache[e.fullName] = name } continue } for e in enumValues { // Can't put a negative size, so use "n" and make the number // positive. let suffix = e.number >= 0 ? "_\(e.number)" : "_n\(-e.number)" enumValueRelativeNameCache[e.fullName] = NamingUtils.sanitize(enumCaseName: camelCased + suffix) } } } /// Calculate the relative name for the given enum value. public func relativeName(enumValue: EnumValueDescriptor) -> String { if let name = enumValueRelativeNameCache[enumValue.fullName] { return name } computeRelativeNames(enum: enumValue.enumType) return enumValueRelativeNameCache[enumValue.fullName]! } /// Calculate the full name for the given enum value. public func fullName(enumValue: EnumValueDescriptor) -> String { return fullName(enum: enumValue.enumType) + "." + relativeName(enumValue: enumValue) } /// The relative name with a leading dot so it can be used where /// the type is known. public func dottedRelativeName(enumValue: EnumValueDescriptor) -> String { let relativeName = self.relativeName(enumValue: enumValue) return "." + NamingUtils.trimBackticks(relativeName) } /// Filters the Enum's values to those that will have unique Swift /// names. Only poorly named proto enum alias values get filtered /// away, so the assumption is they aren't really needed from an /// api pov. public func uniquelyNamedValues(enum e: EnumDescriptor) -> [EnumValueDescriptor] { return e.values.filter { // Original are kept as is. The computations for relative // name already adds values for collisions with different // values. guard let aliasOf = $0.aliasOf else { return true } let relativeName = self.relativeName(enumValue: $0) let aliasOfRelativeName = self.relativeName(enumValue: aliasOf) // If the relative name matches for the alias and original, drop // the alias. guard relativeName != aliasOfRelativeName else { return false } // Only include this alias if it is the first one with this name. // (handles alias with different cases in their names that get // mangled to a single Swift name.) let firstAlias = aliasOf.aliases.firstIndex { let otherRelativeName = self.relativeName(enumValue: $0) return relativeName == otherRelativeName } return aliasOf.aliases[firstAlias!] === $0 } } /// Calculate the relative name for the given oneof. public func relativeName(oneof: OneofDescriptor) -> String { let camelCase = NamingUtils.toUpperCamelCase(oneof.name) return NamingUtils.sanitize(oneofName: "OneOf_\(camelCase)") } /// Calculate the full name for the given oneof. public func fullName(oneof: OneofDescriptor) -> String { return fullName(message: oneof.containingType) + "." + relativeName(oneof: oneof) } /// Calculate the relative name for the given entension. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func relativeName(extensionField field: FieldDescriptor) -> String { precondition(field.isExtension) if field.extensionScope != nil { return NamingUtils.sanitize(messageScopedExtensionName: field.namingBase) } else { let swiftPrefix = typePrefix(forFile: field.file) return swiftPrefix + "Extensions_" + field.namingBase } } /// Calculate the full name for the given extension. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func fullName(extensionField field: FieldDescriptor) -> String { precondition(field.isExtension) let relativeName = self.relativeName(extensionField: field) guard let extensionScope = field.extensionScope else { return modulePrefix(file: field.file) + relativeName } let extensionScopeSwiftFullName = fullName(message: extensionScope) let relativeNameNoBackticks = NamingUtils.trimBackticks(relativeName) return extensionScopeSwiftFullName + ".Extensions." + relativeNameNoBackticks } public typealias MessageFieldNames = (name: String, prefixed: String, has: String, clear: String) /// Calculate the names to use for the Swift fields on the message. /// /// If `prefixed` is not empty, the name prefixed with that will also be included. /// /// If `includeHasAndClear` is False, the has:, clear: values in the result will /// be the empty string. /// /// - Precondition: `field` must be FieldDescriptor that's isn't for an extension. public func messagePropertyNames(field: FieldDescriptor, prefixed: String, includeHasAndClear: Bool) -> MessageFieldNames { precondition(!field.isExtension) let lowerName = NamingUtils.toLowerCamelCase(field.namingBase) let fieldName = NamingUtils.sanitize(fieldName: lowerName) let prefixedFieldName = prefixed.isEmpty ? "" : NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName) if !includeHasAndClear { return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: "", clear: "") } let upperName = NamingUtils.toUpperCamelCase(field.namingBase) let hasName = NamingUtils.sanitize(fieldName: "has\(upperName)", basedOn: lowerName) let clearName = NamingUtils.sanitize(fieldName: "clear\(upperName)", basedOn: lowerName) return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: hasName, clear: clearName) } public typealias OneofFieldNames = (name: String, prefixed: String) /// Calculate the name to use for the Swift field on the message. public func messagePropertyName(oneof: OneofDescriptor, prefixed: String = "_") -> OneofFieldNames { let lowerName = NamingUtils.toLowerCamelCase(oneof.name) let fieldName = NamingUtils.sanitize(fieldName: lowerName) let prefixedFieldName = NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName) return OneofFieldNames(name: fieldName, prefixed: prefixedFieldName) } public typealias MessageExtensionNames = (value: String, has: String, clear: String) /// Calculate the names to use for the Swift Extension on the extended /// message. /// /// - Precondition: `extensionField` must be FieldDescriptor for an extension. public func messagePropertyNames(extensionField field: FieldDescriptor) -> MessageExtensionNames { precondition(field.isExtension) let fieldBaseName = NamingUtils.toLowerCamelCase(field.namingBase) let fieldName: String let hasName: String let clearName: String if let extensionScope = field.extensionScope { let extensionScopeSwiftFullName = fullName(message: extensionScope) // Don't worry about any sanitize api on these names; since there is a // Message name on the front, it should never hit a reserved word. // // fieldBaseName is the lowerCase name even though we put more on the // front, this seems to help make the field name stick out a little // compared to the message name scoping it on the front. fieldName = NamingUtils.periodsToUnderscores(extensionScopeSwiftFullName + "_" + fieldBaseName) let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName) hasName = "has" + fieldNameFirstUp clearName = "clear" + fieldNameFirstUp } else { // If there was no package and no prefix, fieldBaseName could be a reserved // word, so sanitize. These's also the slim chance the prefix plus the // extension name resulted in a reserved word, so the sanitize is always // needed. let swiftPrefix = typePrefix(forFile: field.file) fieldName = NamingUtils.sanitize(fieldName: swiftPrefix + fieldBaseName) if swiftPrefix.isEmpty { // No prefix, so got back to UpperCamelCasing the extension name, and then // sanitize it like we did for the lower form. let upperCleaned = NamingUtils.sanitize(fieldName: NamingUtils.toUpperCamelCase(field.namingBase), basedOn: fieldBaseName) hasName = "has" + upperCleaned clearName = "clear" + upperCleaned } else { // Since there was a prefix, just add has/clear and ensure the first letter // was capitalized. let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName) hasName = "has" + fieldNameFirstUp clearName = "clear" + fieldNameFirstUp } } return MessageExtensionNames(value: fieldName, has: hasName, clear: clearName) } /// Calculate the prefix to use for this file, it is derived from the /// proto package or swift_prefix file option. public func typePrefix(forFile file: FileDescriptor) -> String { if let result = filePrefixCache[file.name] { return result } let result = NamingUtils.typePrefix(protoPackage: file.package, fileOptions: file.fileOptions) filePrefixCache[file.name] = result return result } /// Internal helper to find the module prefix for a symbol given a file. func modulePrefix(file: FileDescriptor) -> String { guard let prefix = mappings.moduleName(forFile: file) else { return String() } if prefix == targetModule { return String() } return "\(prefix)." } }
apache-2.0
5cd1800458e0916ad4dbb453d9e9c495
39.790055
109
0.689896
4.873267
false
false
false
false