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
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/DataStructures/Bag.swift
12
7470
// // Bag.swift // Rx // // Created by Krunoslav Zaher on 2/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import Swift let arrayDictionaryMaxSize = 30 /** Class that enables using memory allocations as a means to uniquely identify objects. */ class Identity { // weird things have known to happen with Swift var _forceAllocation: Int32 = 0 } func hash(_ _x: Int) -> Int { var x = _x x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) &* 0x45d9f3b x = ((x >> 16) ^ x) return x; } /** Unique identifier for object added to `Bag`. */ public struct BagKey : Hashable { let uniqueIdentity: Identity? let key: Int public var hashValue: Int { if let uniqueIdentity = uniqueIdentity { return hash(key) ^ (ObjectIdentifier(uniqueIdentity).hashValue) } else { return hash(key) } } } /** Compares two `BagKey`s. */ public func == (lhs: BagKey, rhs: BagKey) -> Bool { return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity } /** Data structure that represents a bag of elements typed `T`. Single element can be stored multiple times. Time and space complexity of insertion an deletion is O(n). It is suitable for storing small number of elements. */ public struct Bag<T> : CustomDebugStringConvertible { /** Type of identifier for inserted elements. */ public typealias KeyType = BagKey fileprivate typealias ScopeUniqueTokenType = Int typealias Entry = (key: BagKey, value: T) fileprivate var _uniqueIdentity: Identity? fileprivate var _nextKey: ScopeUniqueTokenType = 0 // data // first fill inline variables fileprivate var _key0: BagKey? = nil fileprivate var _value0: T? = nil fileprivate var _key1: BagKey? = nil fileprivate var _value1: T? = nil // then fill "array dictionary" fileprivate var _pairs = ContiguousArray<Entry>() // last is sparse dictionary fileprivate var _dictionary: [BagKey : T]? = nil fileprivate var _onlyFastPath = true /** Creates new empty `Bag`. */ public init() { } /** Inserts `value` into bag. - parameter element: Element to insert. - returns: Key that can be used to remove element from bag. */ public mutating func insert(_ element: T) -> BagKey { _nextKey = _nextKey &+ 1 #if DEBUG _nextKey = _nextKey % 20 #endif if _nextKey == 0 { _uniqueIdentity = Identity() } let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey) if _key0 == nil { _key0 = key _value0 = element return key } _onlyFastPath = false if _key1 == nil { _key1 = key _value1 = element return key } if _dictionary != nil { _dictionary![key] = element return key } if _pairs.count < arrayDictionaryMaxSize { _pairs.append(key: key, value: element) return key } if _dictionary == nil { _dictionary = [:] } _dictionary![key] = element return key } /** - returns: Number of elements in bag. */ public var count: Int { let dictionaryCount: Int = _dictionary?.count ?? 0 return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount } /** Removes all elements from bag and clears capacity. */ public mutating func removeAll() { _key0 = nil _value0 = nil _key1 = nil _value1 = nil _pairs.removeAll(keepingCapacity: false) _dictionary?.removeAll(keepingCapacity: false) } /** Removes element with a specific `key` from bag. - parameter key: Key that identifies element to remove from bag. - returns: Element that bag contained, or nil in case element was already removed. */ public mutating func removeKey(_ key: BagKey) -> T? { if _key0 == key { _key0 = nil let value = _value0! _value0 = nil return value } if _key1 == key { _key1 = nil let value = _value1! _value1 = nil return value } if let existingObject = _dictionary?.removeValue(forKey: key) { return existingObject } for i in 0 ..< _pairs.count { if _pairs[i].key == key { let value = _pairs[i].value _pairs.remove(at: i) return value } } return nil } } extension Bag { /** A textual representation of `self`, suitable for debugging. */ public var debugDescription : String { return "\(self.count) elements in Bag" } } // MARK: forEach extension Bag { /** Enumerates elements inside the bag. - parameter action: Enumeration closure. */ public func forEach(_ action: (T) -> Void) { if _onlyFastPath { if let value0 = _value0 { action(value0) } return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { action(value0) } if let value1 = value1 { action(value1) } for i in 0 ..< pairs.count { action(pairs[i].value) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { action(element) } } } } extension Bag where T: ObserverType { /** Dispatches `event` to app observers contained inside bag. - parameter action: Enumeration closure. */ public func on(_ event: Event<T.E>) { if _onlyFastPath { _value0?.on(event) return } let pairs = _pairs let value0 = _value0 let value1 = _value1 let dictionary = _dictionary if let value0 = value0 { value0.on(event) } if let value1 = value1 { value1.on(event) } for i in 0 ..< pairs.count { pairs[i].value.on(event) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.on(event) } } } } /** Dispatches `dispose` to all disposables contained inside bag. */ @available(*, deprecated, renamed: "disposeAll(in:)") public func disposeAllIn(_ bag: Bag<Disposable>) { disposeAll(in: bag) } /** Dispatches `dispose` to all disposables contained inside bag. */ public func disposeAll(in bag: Bag<Disposable>) { if bag._onlyFastPath { bag._value0?.dispose() return } let pairs = bag._pairs let value0 = bag._value0 let value1 = bag._value1 let dictionary = bag._dictionary if let value0 = value0 { value0.dispose() } if let value1 = value1 { value1.dispose() } for i in 0 ..< pairs.count { pairs[i].value.dispose() } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { element.dispose() } } }
mit
e97e8b50c9bc581f43e4f2839c508cdd
21.229167
99
0.544383
4.246163
false
false
false
false
Q42/NoticeWindow
Pod/Classes/NoticeView.swift
1
2780
// // NoticeView.swift // Pods // // Created by Tim van Steenis on 09/12/15. // // import Foundation import UIKit class NoticeView: UIView { @IBOutlet weak var horizontalStackView: UIStackView! @IBOutlet weak var leftImage: UIImageView! @IBOutlet weak var rightImage: UIImageView! @IBOutlet weak var leftImageWidth: NSLayoutConstraint! @IBOutlet weak var rightImageWidth: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! var style: NoticeViewStyle = NoticeViewStyle() { didSet { backgroundColor = style.backgroundColor titleLabel.textColor = style.textColor messageLabel.textColor = style.textColor titleLabel.numberOfLines = style.titleNumberOfLines messageLabel.numberOfLines = style.messageNumberOfLines horizontalStackView.spacing = style.imageSpacing layoutMargins = style.insets if let image = style.leftImage { leftImage.isHidden = false leftImageWidth.constant = image.width leftImage.image = image.image leftImage.tintColor = image.tintColor leftImage.contentMode = image.contentMode } else { leftImage.isHidden = true } if let image = style.rightImage { rightImage.isHidden = false rightImageWidth.constant = image.width rightImage.image = image.image rightImage.tintColor = image.tintColor rightImage.contentMode = image.contentMode } else { rightImage.isHidden = true } } } public override init(frame: CGRect) { super.init(frame: frame) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default .addObserver(self, selector: #selector(adjustForStatusBarFrameChanges), name: UIApplication.didChangeStatusBarFrameNotification, object: nil) } @objc fileprivate func adjustForStatusBarFrameChanges() { guard style.position == .top else { return } // For some reason, statusBarFrame hasn't been updated yet when rotating, but it is in next event loop DispatchQueue.main.async { self.updateLayoutMarginsWithStatusBarHeight() } } override func didMoveToWindow() { super.didMoveToWindow() updateLayoutMarginsWithStatusBarHeight() } private func updateLayoutMarginsWithStatusBarHeight() { guard style.position == .top else { return } let additionalHeight = (window as? NoticeWindow)?.additionalStatusBarHeight() ?? 0 layoutMargins.top = style.insets.top + additionalHeight } }
mit
ade02138ed007fd54ccc2b1ac695f3e3
26.524752
147
0.713309
5.063752
false
false
false
false
Brightify/ReactantUI
Sources/Tokenizer/Properties/AssignableProperty.swift
1
3261
// // AssignablePropertyDescription.swift // ReactantUI // // Created by Tadeas Kriz. // Copyright © 2017 Brightify. All rights reserved. // import Foundation #if canImport(UIKit) import UIKit #endif /** * Standard typed property obtained from an XML attribute. */ public struct AssignableProperty<T: AttributeSupportedPropertyType>: TypedProperty { public var namespace: [PropertyContainer.Namespace] public var name: String public var description: AssignablePropertyDescription<T> public var value: T public var attributeName: String { return namespace.resolvedAttributeName(name: name) } /** * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(context: PropertyContext) -> String { return value.generate(context: context.child(for: value)) } /** * - parameter target: UI element to be targetted with the property * - parameter context: property context to use * - returns: Swift `String` representation of the property application on the target */ public func application(on target: String, context: PropertyContext) -> String { let namespacedTarget = namespace.resolvedSwiftName(target: target) return "\(namespacedTarget).\(description.swiftName) = \(application(context: context))" } #if SanAndreas public func dematerialize(context: PropertyContext) -> XMLSerializableAttribute { return XMLSerializableAttribute(name: attributeName, value: value.dematerialize(context: context.child(for: value))) } #endif #if canImport(UIKit) /** * Try to apply the property on an object using the passed property context. * - parameter object: UI element to apply the property to * - parameter context: property context to use */ public func apply(on object: AnyObject, context: PropertyContext) throws { let key = description.key let selector = Selector("set\(key.capitalizingFirstLetter()):") let target = try resolveTarget(for: object) guard target.responds(to: selector) else { throw LiveUIError(message: "!! Object `\(target)` doesn't respond to selector `\(key)` to set value `\(value)`") } guard let resolvedValue = value.runtimeValue(context: context.child(for: value)) else { throw LiveUIError(message: "!! Value `\(value)` couldn't be resolved in runtime for key `\(key)`") } do { try catchException { _ = target.setValue(resolvedValue, forKey: key) } } catch { _ = target.perform(selector, with: resolvedValue) } } private func resolveTarget(for object: AnyObject) throws -> AnyObject { if namespace.isEmpty { return object } else { let keyPath = namespace.resolvedKeyPath guard let target = object.value(forKeyPath: keyPath) else { throw LiveUIError(message: "!! Object \(object) doesn't have keyPath \(keyPath) to resolve real target") } return target as AnyObject } } #endif }
mit
d5cff34220c9fdac380e03cc3400d03f
34.053763
124
0.654294
4.865672
false
false
false
false
mownier/pyrobase
Pyrobase/Pyrobase.swift
1
2029
// // Pyrobase.swift // Pyrobase // // Created by Mounir Ybanez on 01/05/2017. // Copyright © 2017 Ner. All rights reserved. // public class Pyrobase { internal var path: RequestPathProtocol internal var request: RequestProtocol public var baseURL: String { return path.baseURL } public init(request: RequestProtocol, path: RequestPathProtocol) { self.request = request self.path = path } public func get(path relativePath: String, query: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.read(path: path.build(relativePath), query: query) { result in completion(result) } } public func put(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .put, data: value) { result in completion(result) } } public func post(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .post, data: value) { result in completion(result) } } public func patch(path relativePath: String, value: [AnyHashable: Any], completion: @escaping (RequestResult) -> Void) { request.write(path: path.build(relativePath), method: .patch, data: value) { result in completion(result) } } public func delete(path relativePath: String, completion: @escaping (RequestResult) -> Void) { request.delete(path: path.build(relativePath), completion: completion) } } extension Pyrobase { public class func create(baseURL: String, accessToken: String) -> Pyrobase { let path = RequestPath(baseURL: baseURL, accessToken: accessToken) let request = Request.create() let pyrobase = Pyrobase(request: request, path: path) return pyrobase } }
mit
b32ea17f27966b0a373e97cf7eecb516
32.8
124
0.642505
4.38013
false
false
false
false
lukejmann/FBLA2017
Pods/Instructions/Sources/Helpers/CoachMarkLayoutHelper.swift
1
9860
// CoachMarkLayoutHelper.swift // // Copyright (c) 2016 Frédéric Maquin <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // swiftlint:disable line_length class CoachMarkLayoutHelper { var layoutDirection: UIUserInterfaceLayoutDirection = .leftToRight // TODO: Improve the layout system. Make it smarter. func constraints(for coachMarkView: CoachMarkView, coachMark: CoachMark, parentView: UIView, layoutDirection: UIUserInterfaceLayoutDirection? = nil) -> [NSLayoutConstraint] { if coachMarkView.superview != parentView { print("coachMarkView was not added to parentView, returned constraints will be empty") return [] } if layoutDirection == nil { if #available(iOS 9, *) { self.layoutDirection = UIView.userInterfaceLayoutDirection( for: parentView.semanticContentAttribute) } } else { self.layoutDirection = layoutDirection! } let computedProperties = computeProperties(for: coachMark, inParentView: parentView) let offset = arrowOffset(for: coachMark, withProperties: computedProperties, inParentView: parentView) switch computedProperties.segmentIndex { case 1: coachMarkView.changeArrowPosition(to: .leading, offset: offset) return leadingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 2: coachMarkView.changeArrowPosition(to: .center, offset: offset) return middleConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) case 3: coachMarkView.changeArrowPosition(to: .trailing, offset: offset) return trailingConstraints(for: coachMarkView, withCoachMark: coachMark, inParentView: parentView) default: return [NSLayoutConstraint]() } } private func leadingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } private func middleConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth)@1000)]-(>=\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) constraints.append(NSLayoutConstraint( item: coachMarkView, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0 )) return constraints } private func trailingConstraints(for coachMarkView: CoachMarkView, withCoachMark coachMark: CoachMark, inParentView parentView: UIView ) -> [NSLayoutConstraint] { return NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=\(coachMark.horizontalMargin))-[currentCoachMarkView(<=\(coachMark.maxWidth))]-(==\(coachMark.horizontalMargin))-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["currentCoachMarkView": coachMarkView]) } /// Returns the arrow offset, based on the layout and the /// segment in which the coach mark will be. /// /// - Parameter coachMark: coachmark data. /// - Parameter properties: precomputed properties. /// - Parameter parentView: view showing the coachmarks. private func arrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { var arrowOffset: CGFloat switch properties.segmentIndex { case 1: arrowOffset = leadingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 2: arrowOffset = middleArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) case 3: arrowOffset = trailingArrowOffset(for: coachMark, withProperties: properties, inParentView: parentView) default: arrowOffset = 0 break } return arrowOffset } private func leadingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return pointOfInterest.x - coachMark.horizontalMargin } else { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } } private func middleArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.center.x - pointOfInterest.x } else { return pointOfInterest.x - parentView.center.x } } private func trailingArrowOffset(for coachMark: CoachMark, withProperties properties: CoachMarkComputedProperties, inParentView parentView: UIView) -> CGFloat { guard let pointOfInterest = coachMark.pointOfInterest else { print("The point of interest was found nil. Fallbacking offset will be 0") return 0 } if properties.layoutDirection == .leftToRight { return parentView.bounds.size.width - pointOfInterest.x - coachMark.horizontalMargin } else { return pointOfInterest.x - coachMark.horizontalMargin } } /// Compute the segment index (for now the screen is separated /// in three horizontal areas and depending in which one the coach /// mark stand, it will be layed out in a different way. /// /// - Parameter coachMark: coachmark data. /// - Parameter layoutDirection: the layout direction (LTR or RTL) /// - Parameter frame: frame of the parent view /// /// - Returns: the segment index (either 1, 2 or 3) private func computeSegmentIndex( of coachMark: CoachMark, forLayoutDirection layoutDirection: UIUserInterfaceLayoutDirection, inFrame frame: CGRect ) -> Int { if let pointOfInterest = coachMark.pointOfInterest { var segmentIndex = 3 * pointOfInterest.x / frame.size.width if layoutDirection == .rightToLeft { segmentIndex = 3 - segmentIndex } return Int(ceil(segmentIndex)) } else { print("The point of interest was found nil. Fallbacking to middle segment.") return 1 } } private func computeProperties(for coachMark: CoachMark, inParentView parentView: UIView) -> CoachMarkComputedProperties { let segmentIndex = computeSegmentIndex(of: coachMark, forLayoutDirection: layoutDirection, inFrame: parentView.frame) return CoachMarkComputedProperties( layoutDirection: layoutDirection, segmentIndex: segmentIndex ) } } struct CoachMarkComputedProperties { let layoutDirection: UIUserInterfaceLayoutDirection let segmentIndex: Int }
mit
7fdccdfcd965ef43f7c5ba5fbd1a879f
44.851163
311
0.638771
6.130597
false
false
false
false
keyeMyria/edx-app-ios
Source/OEXStyles+Swift.swift
4
3515
// // OEXStyles+Swift.swift // edX // // Created by Ehmad Zubair Chughtai on 25/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import Foundation import UIKit extension OEXStyles { var navigationTitleTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .Base, color : navigationItemTintColor()) } var navigationButtonTextStyle : OEXTextStyle { return OEXTextStyle(weight: .SemiBold, size: .XSmall, color: nil) } public func applyGlobalAppearance() { if (OEXConfig.sharedConfig().shouldEnableNewCourseNavigation()) { //Probably want to set the tintColor of UIWindow but it didn't seem necessary right now UINavigationBar.appearance().barTintColor = navigationBarColor() UINavigationBar.appearance().barStyle = UIBarStyle.Black UINavigationBar.appearance().tintColor = navigationItemTintColor() UINavigationBar.appearance().titleTextAttributes = navigationTitleTextStyle.attributes UIBarButtonItem.appearance().setTitleTextAttributes(navigationButtonTextStyle.attributes, forState: .Normal) UIToolbar.appearance().tintColor = navigationBarColor() let styleAttributes = OEXTextStyle(weight: .Normal, size : .Small, color : self.neutralBlack()).attributes UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Selected) UISegmentedControl.appearance().setTitleTextAttributes(styleAttributes, forState: UIControlState.Normal) UISegmentedControl.appearance().tintColor = self.neutralLight() } if UIDevice.currentDevice().isOSVersionAtLeast8() { UINavigationBar.appearance().translucent = false } } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTintColor : UIColor { return UIColor(red: CGFloat(126.0/255.0), green: CGFloat(199.0/255.0), blue: CGFloat(143.0/255.0), alpha: CGFloat(1.00)) } ///**Warning:** Not from style guide. Do not add more uses public var progressBarTrackTintColor : UIColor { return UIColor(red: CGFloat(223.0/255.0), green: CGFloat(242.0/255.0), blue: CGFloat(228.0/255.0), alpha: CGFloat(1.00)) } var standardTextViewInsets : UIEdgeInsets { return UIEdgeInsetsMake(8, 8, 8, 8) } var standardFooterHeight : CGFloat { return 50 } // Standard text Styles var textAreaBodyStyle : OEXTextStyle { let style = OEXMutableTextStyle(weight: OEXTextWeight.Normal, size: .Small, color: OEXStyles.sharedStyles().neutralDark()) style.lineBreakMode = .ByWordWrapping return style } // Standard button styles var filledPrimaryButtonStyle : ButtonStyle { let buttonMargins : CGFloat = 8 let borderStyle = BorderStyle() let textStyle = OEXTextStyle(weight: .Normal, size: .Small, color: self.neutralWhite()) return ButtonStyle(textStyle: textStyle, backgroundColor: OEXStyles.sharedStyles().primaryBaseColor(), borderStyle: borderStyle, contentInsets : UIEdgeInsetsMake(buttonMargins, buttonMargins, buttonMargins, buttonMargins)) } // Standard border styles var entryFieldBorderStyle : BorderStyle { return BorderStyle(width: .Size(1), color: OEXStyles.sharedStyles().neutralLight()) } }
apache-2.0
edc461ffa186f25450b182ac5b367538
38.066667
136
0.676814
5.230655
false
false
false
false
relayr/apple-sdk
Sources/common/services/API/APIUsers.swift
1
7530
import ReactiveSwift import Result import Foundation internal extension API { /// User entity as represented on the relayr API platform. struct User: JSONable { let identifier: String var email: String? var nickname: String? var name: (first: String?, last: String?) var companyName: String? var industryArea: String? } } /// Instances of conforming type can request OAuth codes from the cloud servers. /// /// An OAuth code is the first step on an OAuth login process. Arm with the code, you can request an OAuth token. internal protocol OAuthCodeRetrievable { /// It request an OAuth code to the instance of the conforming type. /// The OAuth process won't start till a `start()` message is send to the `SignalProducer`. static func requestOAuthCode(toURL url: String, withRedirectURI redirectURI: String, willAnimate: Bool, cancellableButton: Bool) -> SignalProducer<String,API.Error> } // HTTP APIs for user related endpoints. internal extension API { /// Requests information about the user currently logged in which owns this API instance. func currentUserInfo() -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/user-info") return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Get, token: token, expectedCodes: [200]).attemptMap { (json : [String:Any]) in Result { try API.User(fromJSON: json) } } } /// Updates the user with the arguments passed. /// /// If no arguments are given, no HTTP call is performed and an error is returned. /// - parameter firstName: Modify the user's first name. /// - parameter lastName: Modify the user's last name. /// - parameter companyName: Modify the user's company name. /// - parameter industryArea: Modify the user's company area. func setUserInfo(withID userID: String, firstName: String?=nil, lastName: String?=nil, companyName: String?=nil, industryArea: String?=nil) -> SignalProducer<API.User,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "users/\(userID)") var body: [String:String] = [:] if let firstName = firstName { body[User.Keys.firstName] = firstName } if let lastName = lastName { body[User.Keys.lastName] = lastName } if let company = companyName { body[User.Keys.companyName] = company } if let industry = industryArea { body[User.Keys.industryArea] = industry } guard !body.isEmpty else { return SignalProducer(error: .insufficientInformation) } return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Patch, token: token, contentType: .JSON, body: body, expectedCodes: [200]).attemptMap { (json: [String:Any]) in Result { guard let data = json["data"] as? [String:Any] else { throw API.Error.invalidResponseBody(body: json) } return try API.User(fromJSON: data) } } } // MARK: Login & Tokens #if os(macOS) || os(iOS) /// It requests the temporal access OAuth code needed to ask for a 100 year OAuth access token. /// - parameter clientID: `String` representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: `String` representing the redirect URI you chosed when creating an app in the relayr developer platform. func oauthCode(withProjectID projectID: String, oauthRedirectURI redirectURI: String, willAnimate: Bool=false, cancellableButton: Bool=true) -> SignalProducer<String,API.Error> { let scope = "access-own-user-info+configure-devices+read-device-history" let relativePath = "oauth2/auth?client_id=\(projectID)&redirect_uri=\(redirectURI)&response_type=code&scope=\(scope)" let url = Addresses.build(withHostURL: urls.root, relativeURL: relativePath) return WebOAuthController.requestOAuthCode(toURL: url, withRedirectURI: redirectURI, willAnimate: willAnimate, cancellableButton: cancellableButton) } #endif /// It request a valid OAuth token from an OAuth code, clientID, clientSecret, and redirectURI. /// - parameter tmpCode: Temporal OAuth code (usually valid for 5 minutes) that it is required to retrieve a token. /// - parameter projectID: String representing the Oauth client ID. You receive this when creating an app in the relayr developer platform. /// - parameter oauthSecret: String representing the Oauth client secret. You receive this when creating an app in the relayr developer platform. /// - parameter redirectURI: String representing the redirect URI you chosed when creating an app in the Relayr developer platform. func oauthToken(withTemporalCode tmpCode: String, projectID: String, oauthSecret: String, redirectURI: String) -> SignalProducer<String,API.Error> { let url = Addresses.build(withHostURL: urls.root, relativeURL: "oauth2/token") let body = ["code": tmpCode, "client_id": projectID, "redirect_uri": redirectURI, "scope": "", "client_secret": oauthSecret, "grant_type": "authorization_code"] return self.sessionForRequests.requestJSON(withAbsoluteURL: url, method: .Post, contentType: .Xform, body: body, expectedCodes: [200]).attemptMap { (json : [String:Any]) in let token = json["access_token"] as? String return Result(token, failWith: .invalidResponseBody(body: json)) } } } internal extension API.User { typealias JSONType = [String:Any] init(fromJSON json: JSONType) throws { guard let identifier = json[Keys.identifier] as? String else { throw API.Error.invalidResponseBody(body: json) } self.identifier = identifier self.email = json[Keys.email] as? String self.nickname = json[Keys.name] as? String self.name = (json[Keys.firstName] as? String, json[Keys.lastName] as? String) self.companyName = json[Keys.companyName] as? String self.industryArea = json[Keys.industryArea] as? String } var json: JSONType { var result: JSONType = [Keys.identifier: self.identifier] if let email = self.email { result[Keys.email] = email } if let nickname = self.nickname { result[Keys.name] = nickname } if let firstName = self.name.first { result[Keys.firstName] = firstName } if let lastName = self.name.last { result[Keys.lastName] = lastName } if let company = self.companyName { result[Keys.companyName] = company } if let industry = self.industryArea { result[Keys.industryArea] = industry } return result } fileprivate init(withIdentifier identifier: String, email: String?=nil, nickname: String?=nil, firstName: String?=nil, lastName: String?=nil, company: String?=nil, industry: String?=nil) { self.identifier = identifier self.email = email self.nickname = nickname self.name = (firstName, lastName) self.companyName = company self.industryArea = industry } fileprivate struct Keys { static let identifier = "id" static let email = "email" static let name = "name" fileprivate static let firstName = "firstName" static let lastName = "lastName" static let companyName = "companyName" static let industryArea = "industryArea" } }
mit
0be95a152765dc0a5ccd308ef878da96
53.963504
193
0.684329
4.458259
false
false
false
false
dnosk/Explore
Example/Explore/ViewController.swift
1
1164
// // ViewController.swift // Explore // // Created by dnosk on 04/26/2017. // Copyright (c) 2017 dnosk. All rights reserved. // import Explore import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var appsDownloaded = [String]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self appsDownloaded = exploreAppsDownloaded() tableView.reloadData() } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appsDownloaded.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let app = appsDownloaded[indexPath.row] cell.textLabel?.text = app return cell } }
mit
5f0de78f81567cdd2699c4a3f8098caf
23.25
100
0.646048
5.173333
false
false
false
false
bm842/TradingLibrary
Sources/OandaRestV1Instrument.swift
2
9009
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import Foundation public final class OandaInstrument: GenericInstrument, Instrument { weak var oandaAccount: OandaRestAccount! { return account as! OandaRestAccount } weak var oanda: OandaRestBroker! init(account: OandaRestAccount, instrumentData: OandaRestV1Instrument) { self.oanda = account.oanda let instrument = instrumentData.instrument let elements = instrument.components(separatedBy: "_") super.init(instrument: instrument, displayName: instrumentData.displayName, pip: instrumentData.pip, minTradeUnits: 1, maxTradeUnits: instrumentData.maxTradeUnits, precision: instrumentData.precision, marginRate: instrumentData.marginRate, base: Currency(rawValue: elements[0]), quote: Currency(rawValue: elements[1])!) self.account = account } public override func stopRateEventsStreaming() { oanda.ratesStreamingConnection.stopStreaming() } public override func startRateEventsStreaming(_ queue: DispatchQueue, handler: @escaping (RatesEvent) -> ()) -> RequestStatus { var query = "prices?" query += "accountId=\(oandaAccount.id)" query += "&instruments=" + instrument return oanda.ratesStreamingConnection.startStreaming(query) { (status, json) in guard let json = json else { queue.async { handler(.status(time: Timestamp.now, status: status)) } return } if let price: OandaRestV1Price = try? json.value(for: "tick") { queue.async { handler(.tickEvent(tick: Tick(fromOanda: price))) } return } if let heartbeat: OandaRestV1Heartbeat = try? json.value(for: "heartbeat") { queue.async { handler(.heartBeat(time: Timestamp(microSeconds: heartbeat.time))) } return } log.error("%f: unexpected json = \(json)") } } public override func submitOrder(_ info: OrderCreation, completion: @escaping (RequestStatus, _ execution: OrderExecution) -> ()) { var params: String = "type=\(info.type.oandaValue)" params += "&side=\(info.side.oandaValue)" params += "&units=\(info.units)" params += "&instrument=\(instrument)" params += "&stopLoss=\(info.stopLoss ?? 0)" params += "&takeProfit=\(info.takeProfit ?? 0)" params += "&price=\(info.entry ?? 0)" params += "&expiry=\(info.expiry?.oandaRestV1Value ?? 0)" /*params += "&lowerBound=\(lowerBound)" params += "&upperBound=\(upperBound)" params += "&trailingStop=\(trailingStop)"*/ oanda.restConnection.fetchJson("accounts/\(oandaAccount.id)/orders", method: "POST", data: params) { (status, json) in var execution: OrderExecution = .none guard let json = json else { log.error("no json, status = \(status) creation=\(info)") return } do { let response = try OandaRestV1CreateOrderResponse(object: json) let time = Timestamp(microSeconds: response.time) if let orderOpened = response.orderOpened { let openedOrder = OrderInfo(orderId: "\(orderOpened.id)", time: time, type: info.type, side: info.side, units: info.units, entry: response.price, stopLoss: nilIfZero(orderOpened.stopLoss), takeProfit: nilIfZero(orderOpened.takeProfit), expiry: Timestamp(microSeconds: orderOpened.expiry)) let order = OandaOrder(instrument: self, info: openedOrder) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenOrders.append(order) } self.notify(tradeEvent: .orderCreated(info: openedOrder)) execution = .orderCreated(orderId: openedOrder.orderId) } if let tradeOpened = response.tradeOpened { let createdTrade = TradeInfo(tradeId: "\(tradeOpened.id)", time: time, side: info.side, units: tradeOpened.units, entry: response.price, stopLoss: nilIfZero(tradeOpened.stopLoss), takeProfit: nilIfZero(tradeOpened.takeProfit)) let trade = OandaTrade(instrument: self, info: createdTrade) self.oandaAccount.queue.sync { self.oandaAccount.internalOpenTrades.append(trade) } self.notify(tradeEvent: .tradeCreated(info: createdTrade)) execution = .orderFilled(tradeId: createdTrade.tradeId) } if let tradesClosed = response.tradesClosed { for tradeClosed in tradesClosed { self.reduceTrade(withId: "\(tradeClosed.id)", atTime: time, units: tradeClosed.units, atPrice: response.price, reason: .reverseOrder) } } if let tradeReduced = response.tradeReduced { self.reduceTrade(withId: "\(tradeReduced.id)", atTime: time, units: tradeReduced.units, atPrice: response.price, reason: .reverseOrder) } completion(status, execution) } catch { completion(OandaStatus.jsonParsingError(error), execution) } } } public override func quote(_ completion: @escaping (RequestStatus, _ tick: Tick?) -> ()) { oanda.restConnection.fetchArray("prices", query: "instruments=" + instrument) { (status, prices: [OandaRestV1Price]?) in if let setPrices = prices { for price in setPrices where price.instrument == self.instrument { completion(status, Tick(fromOanda: price)) break } } else { completion(status, nil) } } } }
mit
0ed0ff9ff97bd8abe6524c5b70220f67
37.5
133
0.487734
5.869055
false
false
false
false
pocketworks/Dollar.swift
Cent/Cent/Int.swift
1
2807
// // Int.swift // Cent // // Created by Ankur Patel on 6/30/14. // Copyright (c) 2014 Encore Dev Labs LLC. All rights reserved. // import Foundation extension Int { /// Invoke a callback n times /// /// :param callback The function to invoke that accepts the index public func times(callback: (Int) -> ()) { (0..<self).eachWithIndex { callback($0) } } /// Invoke a callback n times /// /// :param callback The function to invoke public func times(function: () -> ()) { self.times { (index: Int) -> () in function() } } /// Check if it is even /// /// :return Bool whether int is even public var isEven: Bool { get { return self % 2 == 0 } } /// Check if it is odd /// /// :return Bool whether int is odd public var isOdd: Bool { get { return self % 2 == 1 } } /// Splits the int into array of digits /// /// :return Bool whether int is odd public func digits() -> [Int] { var digits: [Int] = [] var selfCopy = self while selfCopy > 0 { digits << (selfCopy % 10) selfCopy = (selfCopy / 10) } return Array(digits.reverse()) } /// Get the next int /// /// :return next int public func next() -> Int { return self + 1 } /// Get the previous int /// /// :return previous int public func prev() -> Int { return self - 1 } /// Invoke the callback from int up to and including limit /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: () -> ()) { (self...limit).each { callback() } } /// Invoke the callback from int up to and including limit passing the index /// /// :params limit the max value to iterate upto /// :params callback to invoke public func upTo(limit: Int, callback: (Int) -> ()) { (self...limit).eachWithIndex { callback($0) } } /// Invoke the callback from int down to and including limit /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: () -> ()) { var selfCopy = self while selfCopy-- >= limit { callback() } } /// Invoke the callback from int down to and including limit passing the index /// /// :params limit the min value to iterate upto /// :params callback to invoke public func downTo(limit: Int, callback: (Int) -> ()) { var selfCopy = self while selfCopy >= limit { callback(selfCopy--) } } }
mit
9070a125d16521f2339d81c148398aef
23.840708
82
0.530816
4.379095
false
false
false
false
natecook1000/swift
test/PlaygroundTransform/high_performance.swift
7
1253
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main2 %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] __builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='5'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var b = true for i in 0..<3 { i continue } // CHECK-NEXT: [{{.*}}] __builtin_log[b='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0'] // CHECK-NEXT: [{{.*}}] __builtin_log[='1'] // CHECK-NEXT: [{{.*}}] __builtin_log[='2'] var c = true for i in 0..<3 { i break } // CHECK-NEXT: [{{.*}}] __builtin_log[c='true'] // CHECK-NEXT: [{{.*}}] __builtin_log[='0']
apache-2.0
d179622ada08036ee51d59e0127cbe28
28.139535
209
0.592179
2.962175
false
false
false
false
danfsd/FolioReaderKit
Example/Example/ViewController.swift
1
1987
// // ViewController.swift // Example // // Created by Heberti Almeida on 08/04/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit import FolioReaderKit class ViewController: UIViewController { @IBOutlet var bookOne: UIButton! @IBOutlet var bookTwo: UIButton! let epubSampleFiles = [ "The Silver Chair", // standard eBook // "Medcel", "The Adventures Of Sherlock Holmes - Adventure I", // audio-eBook ] override func viewDidLoad() { super.viewDidLoad() setCover(bookOne, index: 0) setCover(bookTwo, index: 1) } @IBAction func didOpen(sender: AnyObject) { openEpub(sender.tag); } func openEpub(sampleNum: Int) { let config = FolioReaderConfig() config.shouldHideNavigationOnTap = sampleNum == 1 ? true : false config.scrollDirection = sampleNum == 1 ? .horizontal : .vertical // See more at FolioReaderConfig.swift // config.enableTTS = false // config.allowSharing = false // config.tintColor = UIColor.blueColor() // config.toolBarTintColor = UIColor.redColor() // config.toolBarBackgroundColor = UIColor.purpleColor() // config.menuTextColor = UIColor.brownColor() // config.menuBackgroundColor = UIColor.lightGrayColor() let epubName = epubSampleFiles[sampleNum-1]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") FolioReader.presentReader(parentViewController: self, withEpubPath: bookPath!, andConfig: config, shouldRemoveEpub: false) } func setCover(button: UIButton, index: Int) { let epubName = epubSampleFiles[index]; let bookPath = NSBundle.mainBundle().pathForResource(epubName, ofType: "epub") if let image = FolioReader.getCoverImage(bookPath!) { button.setBackgroundImage(image, forState: .Normal) } } }
bsd-3-clause
ce6ce0d71999c9a27aaba194bb77f96c
31.57377
130
0.645194
4.485327
false
true
false
false
codercd/DPlayer
DPlayer/Model.swift
1
1721
// // Model.swift // DPlayer // // Created by LiChendi on 16/4/19. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit class Model: NSObject { } enum LiveBaseURL:String { case rtmp = "rtmp://live.quanmin.tv/live/1456011" case hls = "http://hls.quanmin.tv/live/1456011/playlist.m3u8" case flv = "http://flv.quanmin.tv/live/1456011.flv" } //struct HomepageModel { // var homepageCategories = Array<HomepageCategory>() // // // var list = Array<AnyObject>() { // willSet { //// print("will - list---- \(newValue)") // } // } // var homepageItems = Dictionary<String, AnyObject>() { // willSet { // for categories in newValue { // var homepageCategory = HomepageCategory() // homepageCategory.name = categories.0 // homepageCategory.detail = categories.1 as! Array<AnyObject> // homepageCategories.append(homepageCategory) // } // } // } //} //struct HomepageCategory { // var name = "" { // willSet { // print("name----\(newValue)") // } // } // var detail = Array<AnyObject>() { // willSet { // print("detail----\(newValue)") //// RoomDetail(). // } // } //} struct recommendList { // var } struct RoomDetail { var stateus = 0 var follow = 0 var avatar = "" var view = 0 var intro = "" var slug = "" var category_id = 0 var category_name = "" var category_slug = "" var recommend_image = "" var nick = "" var play_at = "" var announcement = "" var title = "" var uid = "" var thumb = "" }
mit
33dc39063638b30d5f30014ddc75bfcc
20.475
77
0.525029
3.571726
false
false
false
false
ociata/OCIKeyboardAdjuster
OCIKeyboardAdjuster.swift
1
7643
// // KeyboardAdjuster.swift // // // Created by Hristo Todorov - Oci on 6/5/15. // Copyright (c) 2015 // import UIKit class OCIKeyboardAdjuster: NSObject { static let sharedKeyboardAdjuster = OCIKeyboardAdjuster() weak var focusedControl: UIView? private override init() { //this way users will always use singleton instance } private(set) weak var scrollView: UIScrollView? private(set) weak var view: UIView! private var originalScrollOffset: CGPoint? private var originalScrollSize: CGSize? func startObserving(scrollableView: UIScrollView, holderView: UIView) { scrollView = scrollableView view = holderView //remove old observers stopObserving() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func stopObserving() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: scrollview ajust when keyboard present @objc private func keyboardWillShow(notification: NSNotification) { if nil == self.view || self.view.window == nil { return } if let scrollView = scrollView, let userInfo = notification.userInfo, let keyboardFrameInWindow = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let keyboardFrameInWindowBegin = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { // the keyboard frame is specified in window-level coordinates. this calculates the frame as if it were a subview of our view, making it a sibling of the scroll view let keyboardFrameInView = self.view.convertRect(keyboardFrameInWindow.CGRectValue(), fromView: nil) let scrollViewKeyboardIntersection = CGRectIntersection(scrollView.frame, keyboardFrameInView) UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { [weak self] in if let strongSelf = self, let scrollView = strongSelf.scrollView { if let focusedControl = strongSelf.focusedControl { // if the control is a deep in the hierarchy below the scroll view, this will calculate the frame as if it were a direct subview var controlFrameInScrollView = scrollView.convertRect(focusedControl.bounds, fromView: focusedControl) controlFrameInScrollView = CGRectInset(controlFrameInScrollView, 0, -10) let controlVisualOffsetToTopOfScrollview = controlFrameInScrollView.origin.y - scrollView.contentOffset.y let controlVisualBottom = controlVisualOffsetToTopOfScrollview + controlFrameInScrollView.size.height // this is the visible part of the scroll view that is not hidden by the keyboard let scrollViewVisibleHeight = scrollView.frame.size.height - scrollViewKeyboardIntersection.size.height var newContentOffset = scrollView.contentOffset //store it to better update latter strongSelf.originalScrollOffset = newContentOffset if controlVisualBottom > scrollViewVisibleHeight // check if the keyboard will hide the control in question { newContentOffset.y += (controlVisualBottom - scrollViewVisibleHeight) //check for impossible offset newContentOffset.y = min(newContentOffset.y, scrollView.contentSize.height - scrollViewVisibleHeight) } else if controlFrameInScrollView.origin.y < scrollView.contentOffset.y // if the control is not fully visible, make it so (useful if the user taps on a partially visible input field { newContentOffset.y = controlFrameInScrollView.origin.y } //no animation as we had own animation already going scrollView.setContentOffset(newContentOffset, animated: false) } var scrollSize = scrollView.contentSize if let _ = strongSelf.originalScrollSize { //subtract old keyboard value scrollSize.height -= strongSelf.view.convertRect(keyboardFrameInWindowBegin.CGRectValue(), fromView: nil).size.height } strongSelf.originalScrollSize = scrollSize scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollSize.height + keyboardFrameInView.height) } }, completion: nil) } } @objc private func keyboardWillHide(notification: NSNotification) { if self.view == nil || self.view.window == nil { return } if let _ = scrollView, let userInfo = notification.userInfo, let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let animationCurve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { UIView.animateWithDuration(animationDuration.doubleValue, delay: 0, options: UIViewAnimationOptions(rawValue: UInt(animationCurve.unsignedLongValue)), animations: { if let scrollView = self.scrollView { if let originalContentSize = self.originalScrollSize { scrollView.contentSize = originalContentSize } if let originalScrollOffset = self.originalScrollOffset { scrollView.setContentOffset( originalScrollOffset, animated: false) } } }, completion: { success in self.originalScrollOffset = nil self.originalScrollSize = nil }) } } }
mit
561c2b437bbbff08384fa7aeca0021c0
45.603659
209
0.568887
6.986289
false
false
false
false
RCacheaux/BitbucketKit
Carthage/Checkouts/Swinject/Sources/SwinjectStoryboard/Container+SwinjectStoryboard.swift
1
2302
// // Container+SwinjectStoryboard.swift // Swinject // // Created by Yoichi Tagaya on 11/28/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // #if os(iOS) || os(OSX) || os(tvOS) extension Container { /// Adds a registration of the specified view or window controller that is configured in a storyboard. /// /// - Note: Do NOT explicitly resolve the controller registered by this method. /// The controller is intended to be resolved by `SwinjectStoryboard` implicitly. /// /// - Parameters: /// - controllerType: The controller type to register as a service type. /// The type is `UIViewController` in iOS, `NSViewController` or `NSWindowController` in OS X. /// - name: A registration name, which is used to differenciate from other registrations /// that have the same view or window controller type. /// - initCompleted: A closure to specifiy how the dependencies of the view or window controller are injected. /// It is invoked by the `Container` when the view or window controller is instantiated by `SwinjectStoryboard`. public func registerForStoryboard<C: Controller>(controllerType: C.Type, name: String? = nil, initCompleted: (ResolverType, C) -> ()) { // Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7. // The actual controller type is distinguished by the dynamic type name in `nameWithActualType`. let nameWithActualType = String(reflecting: controllerType) + ":" + (name ?? "") let wrappingClosure: (ResolverType, Controller) -> () = { r, c in initCompleted(r, c as! C) } self.register(Controller.self, name: nameWithActualType) { (_: ResolverType, controller: Controller) in controller } .initCompleted(wrappingClosure) } } #endif extension Container { #if os(iOS) || os(tvOS) /// The typealias to UIViewController. public typealias Controller = UIViewController #elseif os(OSX) /// The typealias to AnyObject, which should be actually NSViewController or NSWindowController. /// See the reference of NSStoryboard.instantiateInitialController method. public typealias Controller = AnyObject #endif }
apache-2.0
9d7ea5cf5edf5bce1301df0b168b9915
49.021739
139
0.679704
4.773859
false
false
false
false
adamnemecek/SortedArray.swift
Cmdline/main.swift
1
931
// // main.swift // Cmdline // // Created by Adam Nemecek on 5/6/17. // // import Foundation import SortedArray let s = SortedSet([5,2,1,2,3,6,7,8]) let a = [1,2,3,4,5,6] let b = [1, 2, 2, 3, 3, 5, 6] print(b) //var u = UnionIterator(a: a, b: b) { $0 < $1 } //print(s.contains(1)) //while let n = u.next() { // print(n) //} // //struct UniqueSequence<Element : Equatable> : IteratorProtocol { // private var i: AnyIterator<Element> //// // private var last : Element? // // init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element { // self.i = AnyIterator(sequence.makeIterator()) // last = i.next() // } // // func next() -> Element? { // return nil //// while let n = i.next() { //// //// } // } //} let c = SortedSet(b) //let ii = s.intersection(c) //print(s.intersection(c)) for e in s.symmetricDifference(c) { print(e) }
mit
74a3837179a3dd1ff29794093f81f149
17.254902
76
0.538131
2.690751
false
false
false
false
KBryan/SwiftFoundation
Darwin Support/NSUUID.swift
1
1268
// // NSUUID.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/4/15. // Copyright © 2015 PureSwift. All rights reserved. // import Foundation public extension NSUUID { convenience init(byteValue: uuid_t) { var value = byteValue let buffer = withUnsafeMutablePointer(&value, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> UnsafeMutablePointer<UInt8> in let bufferType = UnsafeMutablePointer<UInt8>.self return unsafeBitCast(valuePointer, bufferType) }) self.init(UUIDBytes: buffer) } var byteValue: uuid_t { var uuid = uuid_t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) withUnsafeMutablePointer(&uuid, { (valuePointer: UnsafeMutablePointer<uuid_t>) -> Void in let bufferType = UnsafeMutablePointer<UInt8>.self let buffer = unsafeBitCast(valuePointer, bufferType) self.getUUIDBytes(buffer) }) return uuid } var rawValue: String { return UUIDString } convenience init?(rawValue: String) { self.init(UUIDString: rawValue) } }
mit
1023223f8088c42049b746835267a916
23.365385
134
0.561168
4.891892
false
false
false
false
EstebanVallejo/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/MercadoPago.swift
1
17199
// // MercadoPago.swift // MercadoPagoSDK // // Created by Matias Gualino on 28/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class MercadoPago : NSObject { public class var PUBLIC_KEY : String { return "public_key" } public class var PRIVATE_KEY : String { return "private_key" } public class var ERROR_KEY_CODE : Int { return -1 } public class var ERROR_API_CODE : Int { return -2 } public class var ERROR_UNKNOWN_CODE : Int { return -3 } public class var ERROR_NOT_INSTALLMENTS_FOUND : Int { return -4 } public class var ERROR_PAYMENT : Int { return -4 } let BIN_LENGTH : Int = 6 let MP_API_BASE_URL : String = "https://api.mercadopago.com" public var privateKey : String? public var publicKey : String? public var paymentMethodId : String? public var paymentTypeId : String? public init (publicKey: String) { self.publicKey = publicKey } public init (keyType: String?, key: String?) { if keyType != nil && key != nil { if keyType != MercadoPago.PUBLIC_KEY && keyType != MercadoPago.PRIVATE_KEY { fatalError("keyType must be 'public_key' or 'private_key'.") } else { if keyType == MercadoPago.PUBLIC_KEY { self.publicKey = key } else if keyType == MercadoPago.PUBLIC_KEY { self.privateKey = key } } } else { fatalError("keyType and key cannot be nil.") } } public class func startCustomerCardsViewController(cards: [Card], callback: (selectedCard: Card?) -> Void) -> CustomerCardsViewController { return CustomerCardsViewController(cards: cards, callback: callback) } public class func startNewCardViewController(keyType: String, key: String, paymentMethod: PaymentMethod, requireSecurityCode: Bool, callback: (cardToken: CardToken) -> Void) -> NewCardViewController { return NewCardViewController(keyType: keyType, key: key, paymentMethod: paymentMethod, requireSecurityCode: requireSecurityCode, callback: callback) } public class func startPaymentMethodsViewController(merchantPublicKey: String, supportedPaymentTypes: [String], callback:(paymentMethod: PaymentMethod) -> Void) -> PaymentMethodsViewController { return PaymentMethodsViewController(merchantPublicKey: merchantPublicKey, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public class func startIssuersViewController(merchantPublicKey: String, paymentMethod: PaymentMethod, callback: (issuer: Issuer) -> Void) -> IssuersViewController { return IssuersViewController(merchantPublicKey: merchantPublicKey, paymentMethod: paymentMethod, callback: callback) } public class func startInstallmentsViewController(payerCosts: [PayerCost], amount: Double, callback: (payerCost: PayerCost?) -> Void) -> InstallmentsViewController { return InstallmentsViewController(payerCosts: payerCosts, amount: amount, callback: callback) } public class func startCongratsViewController(payment: Payment, paymentMethod: PaymentMethod) -> CongratsViewController { return CongratsViewController(payment: payment, paymentMethod: paymentMethod) } public class func startPromosViewController(merchantPublicKey: String) -> PromoViewController { return PromoViewController(publicKey: merchantPublicKey) } public class func startVaultViewController(merchantPublicKey: String, merchantBaseUrl: String?, merchantGetCustomerUri: String?, merchantAccessToken: String?, amount: Double, supportedPaymentTypes: [String], callback: (paymentMethod: PaymentMethod, tokenId: String?, issuerId: Int64?, installments: Int) -> Void) -> VaultViewController { return VaultViewController(merchantPublicKey: merchantPublicKey, merchantBaseUrl: merchantBaseUrl, merchantGetCustomerUri: merchantGetCustomerUri, merchantAccessToken: merchantAccessToken, amount: amount, supportedPaymentTypes: supportedPaymentTypes, callback: callback) } public func createNewCardToken(cardToken : CardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { cardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, cardToken: cardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createNewCardToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func createToken(savedCardToken : SavedCardToken, success: (token : Token?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { savedCardToken.device = Device() let service : GatewayService = GatewayService(baseURL: MP_API_BASE_URL) service.getToken(public_key: self.publicKey!, savedCardToken: savedCardToken, success: {(jsonResult: AnyObject?) -> Void in var token : Token? = nil if let tokenDic = jsonResult as? NSDictionary { if tokenDic["error"] == nil { token = Token.fromJSON(tokenDic) success(token: token) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_API_CODE, userInfo: tokenDic as [NSObject : AnyObject])) } } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.createToken", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPaymentMethods(success: (paymentMethods: [PaymentMethod]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getPaymentMethods(public_key: self.publicKey!, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var pms : [PaymentMethod] = [PaymentMethod]() if paymentMethods != nil { for i in 0..<paymentMethods!.count { if let pmDic = paymentMethods![i] as? NSDictionary { pms.append(PaymentMethod.fromJSON(pmDic)) } } } success(paymentMethods: pms) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getPaymentMethods", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIdentificationTypes(success: (identificationTypes: [IdentificationType]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : IdentificationService = IdentificationService(baseURL: MP_API_BASE_URL) service.getIdentificationTypes(public_key: self.publicKey, privateKey: self.privateKey, success: {(jsonResult: AnyObject?) -> Void in if let error = jsonResult as? NSDictionary { if (error["status"]! as? Int) == 404 { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_API_CODE, userInfo: error as [NSObject : AnyObject])) } } } else { var identificationTypesResult = jsonResult as? NSArray? var identificationTypes : [IdentificationType] = [IdentificationType]() if identificationTypesResult != nil { for var i = 0; i < identificationTypesResult!!.count; i++ { if let identificationTypeDic = identificationTypesResult!![i] as? NSDictionary { identificationTypes.append(IdentificationType.fromJSON(identificationTypeDic)) } } } success(identificationTypes: identificationTypes) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getInstallments(bin: String, amount: Double, issuerId: Int64?, paymentTypeId: String, success: (installments: [Installment]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getInstallments(public_key: self.publicKey!, bin: bin, amount: amount, issuer_id: issuerId, payment_type_id: paymentTypeId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var paymentMethods = jsonResult as? NSArray var installments : [Installment] = [Installment]() if paymentMethods != nil && paymentMethods?.count > 0 { if let dic = paymentMethods![0] as? NSDictionary { installments.append(Installment.fromJSON(dic)) } success(installments: installments) } else { var error : NSError = NSError(domain: "mercadopago.sdk.getIdentificationTypes", code: MercadoPago.ERROR_NOT_INSTALLMENTS_FOUND, userInfo: ["message": "NOT_INSTALLMENTS_FOUND".localized + "\(amount)"]) failure?(error: error) } } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getInstallments", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getIssuers(paymentMethodId : String, success: (issuers: [Issuer]?) -> Void, failure: ((error: NSError) -> Void)?) { if self.publicKey != nil { let service : PaymentService = PaymentService(baseURL: MP_API_BASE_URL) service.getIssuers(public_key: self.publicKey!, payment_method_id: paymentMethodId, success: {(jsonResult: AnyObject?) -> Void in if let errorDic = jsonResult as? NSDictionary { if errorDic["error"] != nil { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_API_CODE, userInfo: errorDic as [NSObject : AnyObject])) } } } else { var issuersArray = jsonResult as? NSArray var issuers : [Issuer] = [Issuer]() if issuersArray != nil { for i in 0..<issuersArray!.count { if let issuerDic = issuersArray![i] as? NSDictionary { issuers.append(Issuer.fromJSON(issuerDic)) } } } success(issuers: issuers) } }, failure: failure) } else { if failure != nil { failure!(error: NSError(domain: "mercadopago.sdk.getIssuers", code: MercadoPago.ERROR_KEY_CODE, userInfo: ["message": "Unsupported key type for this method"])) } } } public func getPromos(success: (promos: [Promo]?) -> Void, failure: ((error: NSError) -> Void)?) { // TODO: Está hecho para MLA fijo porque va a cambiar la URL para que dependa de una API y una public key let service : PromosService = PromosService(baseURL: MP_API_BASE_URL) service.getPromos(public_key: self.publicKey!, success: { (jsonResult) -> Void in var promosArray = jsonResult as? NSArray? var promos : [Promo] = [Promo]() if promosArray != nil { for var i = 0; i < promosArray!!.count; i++ { if let promoDic = promosArray!![i] as? NSDictionary { promos.append(Promo.fromJSON(promoDic)) } } } success(promos: promos) }, failure: failure) } public class func isCardPaymentType(paymentTypeId: String) -> Bool { if paymentTypeId == "credit_card" || paymentTypeId == "debit_card" || paymentTypeId == "prepaid_card" { return true } return false } public class func getBundle() -> NSBundle? { var bundle : NSBundle? = nil var privatePath = NSBundle.mainBundle().privateFrameworksPath if privatePath != nil { var path = privatePath!.stringByAppendingPathComponent("MercadoPagoSDK.framework") return NSBundle(path: path) } return nil } public class func getImage(name: String) -> UIImage? { var bundle = getBundle() if (UIDevice.currentDevice().systemVersion as NSString).compare("8.0", options: NSStringCompareOptions.NumericSearch) == NSComparisonResult.OrderedAscending { var nameArr = split(name) {$0 == "."} var imageExtension : String = nameArr[1] var imageName : String = nameArr[0] var filePath = bundle?.pathForResource(name, ofType: imageExtension) if filePath != nil { return UIImage(contentsOfFile: filePath!) } else { return nil } } return UIImage(named:name, inBundle: bundle, compatibleWithTraitCollection:nil) } public class func screenBoundsFixedToPortraitOrientation() -> CGRect { var screenSize : CGRect = UIScreen.mainScreen().bounds if NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 && UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) { return CGRectMake(0.0, 0.0, screenSize.height, screenSize.width) } return screenSize } public class func showAlertViewWithError(error: NSError?, nav: UINavigationController?) { let msgDefault = "An error occurred while processing your request. Please try again." var msg : String? = msgDefault if error != nil { msg = error!.userInfo!["message"] as? String } let alert = UIAlertController() alert.title = "MercadoPago Error" alert.message = "Error = \(msg != nil ? msg! : msgDefault)" alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in switch action.style{ case .Default: nav!.popViewControllerAnimated(true) case .Cancel: println("cancel") case .Destructive: println("destructive") } })) nav!.presentViewController(alert, animated: true, completion: nil) } }
mit
03de915deb85beca28b7b6b05d95b922
45.736413
341
0.589603
5.089672
false
false
false
false
xmartlabs/XLSlidingContainer
Example/Example/ScrollViewController.swift
1
1800
// // ScrollViewController.swift // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import SlidingContainer class ScrollViewController: UIViewController, ContainedViewController { private var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: UIImage(named: "stonehenge")!) let scrollView = UIScrollView() scrollView.addSubview(imageView) scrollView.contentSize = imageView.bounds.size view = scrollView } func didMinimizeControllerWith(diff: CGFloat) { view.alpha = 0.3 } func didMaximizeControllerWith(diff: CGFloat) { view.alpha = 1.0 } }
mit
76c16078fe4dec4f78599e3cf6f925aa
35
80
0.729444
4.675325
false
false
false
false
abdullahselek/SwiftyNotifications
Sample/Sample/ViewController.swift
1
2983
// // ViewController.swift // Sample // // Created by Abdullah Selek on 03/04/2017. // Copyright © 2017 Abdullah Selek. All rights reserved. // import UIKit import SwiftyNotifications class ViewController: UIViewController, SwiftyNotificationsDelegate { private var notification: SwiftyNotifications! private var customNotification: SwiftyNotifications! override func viewDidLoad() { super.viewDidLoad() notification = SwiftyNotifications.withStyle(style: .info, title: "Swifty Notifications", subtitle: "Highly configurable iOS UIView for presenting notifications that doesn't block the UI", direction: .bottom) notification.delegate = self notification.addTouchHandler { } notification.addSwipeGestureRecognizer(direction: .down) view.addSubview(notification) customNotification = SwiftyNotifications.withStyle(style: .custom, title: "Custom", subtitle: "Custom notification with custom image and colors", direction: .top) customNotification.leftAccessoryView.image = UIImage(named: "apple_logo")! customNotification.setCustomColors(backgroundColor: UIColor.cyan, textColor: UIColor.white) view.addSubview(customNotification) } @IBAction func show(_ sender: Any) { notification.show() } @IBAction func dismiss(_ sender: Any) { if customNotification != nil { customNotification.dismiss() } notification.dismiss() } @IBAction func changeStyle(_ sender: Any) { let style = (sender as! UIButton).tag switch style { case 0: notification.customize(style: .normal) break case 1: notification.customize(style: .error) break case 2: notification.customize(style: .success) break case 3: notification.customize(style: .info) break case 4: notification.customize(style: .warning) break case 5: notification.dismiss() customNotification.show() break default: break } } // MARK: SwiftyNotifications Delegates func willShowNotification(notification: UIView) { } func didShowNotification(notification: UIView) { } func willDismissNotification(notification: UIView) { } func didDismissNotification(notification: UIView) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
4ba557ef5e2e6bd0df2cbc38a191927d
27.951456
151
0.57277
5.881657
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/DeviceManagement/CoreDataFixture+MockUserClient.swift
1
1530
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire extension CoreDataFixture { func mockUserClient(fingerprintString: String = "102030405060708090102030405060708090102030405060708090") -> UserClient! { let client = UserClient.insertNewObject(in: uiMOC) client.remoteIdentifier = "102030405060708090" client.user = ZMUser.insertNewObject(in: uiMOC) client.deviceClass = .tablet client.model = "Simulator" client.label = "Bill's MacBook Pro" let fingerprint: Data? = fingerprintString.data(using: .utf8) client.fingerprint = fingerprint let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd HH:mm" let activationDate = formatter.date(from: "2016/05/01 14:31") client.activationDate = activationDate return client } }
gpl-3.0
a3410644d49cd1688a58e23709109c7c
33.772727
126
0.711111
4.409222
false
false
false
false
novi/i2c-swift-example
Sources/I2CDeviceModule/SHT21.swift
1
1397
// // SHT21.swift // I2CDeviceModule // // Created by Yusuke Ito on 3/1/17. // Copyright © 2017 Yusuke Ito. All rights reserved. // import Foundation import I2C public final class SHT21 { public let address: UInt8 public let device: I2CDevice public init(device: I2CDevice, address: UInt8 = 0x40) { self.device = device self.address = address } } fileprivate extension SHT21 { enum Command: UInt8 { case mesureHoldT = 0xe3 case mesureHoldRH = 0xe5 case reset = 0xfe } func sendAndRead(command: Command, readByte: UInt32) throws -> [UInt8] { return try device.write(toAddress: address, data: [command.rawValue], readBytes: readByte) } func send(command: Command) throws -> UInt16 { let data = try sendAndRead(command: command, readByte: 3) let value: UInt16 = (UInt16(data[0]) << 8) | UInt16(data[1] & 0xfc) return value } } public extension SHT21 { func reset() throws { _ = try sendAndRead(command: .reset, readByte: 0) } func mesureTemperature() throws -> Double { let val = Double(try send(command: .mesureHoldT)) return -46.85 + (175.72 * val / 65536) } func mesureRH() throws -> Double { let val = Double(try send(command: .mesureHoldRH)) return -6 + (125 * val / 65536) } }
mit
6647d0ed733129788e5abfb9c1537916
23.491228
98
0.606017
3.607235
false
false
false
false
HasanEdain/NPCColorPicker
NPCColorPicker/NPCPaleteUtility.swift
1
4578
// // NPCPaleteUtility.swift // NPCColorPicker // // Created by Hasan D Edain and Andrew Bush on 12/6/15. // Copyright © 2015-2017 NPC Unlimited. All rights reserved. // import UIKit open class NPCPaleteUtility { open static func twelveColorWheel()->[UIColor] { let colorArray = [NPCColorUtility.colorWithHex("fe7923"), NPCColorUtility.colorWithHex("fd0d1b"), NPCColorUtility.colorWithHex("bf1698"), NPCColorUtility.colorWithHex("941abe"), NPCColorUtility.colorWithHex("6819bd"), NPCColorUtility.colorWithHex("1024fc"), NPCColorUtility.colorWithHex("1ec0a8"), NPCColorUtility.colorWithHex("1dbb20"), NPCColorUtility.colorWithHex("c7f131"), NPCColorUtility.colorWithHex("e8ea34"), NPCColorUtility.colorWithHex("fad931"), NPCColorUtility.colorWithHex("feb92b")] return colorArray } open static func colorArrayWithRGBAStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithRGBA(hexString) colorArray.append(color) } return colorArray } open static func colorArrayWithHexStringArray(_ hexStringArray: [String]) -> [UIColor] { var colorArray = [UIColor]() for hexString in hexStringArray { let color = NPCColorUtility.colorWithHex(hexString) colorArray.append(color) } return colorArray } // These colors are specified in #ffffffff Hexidecimal form open static func colorArrayWithGradient(_ startColor: String, endColor: String, steps: Int) -> [UIColor] { var colorArray = [UIColor]() let startRed = NPCColorUtility.redPercentForHexString(startColor as NSString) let startGreen = NPCColorUtility.greenPercentForHexString(startColor as NSString) let startBlue = NPCColorUtility.bluePercentForHexString(startColor as NSString) let startAlpha = NPCColorUtility.alphaPercentForHexString(startColor as NSString) let endRed = NPCColorUtility.redPercentForHexString(endColor as NSString) let endGreen = NPCColorUtility.greenPercentForHexString(endColor as NSString) let endBlue = NPCColorUtility.bluePercentForHexString(endColor as NSString) let endAlpha = NPCColorUtility.alphaPercentForHexString(endColor as NSString) let redDelta = -1 * (startRed - endRed) let greenDelta = -1 * (startGreen - endGreen) let blueDelta = -1 * (startBlue - endBlue) let alphaDelta = -1 * (startAlpha - endAlpha) var redIncrement:CGFloat = 0.0 if steps > 0 && redDelta != 0 { redIncrement = redDelta / CGFloat(steps) } var greenIncrement: CGFloat = 0.0 if steps > 0 && greenDelta != 0 { greenIncrement = greenDelta / CGFloat(steps) } var blueIncrement: CGFloat = 0.0 if steps > 0 && blueDelta != 0 { blueIncrement = blueDelta / CGFloat(steps) } var alphaIncrement: CGFloat = 0.0 if steps > 0 && alphaDelta != 0 { alphaIncrement = alphaDelta / CGFloat(steps) } for step in 1...steps { let red = startRed + (redIncrement * CGFloat(step)) let green = startGreen + (greenIncrement * CGFloat(step)) let blue = startBlue + (blueIncrement * CGFloat(step)) let alpha = startAlpha + (alphaIncrement * CGFloat(step)) let color = UIColor(red: red, green: green, blue: blue, alpha: alpha) colorArray.append(color) } return colorArray } open static func colorArrayWithColorStringArray(_ colorStrings: [String], steps: Int)->[UIColor] { if colorStrings.count <= 0 { return [UIColor.white] } else if colorStrings.count == 1 { return NPCPaleteUtility.colorArrayWithGradient(colorStrings[0], endColor: "ffffff", steps: steps) } else { var gradients = [UIColor]() for index in 1...(colorStrings.count - 1){ let start = colorStrings[index - 1] let end = colorStrings[index] var gradient = NPCPaleteUtility.colorArrayWithGradient(start, endColor: end, steps: steps) if index > 1 { gradient.removeFirst() } gradients.append(contentsOf: gradient) } return gradients } } }
mit
a3df61595c574825edbf2506c1150447
36.211382
110
0.629233
4.884739
false
false
false
false
ByteriX/BxInputController
BxInputController/Sources/Rows/Boolean/View/BxInputCheckRowBinder.swift
1
1126
/** * @file BxInputCheckRowBinder.swift * @namespace BxInputController * * @details Binder for check box row subclasses * @date 17.03.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Binder for check box Row subclasses open class BxInputCheckRowBinder<Row : BxInputCheckRow, Cell>: BxInputStandartTextRowBinder<Row, Cell> where Cell : UITableViewCell, Cell : BxInputFieldCell { /// call when user selected this cell override open func didSelected() { super.didSelected() owner?.dissmissAllRows() row.value = !row.value didChangeValue() update() } /// call after common update for text attributes updating override open func updateCell() { cell?.valueTextField.isEnabled = false cell?.valueTextField.text = "" cell?.accessoryType = row.value ? .checkmark : .none cell?.selectionStyle = .default } }
mit
4524d134178bdc3d45cd42285ff23c16
27.871795
102
0.674067
4.217228
false
false
false
false
LunaGao/cnblogs-Mac-Swift
CNBlogsForMac/WebApi/BaseWebApi.swift
1
1904
// // BaseWebApi.swift // CNBlogsForMac // // Created by Luna Gao on 15/11/16. // Copyright © 2015年 gao.luna.com. All rights reserved. // import Foundation class BaseWebApi : NSObject { func basicRequest(callback:(String?)->Void){ let basicAuth = "Basic 这个值是根据ClientId和ClientSercret计算得来,这里隐藏" let urlstr = "https://api.cnblogs.com/token" let url = NSURL(string: urlstr) let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.addValue(basicAuth, forHTTPHeaderField: "Authorization") let op:NSOperationQueue = NSOperationQueue.mainQueue() request.HTTPBody = "grant_type=client_credentials".dataUsingEncoding(NSUTF8StringEncoding) //通过NSURLConnection发送请求 NSURLConnection.sendAsynchronousRequest(request, queue: op) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in //异步处理 dispatch_async(dispatch_get_main_queue(), { () -> Void in do { let jsonValue: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) if let statusesArray = jsonValue as? NSDictionary{ // NSLog("%@",statusesArray) if let aStatus = statusesArray["access_token"] as? String{ callback(aStatus) } else { callback(nil) } } } catch { callback(nil) } // NSLog("%@", String.init(data: data!, encoding: NSUTF8StringEncoding)!) }) } } } //同步处理 // dispatch_sync(dispatch_get_main_queue(), { () -> Void in // // })
mit
f60ff12f936f92dc73c4c8c7b585015c
33.735849
142
0.555676
4.672589
false
false
false
false
q231950/appwatch
AppWatch/ViewControllers/TimeTableViewController.swift
1
1268
// // TimeTableViewController.swift // AppWatch // // Created by Martin Kim Dung-Pham on 25.08.15. // Copyright © 2015 Martin Kim Dung-Pham. All rights reserved. // import AppKit class TimeTableViewController: NSViewController { @IBOutlet weak var collectionView: NSCollectionView! override func viewDidLoad() { super.viewDidLoad() // collectionView.content = ["hu", "lu"] // collectionView.itemPrototype = storyboard!.instantiateControllerWithIdentifier("collectionViewItem") as? NSCollectionViewItem } // func numberOfSectionsInCollectionView(collectionView: NSCollectionView) -> Int { // return 1 // } // // func collectionView(collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { // return 4 // } // // func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem { // // let item: NSCollectionViewItem // if let i = collectionView.itemAtIndexPath(indexPath) { // item = i // } else { // item = collectionView.newItemForRepresentedObject("hulu") // } // // return item // } // // }
mit
f58453514cd32b3c8d5c19ddc6cdce77
28.465116
145
0.648777
4.727612
false
false
false
false
praca-japao/156
PMC156Inteligente/MyProfileTableViewController.swift
1
3269
// // MyProfileTableViewController.swift // PMC156Inteligente // // Created by Giovanni Pietrangelo on 11/29/15. // Copyright © 2015 Sigma Apps. All rights reserved. // import UIKit class MyProfileTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
a4c6d543bbda53199ba57cdbef76256a
33.4
157
0.690024
5.576792
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift
1
5571
// // ImageDataProvider.swift // Kingfisher // // Created by onevcat on 2018/11/13. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// Represents a data provider to provide image data to Kingfisher when setting with /// `Source.provider` source. Compared to `Source.network` member, it gives a chance /// to load some image data in your own way, as long as you can provide the data /// representation for the image. public protocol ImageDataProvider { /// The key used in cache. var cacheKey: String { get } /// Provides the data which represents image. Kingfisher uses the data you pass in the /// handler to process images and caches it for later use. /// /// - Parameter handler: The handler you should call when you prepared your data. /// If the data is loaded successfully, call the handler with /// a `.success` with the data associated. Otherwise, call it /// with a `.failure` and pass the error. /// /// - Note: /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError` /// from the framework. func data(handler: @escaping (Result<Data, Error>) -> Void) } /// Represents an image data provider for loading from a local file URL on disk. /// Uses this type for adding a disk image to Kingfisher. Compared to loading it /// directly, you can get benefit of using Kingfisher's extension methods, as well /// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher. public struct LocalFileImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The file URL from which the image be loaded. public let fileURL: URL // MARK: Initializers /// Creates an image data provider by supplying the target local file URL. /// /// - Parameters: /// - fileURL: The file URL from which the image be loaded. /// - cacheKey: The key is used for caching the image data. By default, /// the `absoluteString` of `fileURL` is used. public init(fileURL: URL, cacheKey: String? = nil) { self.fileURL = fileURL self.cacheKey = cacheKey ?? fileURL.absoluteString } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { handler( Result { try Data(contentsOf: fileURL) } ) } } /// Represents an image data provider for loading image from a given Base64 encoded string. public struct Base64ImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The encoded Base64 string for the image. public let base64String: String // MARK: Initializers /// Creates an image data provider by supplying the Base64 encoded string. /// /// - Parameters: /// - base64String: The Base64 encoded string for an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(base64String: String, cacheKey: String) { self.base64String = base64String self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: (Result<Data, Error>) -> Void) { let data = Data(base64Encoded: base64String)! handler(.success(data)) } } /// Represents an image data provider for a raw data object. public struct RawImageDataProvider: ImageDataProvider { // MARK: Public Properties /// The raw data object to provide to Kingfisher image loader. public let data: Data // MARK: Initializers /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache. /// /// - Parameters: /// - data: The raw data reprensents an image. /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. public init(data: Data, cacheKey: String) { self.data = data self.cacheKey = cacheKey } // MARK: Protocol Conforming /// The key used in cache. public var cacheKey: String public func data(handler: @escaping (Result<Data, Error>) -> Void) { handler(.success(data)) } }
mit
968c0e7519d64e9a12ef46d66b5dff30
37.42069
115
0.680129
4.496368
false
false
false
false
therealbnut/swift
stdlib/public/SDK/Foundation/NSString.swift
9
4420
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module //===----------------------------------------------------------------------===// // Strings //===----------------------------------------------------------------------===// @available(*, unavailable, message: "Please use String or NSString") public class NSSimpleCString {} @available(*, unavailable, message: "Please use String or NSString") public class NSConstantString {} @_silgen_name("swift_convertStringToNSString") public // COMPILER_INTRINSIC func _convertStringToNSString(_ string: String) -> NSString { return string._bridgeToObjectiveC() } extension NSString : ExpressibleByStringLiteral { /// Create an instance initialized to `value`. public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init( extendedGraphemeClusterLiteral value: StaticString ) { self.init(stringLiteral: value) } /// Create an instance initialized to `value`. public required convenience init(stringLiteral value: StaticString) { var immutableResult: NSString if value.hasPointerRepresentation { immutableResult = NSString( bytesNoCopy: UnsafeMutableRawPointer(mutating: value.utf8Start), length: Int(value.utf8CodeUnitCount), encoding: value.isASCII ? String.Encoding.ascii.rawValue : String.Encoding.utf8.rawValue, freeWhenDone: false)! } else { var uintValue = value.unicodeScalar immutableResult = NSString( bytes: &uintValue, length: 4, encoding: String.Encoding.utf32.rawValue)! } self.init(string: immutableResult as String) } } extension NSString : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to prevent infinite recursion trying to bridge // AnyHashable to NSObject. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { // Consistently use Swift equality and hashing semantics for all strings. return AnyHashable(self as String) } } extension NSString { public convenience init(format: NSString, _ args: CVarArg...) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, arguments: va_args) } public convenience init( format: NSString, locale: Locale?, _ args: CVarArg... ) { // We can't use withVaList because 'self' cannot be captured by a closure // before it has been initialized. let va_args = getVaList(args) self.init(format: format as String, locale: locale, arguments: va_args) } public class func localizedStringWithFormat( _ format: NSString, _ args: CVarArg... ) -> Self { return withVaList(args) { self.init(format: format as String, locale: Locale.current, arguments: $0) } } public func appendingFormat(_ format: NSString, _ args: CVarArg...) -> NSString { return withVaList(args) { self.appending(NSString(format: format as String, arguments: $0) as String) as NSString } } } extension NSMutableString { public func appendFormat(_ format: NSString, _ args: CVarArg...) { return withVaList(args) { self.append(NSString(format: format as String, arguments: $0) as String) } } } extension NSString { /// Returns an `NSString` object initialized by copying the characters /// from another given string. /// /// - Returns: An `NSString` object initialized by copying the /// characters from `aString`. The returned object may be different /// from the original receiver. @nonobjc public convenience init(string aString: NSString) { self.init(string: aString as String) } } extension NSString : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(self as String) } }
apache-2.0
2d7638467eddfa465fb0cb69a0bba20e
32.740458
97
0.659955
4.851811
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Presenter Tests/Dealer Detail/Presenter Tests/WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould.swift
1
1348
@testable import Eurofurence import EurofurenceModel import XCTest class WhenBindingAboutTheArtistComponent_DealerDetailPresenterShould: XCTestCase { func testBindTheArtistDescriptionOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.artistDescription, context.boundAboutTheArtistComponent?.capturedArtistDescription) } func testBindTheTitleOntoTheComponent() { let aboutTheArtistViewModel = DealerDetailAboutTheArtistViewModel.random let viewModel = FakeDealerDetailAboutTheArtistViewModel(aboutTheArtist: aboutTheArtistViewModel) let interactor = FakeDealerDetailInteractor(viewModel: viewModel) let context = DealerDetailPresenterTestBuilder().with(interactor).build() context.simulateSceneDidLoad() context.bindComponent(at: 0) XCTAssertEqual(aboutTheArtistViewModel.title, context.boundAboutTheArtistComponent?.capturedTitle) } }
mit
e76b55b76698623a595eea851280ea45
45.482759
130
0.793027
6.912821
false
true
false
false
grandiere/box
box/Metal/Texture/MetalTexture.swift
1
1392
import UIKit import MetalKit class MetalTexture { let totalFrames:Int var currentFrame:Int private var frameTick:Int private let frames:[MTLTexture] private let ticksPerFrame:Int init( ticksPerFrame:Int, images:[UIImage], textureLoader:MTKTextureLoader) { self.ticksPerFrame = ticksPerFrame currentFrame = 0 frameTick = 0 var frames:[MTLTexture] = [] for image:UIImage in images { guard let texture:MTLTexture = textureLoader.loadImage(image:image) else { continue } frames.append(texture) } self.frames = frames totalFrames = frames.count } //MARK: public func changeFrame() { } //MARK final final func current() -> MTLTexture? { if totalFrames < 1 { return nil } frameTick += 1 if frameTick >= ticksPerFrame { frameTick = 0 changeFrame() } let texture:MTLTexture = frames[currentFrame] return texture } final func restart() { currentFrame = 0 frameTick = 0 } }
mit
cddadf31969df21e35d795e9584c88dd
17.810811
77
0.475575
5.8
false
false
false
false
serieuxchat/SwiftySRP
SwiftySRP/SRPData+BigIntType.swift
1
9367
// // SRPData+BigIntType.swift // SwiftySRP // // Created by Sergey A. Novitsky on 20/03/2017. // Copyright © 2017 Flock of Files. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation /// Internal extension to short-circuit conversions between Data and BigIntType extension SRPData { // Client specific data /// Password hash 'x' (see SRP spec. in SRPProtocol.swift) func bigInt_x<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._x } return BigIntType(passwordHash) } /// Client private value 'a' (see SRP spec. in SRPProtocol.swift) func bigInt_a<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._a } return BigIntType(clientPrivateValue) } /// Client public value 'A' (see SRP spec. in SRPProtocol.swift) func bigInt_A<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._A } return BigIntType(clientPublicValue) } /// Client evidence message, computed as: M = H( pA | pB | pS), where pA, pB, and pS - padded values of A, B, and S (see SRP spec. in SRPProtocol.swift) func bigInt_clientM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientM } return BigIntType(clientEvidenceMessage) } mutating func setBigInt_clientM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientM = newValue self = impl as! Self } else { clientEvidenceMessage = newValue.serialize() } } /// Server evidence message, computed as: M = H( pA | pMc | pS), where pA is the padded A value; pMc is the padded client evidence message, and pS is the padded shared secret. (see SRP spec. in SRPProtocol.swift) func bigInt_serverM<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverM } return BigIntType(serverEvidenceMessage) } mutating func setBigInt_serverM<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverM = newValue self = impl as! Self } else { serverEvidenceMessage = newValue.serialize() } } // Common data: /// SRP Verifier 'v' (see SRP spec. in SRPProtocol.swift) func bigInt_v<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._v } return BigIntType(verifier) } mutating func setBigInt_v<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._v = newValue self = impl as! Self } else { self.verifier = newValue.serialize() } } // Scrambler parameter 'u'. u = H(A, B) (see SRP spec. in SRPProtocol.swift) func bigInt_u<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._u } return BigIntType(scrambler) } mutating func setBigInt_u<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._u = newValue self = impl as! Self } else { self.scrambler = newValue.serialize() } } /// Shared secret 'S' . Computed on the client as: S = (B - kg^x) ^ (a + ux) (see SRP spec. in SRPProtocol.swift) func bigInt_clientS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._clientS } return BigIntType(clientSecret) } mutating func setBigInt_clientS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._clientS = newValue self = impl as! Self } else { self.clientSecret = newValue.serialize() } } /// Shared secret 'S'. Computed on the server as: S = (Av^u) ^ b (see SRP spec. in SRPProtocol.swift) func bigInt_serverS<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._serverS } return BigIntType(serverSecret) } mutating func setBigInt_serverS<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._serverS = newValue self = impl as! Self } else { self.serverSecret = newValue.serialize() } } // Server specific data /// Multiplier parameter 'k'. Computed as: k = H(N, g) (see SRP spec. in SRPProtocol.swift) func bigInt_k<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._k } return BigIntType(multiplier) } mutating func setBigInt_k<BigIntType: SRPBigIntProtocol>(_ newValue: BigIntType) { // Short-circuit conversions between Data and BigIntType if possible if var impl = self as? SRPDataGenericImpl<BigIntType> { impl._k = newValue self = impl as! Self } else { self.multiplier = newValue.serialize() } } /// Server private value 'b' (see SRP spec. in SRPProtocol.swift) func bigInt_b<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._b } return BigIntType(serverPrivateValue) } /// Server public value 'B' (see SRP spec. in SRPProtocol.swift) func bigInt_B<BigIntType: SRPBigIntProtocol>() -> BigIntType { // Short-circuit conversions between Data and BigIntType if possible if let impl = self as? SRPDataGenericImpl<BigIntType> { return impl._B } return BigIntType(serverPublicValue) } }
mit
0ffc35fd5a580d9ccd033be597b69b8b
33.307692
216
0.623425
5.008556
false
false
false
false
tokyovigilante/CesiumKit
CesiumKit/Core/EllipsoidGeodesic.swift
1
14805
// // EllipsoidGeodesic.swift // CesiumKit // // Created by Ryan Walklin on 2/11/2015. // Copyright © 2015 Test Toast. All rights reserved. // import Foundation /** * Initializes a geodesic on the ellipsoid connecting the two provided planetodetic points. * * @alias EllipsoidGeodesic * @constructor * * @param {Cartographic} [start] The initial planetodetic point on the path. * @param {Cartographic} [end] The final planetodetic point on the path. * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the geodesic lies. */ class EllipsoidGeodesic { /** * Gets the ellipsoid. * @memberof EllipsoidGeodesic.prototype * @type {Ellipsoid} * @readonly */ let ellipsoid: Ellipsoid /** * Gets the initial planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var start: Cartographic? = nil /** * Gets the final planetodetic point on the path. * @memberof EllipsoidGeodesic.prototype * @type {Cartographic?} * @readonly */ fileprivate (set) var end: Cartographic? = nil /** * Gets the heading at the initial point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var startHeading: Double { assert(_distance != nil, "set end positions before getting startHeading") return _startHeading! } fileprivate var _startHeading: Double? = nil /** * Gets the heading at the final point. * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var endHeading: Double { assert(_distance != nil, "set end positions before getting endHeading") return _endHeading! } fileprivate var _endHeading: Double? = nil /** * Gets the surface distance between the start and end point * @memberof EllipsoidGeodesic.prototype * @type {Number} * @readonly */ var surfaceDistance: Double { assert(_distance != nil, "set end positions before getting surfaceDistance") return _distance! } fileprivate var _distance: Double? = nil fileprivate var _uSquared: Double? = nil fileprivate var _constants = EllipsoidGeodesicConstants() init (start: Cartographic? = nil, end: Cartographic? = nil, ellipsoid: Ellipsoid = Ellipsoid.wgs84) { self.ellipsoid = ellipsoid if start != nil && end != nil { computeProperties(start: start!, end: end!) } } /** * Sets the start and end points of the geodesic * * @param {Cartographic} start The initial planetodetic point on the path. * @param {Cartographic} end The final planetodetic point on the path. */ func setEndPoints (start: Cartographic, end: Cartographic) { computeProperties(start: start, end: end) } fileprivate func computeProperties(start: Cartographic, end: Cartographic) { let firstCartesian = ellipsoid.cartographicToCartesian(start).normalize() let lastCartesian = ellipsoid.cartographicToCartesian(end).normalize() assert(abs(abs(firstCartesian.angle(between: lastCartesian)) - .pi) >= 0.0125, "geodesic position is not unique") vincentyInverseFormula(major: ellipsoid.maximumRadius, minor: ellipsoid.minimumRadius, firstLongitude: start.longitude, firstLatitude: start.latitude, secondLongitude: end.longitude, secondLatitude: end.latitude) var surfaceStart = start var surfaceEnd = end surfaceStart.height = 0 surfaceEnd.height = 0 self.start = surfaceStart self.end = surfaceEnd setConstants() } fileprivate func vincentyInverseFormula(major: Double, minor: Double, firstLongitude: Double, firstLatitude: Double, secondLongitude: Double, secondLatitude: Double) { let eff = (major - minor) / major let l = secondLongitude - firstLongitude let u1 = atan((1 - eff) * tan(firstLatitude)) let u2 = atan((1 - eff) * tan(secondLatitude)) let cosineU1 = cos(u1) let sineU1 = sin(u1) let cosineU2 = cos(u2) let sineU2 = sin(u2) let cc = cosineU1 * cosineU2 let cs = cosineU1 * sineU2 let ss = sineU1 * sineU2 let sc = sineU1 * cosineU2 var lambda = l var lambdaDot = M_2_PI var cosineLambda = cos(lambda) var sineLambda = sin(lambda) var sigma: Double var cosineSigma: Double var sineSigma: Double var cosineSquaredAlpha: Double var cosineTwiceSigmaMidpoint: Double repeat { cosineLambda = cos(lambda) sineLambda = sin(lambda) let temp = cs - sc * cosineLambda sineSigma = sqrt(cosineU2 * cosineU2 * sineLambda * sineLambda + temp * temp) cosineSigma = ss + cc * cosineLambda sigma = atan2(sineSigma, cosineSigma) let sineAlpha: Double if sineSigma == 0.0 { sineAlpha = 0.0 cosineSquaredAlpha = 1.0 } else { sineAlpha = cc * sineLambda / sineSigma cosineSquaredAlpha = 1.0 - sineAlpha * sineAlpha } lambdaDot = lambda cosineTwiceSigmaMidpoint = cosineSigma - 2.0 * ss / cosineSquaredAlpha; if cosineTwiceSigmaMidpoint.isNaN { cosineTwiceSigmaMidpoint = 0.0 } lambda = l + computeDeltaLambda(eff, sineAlpha: sineAlpha, cosineSquaredAlpha: cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) } while (abs(lambda - lambdaDot) > Math.Epsilon12) let uSquared = cosineSquaredAlpha * (major * major - minor * minor) / (minor * minor) let A = 1.0 + uSquared * (4096.0 + uSquared * (uSquared * (320.0 - 175.0 * uSquared) - 768.0)) / 16384.0 let B = uSquared * (256.0 + uSquared * (uSquared * (74.0 - 47.0 * uSquared) - 128.0)) / 1024.0 let cosineSquaredTwiceSigmaMidpoint = cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint; let deltaSigma = B * sineSigma * (cosineTwiceSigmaMidpoint + B * (cosineSigma * (2.0 * cosineSquaredTwiceSigmaMidpoint - 1.0) - B * cosineTwiceSigmaMidpoint * (4.0 * sineSigma * sineSigma - 3.0) * (4.0 * cosineSquaredTwiceSigmaMidpoint - 3.0) / 6.0) / 4.0); _distance = minor * A * (sigma - deltaSigma) _startHeading = atan2(cosineU2 * sineLambda, cs - sc * cosineLambda) _endHeading = atan2(cosineU1 * sineLambda, cs * cosineLambda - sc) _uSquared = uSquared } fileprivate func setConstants() { let a = ellipsoid.maximumRadius let b = ellipsoid.minimumRadius let f = (a - b) / a let cosineHeading = cos(startHeading) let sineHeading = sin(startHeading) let tanU = (1 - f) * tan(start!.latitude) let cosineU = 1.0 / sqrt(1.0 + tanU * tanU) let sineU = cosineU * tanU let sigma = atan2(tanU, cosineHeading) let sineAlpha = cosineU * sineHeading let sineSquaredAlpha = sineAlpha * sineAlpha let cosineSquaredAlpha = 1.0 - sineSquaredAlpha let cosineAlpha = sqrt(cosineSquaredAlpha) let u2Over4 = _uSquared! / 4.0 let u4Over16 = u2Over4 * u2Over4 let u6Over64 = u4Over16 * u2Over4 let u8Over256 = u4Over16 * u4Over16 let a0: Double = (1.0 + u2Over4 - 3.0 * u4Over16 / 4.0 + 5.0 * u6Over64 / 4.0 - 175.0 * u8Over256 / 64.0) let a1: Double = (1.0 - u2Over4 + 15.0 * u4Over16 / 8.0 - 35.0 * u6Over64 / 8.0) let a2: Double = (1.0 - 3.0 * u2Over4 + 35.0 * u4Over16 / 4.0) let a3: Double = (1.0 - 5.0 * u2Over4) // FIXME: Compiler //let distanceRatio0 = a0 * sigma - a1 * sin(2.0 * sigma) * u2Over4 / 2.0 - a2 * sin(4.0 * sigma) * u4Over16 / 16.0 - a3 * sin(6.0 * sigma) * u6Over64 / 48.0 - sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let dr0 = a0 * sigma let dr1 = a1 * sin(2.0 * sigma) * u2Over4 / 2.0 let dr2 = a2 * sin(4.0 * sigma) * u4Over16 / 16.0 let dr3 = a3 * sin(6.0 * sigma) * u6Over64 / 48.0 let dr4 = sin(8.0 * sigma) * 5.0 * u8Over256 / 512 let distanceRatio = dr0 - dr1 - dr2 - dr3 - dr4 _constants.a = a _constants.b = b _constants.f = f _constants.cosineHeading = cosineHeading _constants.sineHeading = sineHeading _constants.tanU = tanU _constants.cosineU = cosineU _constants.sineU = sineU _constants.sigma = sigma _constants.sineAlpha = sineAlpha _constants.sineSquaredAlpha = sineSquaredAlpha _constants.cosineSquaredAlpha = cosineSquaredAlpha _constants.cosineAlpha = cosineAlpha _constants.u2Over4 = u2Over4 _constants.u4Over16 = u4Over16 _constants.u6Over64 = u6Over64 _constants.u8Over256 = u8Over256 _constants.a0 = a0 _constants.a1 = a1 _constants.a2 = a2 _constants.a3 = a3 _constants.distanceRatio = distanceRatio } fileprivate func computeDeltaLambda(_ f: Double, sineAlpha: Double, cosineSquaredAlpha: Double, sigma: Double, sineSigma: Double, cosineSigma: Double, cosineTwiceSigmaMidpoint: Double) -> Double { let C = computeC(f, cosineSquaredAlpha: cosineSquaredAlpha) return (1.0 - C) * f * sineAlpha * (sigma + C * sineSigma * (cosineTwiceSigmaMidpoint + C * cosineSigma * (2.0 * cosineTwiceSigmaMidpoint * cosineTwiceSigmaMidpoint - 1.0))) } fileprivate func computeC(_ f: Double, cosineSquaredAlpha: Double) -> Double { return f * cosineSquaredAlpha * (4.0 + f * (4.0 - 3.0 * cosineSquaredAlpha)) / 16.0 } /** * Provides the location of a point at the indicated portion along the geodesic. * * @param {Number} fraction The portion of the distance between the initial and final points. * @returns {Cartographic} The location of the point along the geodesic. */ func interpolate (fraction: Double) -> Cartographic { assert(fraction >= 0.0 && fraction <= 1.0, "fraction out of bounds") assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") return interpolate(surfaceDistance: _distance! * fraction) } /** * Provides the location of a point at the indicated distance along the geodesic. * * @param {Number} distance The distance from the inital point to the point of interest along the geodesic * @returns {Cartographic} The location of the point along the geodesic. * * @exception {DeveloperError} start and end must be set before calling funciton interpolateUsingSurfaceDistance */ func interpolate (surfaceDistance distance: Double) -> Cartographic { assert(_distance != nil, "start and end must be set before calling funciton interpolateUsingSurfaceDistance") let constants = _constants let s = constants.distanceRatio + distance / constants.b let cosine2S = cos(2.0 * s) let cosine4S = cos(4.0 * s) let cosine6S = cos(6.0 * s) let sine2S = sin(2.0 * s) let sine4S = sin(4.0 * s) let sine6S = sin(6.0 * s) let sine8S = sin(8.0 * s) let s2 = s * s; let s3 = s * s2; let u8Over256 = constants.u8Over256 let u2Over4 = constants.u2Over4 let u6Over64 = constants.u6Over64 let u4Over16 = constants.u4Over16 var sigma = 2.0 * s3 * u8Over256 * cosine2S / 3.0 + s * (1.0 - u2Over4 + 7.0 * u4Over16 / 4.0 - 15.0 * u6Over64 / 4.0 + 579.0 * u8Over256 / 64.0 - (u4Over16 - 15.0 * u6Over64 / 4.0 + 187.0 * u8Over256 / 16.0) * cosine2S - (5.0 * u6Over64 / 4.0 - 115.0 * u8Over256 / 16.0) * cosine4S - 29.0 * u8Over256 * cosine6S / 16.0) + (u2Over4 / 2.0 - u4Over16 + 71.0 * u6Over64 / 32.0 - 85.0 * u8Over256 / 16.0) * sine2S + (5.0 * u4Over16 / 16.0 - 5.0 * u6Over64 / 4.0 + 383.0 * u8Over256 / 96.0) * sine4S - s2 * ((u6Over64 - 11.0 * u8Over256 / 2.0) * sine2S + 5.0 * u8Over256 * sine4S / 2.0) + (29.0 * u6Over64 / 96.0 - 29.0 * u8Over256 / 16.0) * sine6S + 539.0 * u8Over256 * sine8S / 1536.0; let theta = asin(sin(sigma) * constants.cosineAlpha) let latitude = atan(constants.a / constants.b * tan(theta)) // Redefine in terms of relative argument of latitude. sigma = sigma - constants.sigma let cosineTwiceSigmaMidpoint = cos(2.0 * constants.sigma + sigma) let sineSigma = sin(sigma) let cosineSigma = cos(sigma) let cc = constants.cosineU * cosineSigma; let ss = constants.sineU * sineSigma; let lambda = atan2(sineSigma * constants.sineHeading, cc - ss * constants.cosineHeading) let l = lambda - computeDeltaLambda(constants.f, sineAlpha: constants.sineAlpha, cosineSquaredAlpha: constants.cosineSquaredAlpha, sigma: sigma, sineSigma: sineSigma, cosineSigma: cosineSigma, cosineTwiceSigmaMidpoint: cosineTwiceSigmaMidpoint) return Cartographic(longitude: start!.longitude + l, latitude: latitude, height: 0.0) } fileprivate struct EllipsoidGeodesicConstants { var a = Double.nan var b = Double.nan var f = Double.nan var cosineHeading = Double.nan var sineHeading = Double.nan var tanU = Double.nan var cosineU = Double.nan var sineU = Double.nan var sigma = Double.nan var sineAlpha = Double.nan var sineSquaredAlpha = Double.nan var cosineSquaredAlpha = Double.nan var cosineAlpha = Double.nan var u2Over4 = Double.nan var u4Over16 = Double.nan var u6Over64 = Double.nan var u8Over256 = Double.nan var a0 = Double.nan var a1 = Double.nan var a2 = Double.nan var a3 = Double.nan var distanceRatio = Double.nan } }
apache-2.0
b0b90ae8d322df29746dac6160cefefb
37.855643
208
0.596663
4.13058
false
false
false
false
3drobotics/SwiftIO
Sources/UDPChannel.swift
1
9242
// // UDPMavlinkReceiver.swift // SwiftIO // // Created by Jonathan Wight on 4/22/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Darwin import Dispatch import SwiftUtilities /** * A GCD based UDP listener. */ public class UDPChannel { public enum PreconditionError: ErrorType { case QueueSuspended case QueueNotExist } public let label: String? public let address: Address public var readHandler: (Datagram -> Void)? = loggingReadHandler public var errorHandler: (ErrorType -> Void)? = loggingErrorHandler private var resumed: Bool = false private let receiveQueue: dispatch_queue_t! private let sendQueue: dispatch_queue_t! private var source: dispatch_source_t! public private(set) var socket: Socket! public var configureSocket: (Socket -> Void)? // MARK: - Initialization public init(label: String? = nil, address: Address, qos: dispatch_qos_class_t = QOS_CLASS_DEFAULT, readHandler: (Datagram -> Void)? = nil) { self.label = label self.address = address assert(address.port != nil) if let readHandler = readHandler { self.readHandler = readHandler } let queueAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos, 0) receiveQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.receiveQueue", queueAttribute) guard receiveQueue != nil else { fatalError("dispatch_queue_create() failed") } sendQueue = dispatch_queue_create("io.schwa.SwiftIO.UDP.sendQueue", queueAttribute) guard sendQueue != nil else { fatalError("dispatch_queue_create() failed") } } // MARK: - Actions public func resume() throws { do { socket = try Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) } catch let error { cleanup() errorHandler?(error) } configureSocket?(socket) source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, UInt(socket.descriptor), 0, receiveQueue) guard source != nil else { cleanup() throw Error.Generic("dispatch_source_create() failed") } dispatch_source_set_cancel_handler(source) { [weak self] in guard let strong_self = self else { return } strong_self.cleanup() strong_self.resumed = false } dispatch_source_set_event_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.read() } catch let error { strong_self.errorHandler?(error) } } dispatch_source_set_registration_handler(source) { [weak self] in guard let strong_self = self else { return } do { try strong_self.socket.bind(strong_self.address) strong_self.resumed = true } catch let error { strong_self.errorHandler?(error) tryElseFatalError() { try strong_self.cancel() } return } } dispatch_resume(source) } public func cancel() throws { if resumed == true { assert(source != nil, "Cancel called with source = nil.") dispatch_source_cancel(source) } } public func send(data: DispatchData <Void>, address: Address? = nil, callback: Result <Void> -> Void) { guard sendQueue != nil else { callback(.Failure(PreconditionError.QueueNotExist)) return } guard resumed else { callback(.Failure(PreconditionError.QueueSuspended)) return } dispatch_async(sendQueue) { [weak self] in guard let strong_self = self else { return } do { // use default address if address parameter is not set let address = address ?? strong_self.address if address.family != strong_self.address.family { throw Error.Generic("Cannot send UDP data down a IPV6 socket with a IPV4 address or vice versa.") } try strong_self.socket.sendto(data, address: address) } catch let error { strong_self.errorHandler?(error) callback(.Failure(error)) return } callback(.Success()) } } public static func send(data: DispatchData <Void>, address: Address, queue: dispatch_queue_t, writeHandler: Result <Void> -> Void) { let socket = try! Socket(domain: address.family.rawValue, type: SOCK_DGRAM, protocol: IPPROTO_UDP) dispatch_async(queue) { do { try socket.sendto(data, address: address) } catch let error { writeHandler(.Failure(error)) return } writeHandler(.Success()) } } } // MARK: - extension UDPChannel: CustomStringConvertible { public var description: String { return "\(self.dynamicType)(\"\(label ?? "")\")" } } // MARK: - private extension UDPChannel { func read() throws { let data: NSMutableData! = NSMutableData(length: 4096) var addressData = Array <Int8> (count: Int(SOCK_MAXADDRLEN), repeatedValue: 0) let (result, address) = addressData.withUnsafeMutableBufferPointer() { (inout ptr: UnsafeMutableBufferPointer <Int8>) -> (Int, Address?) in var addrlen: socklen_t = socklen_t(SOCK_MAXADDRLEN) let result = Darwin.recvfrom(socket.descriptor, data.mutableBytes, data.length, 0, UnsafeMutablePointer<sockaddr> (ptr.baseAddress), &addrlen) guard result >= 0 else { return (result, nil) } let addr = UnsafeMutablePointer <sockaddr_storage> (ptr.baseAddress) let address = Address(sockaddr: addr.memory) return (result, address) } guard result >= 0 else { let error = Error.Generic("recvfrom() failed") errorHandler?(error) throw error } data.length = result let datagram = Datagram(from: address!, timestamp: Timestamp(), data: DispatchData <Void> (buffer: data.toUnsafeBufferPointer())) readHandler?(datagram) } func cleanup() { defer { socket = nil source = nil } do { try socket.close() } catch let error { errorHandler?(error) } } } // MARK: - public extension UDPChannel { public func send(data: NSData, address: Address? = nil, callback: Result <Void> -> Void) { let data = DispatchData <Void> (start: data.bytes, count: data.length) send(data, address: address ?? self.address, callback: callback) } } // Private for now - make public soon? private extension Socket { func sendto(data: DispatchData <Void>, address: Address) throws { var addr = sockaddr_storage(address: address) let result = withUnsafePointer(&addr) { ptr in return data.createMap() { (_, buffer) in return Darwin.sendto(descriptor, buffer.baseAddress, buffer.count, 0, UnsafePointer <sockaddr> (ptr), socklen_t(addr.ss_len)) } } // TODO: what about "partial" sends. if result < data.length { throw Errno(rawValue: errno) ?? Error.Unknown } } }
mit
620890acea87fea54837254886f27626
31.42807
154
0.59143
4.651233
false
false
false
false
jisudong/study
MyPlayground.playground/Pages/可选链式调用.xcplaygroundpage/Contents.swift
1
1812
//: [Previous](@previous) import Foundation class Person { var residence: Residence? } class Residence { var rooms = [Room]() var address: Address? var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room{ get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRooms() { print("The number of rooms is \(numberOfRooms)") } } class Room { var name: String init(name: String) { self.name = name } } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName != nil { return buildingName } else if buildingNumber != nil && street != nil { return "\(String(describing: buildingNumber))\(String(describing: street))" } else { return nil } } } let john = Person() if let roomCount = john.residence?.numberOfRooms { print("John's residence has \(roomCount) room(s).") } else { print("Unable to retrieve the number of rooms.") } let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" john.residence?.address = someAddress // residence 为nil if john.residence?.printNumberOfRooms() != nil { print("It was possible to print the number of rooms.") } else { print("It was not possible to print the number of rooms.") } if let firstRoomName = john.residence?[0].name { print("The first room name is \(firstRoomName).") } else { print("Unable to retrieve the first room name.") } var dict = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]] dict["Dave"]?[0] = 91 dict["Bev"]?[0] += 1 dict["Brian"]?[0] = 72
mit
313678c8e211e0d19402b9f62c2d931c
21.625
87
0.596133
4.049217
false
false
false
false
STShenZhaoliang/Swift2Guide
Swift2Guide/Swift100Tips/Swift100Tips/ErrorController.swift
1
3869
// // ErrorController.swift // Swift100Tips // // Created by 沈兆良 on 16/5/30. // Copyright © 2016年 ST. All rights reserved. // import UIKit class ErrorController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let path = NSBundle.mainBundle().pathForResource("", ofType: "")! let file = NSFileManager.defaultManager().contentsAtPath(path)! do { try file.writeToFile("Hello", options: []) } catch let error as NSError { print ("Error: \(error.domain)") } do { try login("onevcat", password: "123") } catch LoginError.UserNotFound { print("UserNotFound") } catch LoginError.UserPasswordNotMatch { print("UserPasswordNotMatch") } catch { } let result = doSomethingParam(path) switch result { case let .Success(ok): let serverResponse = ok case let .Error(error): let serverResponse = error.description } do { try methodRethrows(1, f: methodThrows) } catch _ { } // 输出: // Int } enum LoginError: ErrorType { case UserNotFound, UserPasswordNotMatch } var users:[String: String]! func login(user: String, password: String) throws { //users 是 [String: String],存储[用户名:密码] if !users.keys.contains(user) { throw LoginError.UserNotFound } if users[user] != password { throw LoginError.UserPasswordNotMatch } print("Login successfully.") } enum Result { case Success(String) case Error(NSError) } func doSomethingParam(param:AnyObject) -> Result { //...做某些操作,成功结果放在 success 中 let success = true if success { return Result.Success("成功完成") } else { let error = NSError(domain: "errorDomain", code: 1, userInfo: nil) return Result.Error(error) } } func methodThrows(num: Int) throws { if num < 0 { print("Throwing!") // throw Error.Negative } print("Executed!") } func methodRethrows(num: Int, f: Int throws -> ()) rethrows { try f(num) } } //在 Swift 2.0 中,我们甚至可以在 enum 中指定泛型,这样就使结果统一化了。 enum Result<T> { case Success(T) case Failure(NSError) } //在 Swift 2 时代中的错误处理,现在一般的最佳实践是对于同步 API 使用异常机制,对于异步 API 使用泛型枚举。 //首先,try 可以接 ! 表示强制执行,这代表你确定知道这次调用不会抛出异常。如果在调用中出现了异常的话,你的程序将会崩溃,这和我们在对 Optional 值用 ! 进行强制解包时的行为是一致的。另外,我们也可以在 try 后面加上 ? 来进行尝试性的运行。try? 会返回一个 Optional 值:如果运行成功,没有抛出错误的话,它会包含这条语句的返回值,否则将为 nil。和其他返回 Optional 的方法类似,一个典型的 try? 的应用场景是和 if let 这样的语句搭配使用,不过如果你用了 try? 的话,就意味着你无视了错误的具体类型 /* 简单理解的话你可以将 rethrows 看做是 throws 的“子类”,rethrows 的方法可以用来重载那些被标为 throws 的方法或者参数,或者用来满足被标为 throws 的接口,但是反过来不行。如果你拿不准要怎么使用的话,就先记住你在要 throws 另一个 throws 时,应该将前者改为 rethrows。这样在不失灵活性的同时保证了代码的可读性和准确性。 */
mit
5ae8aec70819aa3815fe0d599929e09c
22.068702
279
0.592323
3.610514
false
false
false
false
AaronMT/firefox-ios
Client/Frontend/AuthenticationManager/PagingPasscodeViewController.swift
9
3110
/* 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 private let PaneSwipeDuration: TimeInterval = 0.3 /// Base class for implementing a Passcode configuration screen with multiple 'panes'. class PagingPasscodeViewController: BasePasscodeViewController { fileprivate lazy var pager: UIScrollView = { let scrollView = UIScrollView() scrollView.isPagingEnabled = true scrollView.isUserInteractionEnabled = false scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false return scrollView }() var panes = [PasscodePane]() var currentPaneIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() view.addSubview(pager) panes.forEach { pager.addSubview($0) } pager.snp.makeConstraints { make in make.bottom.left.right.equalTo(self.view) make.top.equalTo(self.view.safeArea.top) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() panes.enumerated().forEach { index, pane in pane.frame = CGRect(origin: CGPoint(x: CGFloat(index) * pager.frame.width, y: 0), size: pager.frame.size) } pager.contentSize = CGSize(width: CGFloat(panes.count) * pager.frame.width, height: pager.frame.height) scrollToPaneAtIndex(currentPaneIndex) if self.authenticationInfo?.isLocked() ?? false { return } panes[currentPaneIndex].codeInputView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.view.endEditing(true) } } extension PagingPasscodeViewController { @discardableResult func scrollToNextAndSelect() -> PasscodePane { scrollToNextPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } @discardableResult func scrollToPreviousAndSelect() -> PasscodePane { scrollToPreviousPane() panes[currentPaneIndex].codeInputView.becomeFirstResponder() return panes[currentPaneIndex] } func resetAllInputFields() { panes.forEach { $0.codeInputView.resetCode() } } func scrollToNextPane() { guard (currentPaneIndex + 1) < panes.count else { return } currentPaneIndex += 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPreviousPane() { guard (currentPaneIndex - 1) >= 0 else { return } currentPaneIndex -= 1 scrollToPaneAtIndex(currentPaneIndex) } func scrollToPaneAtIndex(_ index: Int) { UIView.animate(withDuration: PaneSwipeDuration, delay: 0, options: [], animations: { self.pager.contentOffset = CGPoint(x: CGFloat(self.currentPaneIndex) * self.pager.frame.width, y: 0) }, completion: nil) } }
mpl-2.0
4507c007c889d6b3e1dec35f7693579d
33.94382
117
0.667524
4.960128
false
false
false
false
djq993452611/YiYuDaoJia_Swift
YiYuDaoJia/YiYuDaoJia/Classes/Main/Controller/BaseViewController.swift
1
2249
// // BaseViewController.swift // YiYuDaoJia // // Created by 蓝海天网Djq on 2017/4/25. // Copyright © 2017年 蓝海天网Djq. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK: 定义属性 var contentView : UIView? var baseVM : BaseViewModel! // MARK: 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: #imageLiteral(resourceName: "daipingjia")) imageView.center = self.view.center imageView.animationImages = [#imageLiteral(resourceName: "daipingjia"),#imageLiteral(resourceName: "daishouhuo")] imageView.animationDuration = 2 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // extension BaseViewController { func setupUI() { // 1.隐藏内容的View contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(animImageView) // 3.给animImageView执行动画 animImageView.startAnimating() // 4.设置view的背景颜色 view.backgroundColor = UIColor.ColorHexString(hexStr: "#f0f0f0") //5.设置返回按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(backImage: #imageLiteral(resourceName: "back"), title: nil, parentVc: self, action: #selector(self.popAction)) navigationController?.navigationBar.tintColor = UIColor.gray } func loadDataFinished() { // 1.停止动画 animImageView.stopAnimating() // 2.隐藏animImageView animImageView.isHidden = true // 3.显示内容的View contentView?.isHidden = false } func popAction(){ navigationController?.popViewController(animated: true) } } // MARK:- 请求数据 extension BaseViewController { func loadData() { } }
mit
f5150ca70d079a567cca399132d57cee
20.353535
169
0.613529
4.848624
false
false
false
false
piv199/LocalisysChat
LocalisysChat/Sources/Modules/Common/Chat/Views/Inputs/AutoTextView.swift
1
5792
// // ALTextView.swift // ALTextInputBar // // Created by Alex Littlejohn on 2015/04/24. // Copyright (c) 2015 zero. All rights reserved. // import UIKit public protocol AutoTextViewDelegate: UITextViewDelegate { /** Notifies the receiver of a change to the contentSize of the textView The receiver is responsible for layout - parameter textView: The text view that triggered the size change - parameter newHeight: The ideal height for the new text view */ func textViewHeightChanged(textView: AutoTextView, newHeight: CGFloat) } public class AutoTextView: UITextView { // MARK: - Core properties fileprivate var textObserver: NSObjectProtocol? // MARK: - UI fileprivate lazy var placeholderLabel: UILabel = { var _placeholderLabel = UILabel() _placeholderLabel.clipsToBounds = false _placeholderLabel.autoresizesSubviews = false _placeholderLabel.numberOfLines = 1 _placeholderLabel.font = self.font _placeholderLabel.backgroundColor = UIColor.clear _placeholderLabel.textColor = self.tintColor _placeholderLabel.isHidden = true self.addSubview(_placeholderLabel) return _placeholderLabel }() // MARK: - Public properties override public var font: UIFont? { didSet { placeholderLabel.font = font } } override public var contentSize: CGSize { didSet { updateSize() } } public weak var textViewDelegate: AutoTextViewDelegate? { didSet { delegate = textViewDelegate } } public var placeholder: String = "" { didSet { placeholderLabel.text = placeholder } } /// The color of the placeholder text public var placeholderColor: UIColor! { get { return placeholderLabel.textColor } set { placeholderLabel.textColor = newValue } } public override var textAlignment: NSTextAlignment { get { return super.textAlignment } set { super.textAlignment = newValue placeholderLabel.textAlignment = newValue } } /// The maximum number of lines that will be shown before the text view will scroll. 0 = no limit public var maxNumberOfLines: CGFloat = 0 public fileprivate(set) var expectedHeight: CGFloat = 0 { didSet { guard oldValue != expectedHeight else { return } textViewDelegate?.textViewHeightChanged(textView: self, newHeight: expectedHeight) } } public var minimumHeight: CGFloat { get { return ceil(font?.lineHeight ?? 0.0) + textContainerInset.top + textContainerInset.bottom } } // MARK: - Lifecycle override public init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { isScrollEnabled = false configureObservers() updateSize() } fileprivate func configureObservers() { textObserver = NotificationCenter.default .addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: self, queue: nil) { [unowned self] (notification) in guard (notification.object as? AutoTextView) == self else { return } self.textViewDidChange() } } // MARK: - Layout override public func layoutSubviews() { super.layoutSubviews() placeholderLabel.isHidden = shouldHidePlaceholder() if !placeholderLabel.isHidden { placeholderLabel.frame = placeholderRectThatFits(rect: bounds) sendSubview(toBack: placeholderLabel) } } //MARK: - Sizing and scrolling private func updateSize() { let maxHeight = maxNumberOfLines > 0 ? (ceil(font!.lineHeight) * maxNumberOfLines) + textContainerInset.top + textContainerInset.bottom : CGFloat.greatestFiniteMagnitude let roundedHeight = roundHeight() if roundedHeight >= maxHeight { expectedHeight = maxHeight isScrollEnabled = true } else { isScrollEnabled = false expectedHeight = roundedHeight } ensureCaretDisplaysCorrectly() } /** Calculates the correct height for the text currently in the textview as we cannot rely on contentsize to do the right thing */ private func roundHeight() -> CGFloat { let boundingSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude) let size = sizeThatFits(boundingSize) return max(ceil(size.height), minimumHeight) } /** Ensure that when the text view is resized that the caret displays correctly withing the visible space */ private func ensureCaretDisplaysCorrectly() { guard let range = selectedTextRange else { return } DispatchQueue.main.async { let rect = self.caretRect(for: range.end) UIView.performWithoutAnimation { self.scrollRectToVisible(rect, animated: false) } } } //MARK: - Placeholder Layout - /** Determines if the placeholder should be hidden dependant on whether it was set and if there is text in the text view - returns: true if it should not be visible */ private func shouldHidePlaceholder() -> Bool { return placeholder.characters.count == 0 || text.characters.count > 0 } /** Layout the placeholder label to fit in the rect specified - parameter rect: The constrained size in which to fit the label - returns: The placeholder label frame */ private func placeholderRectThatFits(rect: CGRect) -> CGRect { let padding = textContainer.lineFragmentPadding var placeHolderRect = UIEdgeInsetsInsetRect(rect, textContainerInset) placeHolderRect.origin.x += padding placeHolderRect.size.width -= padding * 2 return placeHolderRect } //MARK: - Notifications - internal func textViewDidChange() { placeholderLabel.isHidden = shouldHidePlaceholder() updateSize() } }
unlicense
774bc41b3204ccedfb4a8d3907e0bfce
28.105528
126
0.710117
5.00605
false
false
false
false
te-th/xID3
Tests/xID3Tests/WithFilesTests.swift
1
1814
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import xID3 /// Verifies loading MP3 Files and extracting ID3 Tag class WithFilesTest: XCTestCase { /// Verifies that reading a MP3 file without ID3 data results in an absent ID3Tag. func testNonTaggedFile() { if let url = Bundle(for: type(of: self)).url(forResource: "without-id3", withExtension: "mp3") { if let inputStream = InputStream(url: url) { TestUtils.expectedAbsentID3Tag(inputStream) } } } /// Verifies that reading a MP3 file with an existing ID3 Tag func testTaggedFile() { if let url = Bundle(for: type(of: self)).url(forResource: "with-some-frames", withExtension: "mp3") { if let inputstream = InputStream(url: url) { let id3Tag = TestUtils.id3Tag(from: inputstream) XCTAssertNotNil(id3Tag) XCTAssertGreaterThan(id3Tag!.rawFrames().count, 0) } else { XCTFail("Could not find file with-some-frames.mp3") } } } }
apache-2.0
600176efee8ee7d638c3171d6a45b298
36.791667
109
0.68688
4.308789
false
true
false
false
MarvinNazari/ICSPullToRefresh.Swift
ICSPullToRefresh/NVActivityIndicatorAnimationBallPulseRise.swift
1
3984
// // NVActivityIndicatorAnimationBallPulseRise.swift // NVActivityIndicatorViewDemo // // Created by Nguyen Vinh on 7/24/15. // Copyright (c) 2015 Nguyen Vinh. All rights reserved. // import UIKit class NVActivityIndicatorAnimationBallPulseRise: NVActivityIndicatorAnimationDelegate { func setUpAnimationInLayer(layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - 4 * circleSpacing) / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - circleSize) / 2 let deltaY = size.height / 2 let duration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(controlPoints: 0.15, 0.46, 0.9, 0.6) let oddAnimation = self.oddAnimation(duration: duration, deltaY: deltaY, timingFunction: timingFunction) let evenAnimation = self.evenAnimation(duration: duration, deltaY: deltaY, timingFunction: timingFunction) // Draw circles for var i = 0; i < 5; i++ { let circle = NVActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), y: y, width: circleSize, height: circleSize) circle.frame = frame if i % 2 == 0 { circle.addAnimation(evenAnimation, forKey: "animation") } else { circle.addAnimation(oddAnimation, forKey: "animation") } layer.addSublayer(circle) } } func oddAnimation(duration duration: CFTimeInterval, deltaY: CGFloat, timingFunction: CAMediaTimingFunction) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [0.4, 1.1, 0.75] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") translateAnimation.keyTimes = [0, 0.25, 0.75, 1] translateAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction] translateAnimation.values = [0, deltaY, -deltaY, 0] translateAnimation.duration = duration let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false return animation } func evenAnimation(duration duration: CFTimeInterval, deltaY: CGFloat, timingFunction: CAMediaTimingFunction) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1.1, 0.4, 1] scaleAnimation.duration = duration // Translate animation let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation.y") translateAnimation.keyTimes = [0, 0.25, 0.75, 1] translateAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction] translateAnimation.values = [0, -deltaY, deltaY, 0] translateAnimation.duration = duration let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.removedOnCompletion = false return animation } }
mit
0799c7876c929d3978b3c612e614659f
40.936842
139
0.646586
5.304927
false
false
false
false
neotron/SwiftBot-Discord
DiscordAPI/Source/API/Utility/URLEndpoints.swift
1
727
// // Created by David Hedbor on 2/12/16. // Copyright (c) 2016 NeoTron. All rights reserved. // import Foundation import Alamofire enum URLEndpoint: String { case Login = "auth/login", Logout = "auth/logout", Gateway = "gateway", Channel = "channels", User = "users" } class Endpoints { class func Simple(_ endpoint: URLEndpoint) -> String { return "https://discordapp.com/api/\(endpoint.rawValue)" } class func Channel(_ channel: String) -> String { return "\(Simple(.Channel))/\(channel)/messages" } class func User(_ userId: String, endpoint: URLEndpoint) -> String { return "\(Simple(.User))/\(userId)/\(endpoint.rawValue)" } }
gpl-3.0
74117925a32497bf72326f993237c1e7
24.068966
72
0.609354
3.972678
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSScanner.swift
2
23943
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // import CoreFoundation public class NSScanner : NSObject, NSCopying { internal var _scanString: String internal var _skipSet: NSCharacterSet? internal var _invertedSkipSet: NSCharacterSet? internal var _scanLocation: Int public func copyWithZone(zone: NSZone) -> AnyObject { return NSScanner(string: string) } public var string: String { return _scanString } public var scanLocation: Int { get { return _scanLocation } set { if newValue > string.length { fatalError("Index \(newValue) beyond bounds; string length \(string.length)") } _scanLocation = newValue } } /*@NSCopying*/ public var charactersToBeSkipped: NSCharacterSet? { get { return _skipSet } set { _skipSet = newValue?.copy() as? NSCharacterSet _invertedSkipSet = nil } } internal var invertedSkipSet: NSCharacterSet? { get { if let inverted = _invertedSkipSet { return inverted } else { if let set = charactersToBeSkipped { _invertedSkipSet = set.invertedSet return _invertedSkipSet } return nil } } } public var caseSensitive: Bool = false public var locale: NSLocale? internal static let defaultSkipSet = NSCharacterSet.whitespaceAndNewlineCharacterSet() public init(string: String) { _scanString = string _skipSet = NSScanner.defaultSkipSet _scanLocation = 0 } } private struct _NSStringBuffer { var bufferLen: Int var bufferLoc: Int var string: NSString var stringLen: Int var stringLoc: Int var buffer = Array<unichar>(count: 32, repeatedValue: 0) var curChar: unichar static let EndCharacter = unichar(0xffff) init(string: String, start: Int, end: Int) { self.string = string._bridgeToObjectiveC() stringLoc = start stringLen = end if stringLoc < stringLen { bufferLen = min(32, stringLen - stringLoc); let range = NSMakeRange(stringLoc, bufferLen) bufferLoc = 1 curChar = buffer[0] buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in self.string.getCharacters(ptr.baseAddress, range: range) }) } else { bufferLen = 0 bufferLoc = 1 curChar = _NSStringBuffer.EndCharacter } } var currentCharacter: unichar { return curChar } var isAtEnd: Bool { return curChar == _NSStringBuffer.EndCharacter } mutating func fill() { bufferLen = min(32, stringLen - stringLoc); let range = NSMakeRange(stringLoc, bufferLen) buffer.withUnsafeMutableBufferPointer({ (inout ptr: UnsafeMutableBufferPointer<unichar>) -> Void in string.getCharacters(ptr.baseAddress, range: range) }) bufferLoc = 1 curChar = buffer[0] } mutating func advance() { if bufferLoc < bufferLen { /*buffer is OK*/ curChar = buffer[bufferLoc++] } else if (stringLoc + bufferLen < stringLen) { /* Buffer is empty but can be filled */ stringLoc += bufferLen fill() } else { /* Buffer is empty and we're at the end */ bufferLoc = bufferLen + 1 curChar = _NSStringBuffer.EndCharacter } } mutating func skip(skipSet: NSCharacterSet?) { if let set = skipSet { while set.characterIsMember(currentCharacter) && !isAtEnd { advance() } } } } private func isADigit(ch: unichar) -> Bool { struct Local { static let set = NSCharacterSet.decimalDigitCharacterSet() } return Local.set.characterIsMember(ch) } // This is just here to allow just enough generic math to handle what is needed for scanning an abstract integer from a string, perhaps these should be on IntegerType? internal protocol _BitShiftable { func >>(lhs: Self, rhs: Self) -> Self func <<(lhs: Self, rhs: Self) -> Self } internal protocol _IntegerLike : IntegerType, _BitShiftable { init(_ value: Int) static var max: Self { get } static var min: Self { get } } internal protocol _FloatArithmeticType { func +(lhs: Self, rhs: Self) -> Self func -(lhs: Self, rhs: Self) -> Self func *(lhs: Self, rhs: Self) -> Self func /(lhs: Self, rhs: Self) -> Self } internal protocol _FloatLike : FloatingPointType, _FloatArithmeticType { init(_ value: Int) init(_ value: Double) static var max: Self { get } static var min: Self { get } } extension Int : _IntegerLike { } extension Int32 : _IntegerLike { } extension Int64 : _IntegerLike { } extension UInt32 : _IntegerLike { } extension UInt64 : _IntegerLike { } // these might be good to have in the stdlib extension Float : _FloatLike { static var max: Float { return FLT_MAX } static var min: Float { return FLT_MIN } } extension Double : _FloatLike { static var max: Double { return DBL_MAX } static var min: Double { return DBL_MIN } } private func numericValue(ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else { return __CFCharDigitValue(UniChar(ch)) } } private func numericOrHexValue(ch: unichar) -> Int { if (ch >= unichar(unicodeScalarLiteral: "0") && ch <= unichar(unicodeScalarLiteral: "9")) { return Int(ch) - Int(unichar(unicodeScalarLiteral: "0")) } else if (ch >= unichar(unicodeScalarLiteral: "A") && ch <= unichar(unicodeScalarLiteral: "F")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "A")) } else if (ch >= unichar(unicodeScalarLiteral: "a") && ch <= unichar(unicodeScalarLiteral: "f")) { return Int(ch) + 10 - Int(unichar(unicodeScalarLiteral: "a")) } else { return -1; } } private func decimalSep(locale: NSLocale?) -> String { if let loc = locale { if let sep = loc.objectForKey(NSLocaleDecimalSeparator) as? NSString { return sep._swiftObject } return "." } else { return decimalSep(NSLocale.currentLocale()) } } extension String { internal func scan<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = 0 if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } if (localResult >= T.max / 10) && ((localResult > T.max / 10) || T(numeral - (neg ? 1 : 0)) >= T.max - localResult * 10) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? T.min : T.max neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { // normal case for scanning localResult = localResult * 10 + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) to(neg ? -1 * localResult : localResult) locationToScanFrom = buf.stringLoc return true } internal func scanHex<T: _IntegerLike>(skipSet: NSCharacterSet?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var localResult: T = 0 var curDigit: Int if buf.currentCharacter == unichar(unicodeScalarLiteral: "0") { buf.advance() let locRewindTo = buf.stringLoc curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { if buf.currentCharacter == unichar(unicodeScalarLiteral: "x") || buf.currentCharacter == unichar(unicodeScalarLiteral: "X") { buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } } if curDigit == -1 { locationToScanFrom = locRewindTo to(T(0)) return true } } else { curDigit = numericOrHexValue(buf.currentCharacter) if curDigit == -1 { return false } } repeat { if localResult > T.max >> T(4) { localResult = T.max } else { localResult = (localResult << T(4)) + T(curDigit) } buf.advance() curDigit = numericOrHexValue(buf.currentCharacter) } while (curDigit != -1) to(localResult) locationToScanFrom = buf.stringLoc return true } internal func scan<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { let ds_chars = decimalSep(locale).utf16 let ds = ds_chars[ds_chars.startIndex] var buf = _NSStringBuffer(string: self, start: locationToScanFrom, end: length) buf.skip(skipSet) var neg = false var localResult: T = T(0) if buf.currentCharacter == unichar(unicodeScalarLiteral: "-") || buf.currentCharacter == unichar(unicodeScalarLiteral: "+") { neg = buf.currentCharacter == unichar(unicodeScalarLiteral: "-") buf.advance() buf.skip(skipSet) } if (!isADigit(buf.currentCharacter)) { return false } repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } // if (localResult >= T.max / T(10)) && ((localResult > T.max / T(10)) || T(numericValue(buf.currentCharacter) - (neg ? 1 : 0)) >= T.max - localResult * T(10)) is evidently too complex; so break it down to more "edible chunks" let limit1 = localResult >= T.max / T(10) let limit2 = localResult > T.max / T(10) let limit3 = T(numeral - (neg ? 1 : 0)) >= T.max - localResult * T(10) if (limit1) && (limit2 || limit3) { // apply the clamps and advance past the ending of the buffer where there are still digits localResult = neg ? T.min : T.max neg = false repeat { buf.advance() } while (isADigit(buf.currentCharacter)) break } else { localResult = localResult * T(10) + T(numeral) } buf.advance() } while (isADigit(buf.currentCharacter)) if buf.currentCharacter == ds { var factor = T(0.1) buf.advance() repeat { let numeral = numericValue(buf.currentCharacter) if numeral == -1 { break } localResult = localResult + T(numeral) * factor factor = factor * T(0.1) buf.advance() } while (isADigit(buf.currentCharacter)) } to(neg ? T(-1) * localResult : localResult) locationToScanFrom = buf.stringLoc return true } internal func scanHex<T: _FloatLike>(skipSet: NSCharacterSet?, locale: NSLocale?, inout locationToScanFrom: Int, to: (T) -> Void) -> Bool { NSUnimplemented() } } extension NSScanner { // On overflow, the below methods will return success and clamp public func scanInt(result: UnsafeMutablePointer<Int32>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int32) -> Void in result.memory = value } } public func scanInteger(result: UnsafeMutablePointer<Int>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int) -> Void in result.memory = value } } public func scanLongLong(result: UnsafeMutablePointer<Int64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: Int64) -> Void in result.memory = value } } public func scanUnsignedLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scan(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in result.memory = value } } public func scanFloat(result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in result.memory = value } } public func scanDouble(result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scan(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in result.memory = value } } public func scanHexInt(result: UnsafeMutablePointer<UInt32>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt32) -> Void in result.memory = value } } public func scanHexLongLong(result: UnsafeMutablePointer<UInt64>) -> Bool { return _scanString.scanHex(_skipSet, locationToScanFrom: &scanLocation) { (value: UInt64) -> Void in result.memory = value } } public func scanHexFloat(result: UnsafeMutablePointer<Float>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Float) -> Void in result.memory = value } } public func scanHexDouble(result: UnsafeMutablePointer<Double>) -> Bool { return _scanString.scanHex(_skipSet, locale: locale, locationToScanFrom: &scanLocation) { (value: Double) -> Void in result.memory = value } } public var atEnd: Bool { var stringLoc = scanLocation let stringLen = string.length if let invSet = invertedSkipSet { let range = string._nsObject.rangeOfCharacterFromSet(invSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } return stringLoc == stringLen } public class func localizedScannerWithString(string: String) -> AnyObject { NSUnimplemented() } } /// Revised API for avoiding usage of AutoreleasingUnsafeMutablePointer and better Optional usage. /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future extension NSScanner { public func scanInt() -> Int32? { var value: Int32 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int32>) -> Int32? in if scanInt(ptr) { return ptr.memory } else { return nil } } } public func scanInteger() -> Int? { var value: Int = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int>) -> Int? in if scanInteger(ptr) { return ptr.memory } else { return nil } } } public func scanLongLong() -> Int64? { var value: Int64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Int64>) -> Int64? in if scanLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanUnsignedLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanUnsignedLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanFloat(ptr) { return ptr.memory } else { return nil } } } public func scanDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanDouble(ptr) { return ptr.memory } else { return nil } } } public func scanHexInt() -> UInt32? { var value: UInt32 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt32>) -> UInt32? in if scanHexInt(ptr) { return ptr.memory } else { return nil } } } public func scanHexLongLong() -> UInt64? { var value: UInt64 = 0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<UInt64>) -> UInt64? in if scanHexLongLong(ptr) { return ptr.memory } else { return nil } } } public func scanHexFloat() -> Float? { var value: Float = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Float>) -> Float? in if scanHexFloat(ptr) { return ptr.memory } else { return nil } } } public func scanHexDouble() -> Double? { var value: Double = 0.0 return withUnsafeMutablePointer(&value) { (ptr: UnsafeMutablePointer<Double>) -> Double? in if scanHexDouble(ptr) { return ptr.memory } else { return nil } } } // These methods avoid calling the private API for _invertedSkipSet and manually re-construct them so that it is only usage of public API usage // Future implementations on Darwin of these methods will likely be more optimized to take advantage of the cached values. public func scanString(string searchString: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = [caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch, NSStringCompareOptions.AnchoredSearch] if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } let range = str.rangeOfString(searchString, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length > 0 { /* ??? Is the range below simply range? 99.9% of the time, and perhaps even 100% of the time... Hmm... */ let res = str.substringWithRange(NSMakeRange(stringLoc, range.location + range.length - stringLoc)) scanLocation = range.location + range.length return res } return nil } public func scanCharactersFromSet(set: NSCharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacterFromSet(set.invertedSet, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToString(string: String) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfString(string, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } public func scanUpToCharactersFromSet(set: NSCharacterSet) -> String? { let str = self.string._bridgeToObjectiveC() var stringLoc = scanLocation let stringLen = str.length let options: NSStringCompareOptions = caseSensitive ? [] : NSStringCompareOptions.CaseInsensitiveSearch if let invSkipSet = charactersToBeSkipped?.invertedSet { let range = str.rangeOfCharacterFromSet(invSkipSet, options: [], range: NSMakeRange(stringLoc, stringLen - stringLoc)) stringLoc = range.length > 0 ? range.location : stringLen } var range = str.rangeOfCharacterFromSet(set, options: options, range: NSMakeRange(stringLoc, stringLen - stringLoc)) if range.length == 0 { range.location = stringLen } if stringLoc != range.location { let res = str.substringWithRange(NSMakeRange(stringLoc, range.location - stringLoc)) scanLocation = range.location return res } return nil } }
apache-2.0
601fa2a2f22362f39712a962204ac363
35.949074
239
0.586852
5.043817
false
false
false
false
MrAlek/PagedArray
Sources/PagedArray.swift
1
6848
// // PagedArray.swift // // Created by Alek Åström on 2015-02-14. // Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek) // // 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. /// /// A paging collection type for arbitrary elements. Great for implementing paging /// mechanisms to scrolling UI elements such as `UICollectionView` and `UITableView`. /// public struct PagedArray<T> { public typealias PageIndex = Int /// The datastorage public fileprivate(set) var elements = [PageIndex: [T]]() // MARK: Public properties /// The size of each page public let pageSize: Int /// The total count of supposed elements, including nil values public var count: Int /// The starting page index public let startPage: PageIndex /// When set to true, no size or upper index checking /// is done when setting pages, making the paged array /// adjust its size dynamically. /// /// Useful for infinite lists and when data count cannot /// be guaranteed not to change while loading new pages. public var updatesCountWhenSettingPages: Bool = false /// The last valid page index public var lastPage: PageIndex { if count == 0 { return 0 } else if count%pageSize == 0 { return count/pageSize+startPage-1 } else { return count/pageSize+startPage } } /// All elements currently set, in order public var loadedElements: [T] { return self.compactMap { $0 } } // MARK: Initializers /// Creates an empty `PagedArray` public init(count: Int, pageSize: Int, startPage: PageIndex = 0) { self.count = count self.pageSize = pageSize self.startPage = startPage } // MARK: Public functions /// Returns the page index for an element index public func page(for index: Index) -> PageIndex { assert(index >= startIndex && index < endIndex, "Index out of bounds") return index/pageSize+startPage } /// Returns a `Range` corresponding to the indexes for a page public func indexes(for page: PageIndex) -> CountableRange<Index> { assert(page >= startPage && page <= lastPage, "Page index out of bounds") let start: Index = (page-startPage)*pageSize let end: Index if page == lastPage { end = count } else { end = start+pageSize } return (start..<end) } // MARK: Public mutating functions /// Sets a page of elements for a page index public mutating func set(_ elements: [T], forPage page: PageIndex) { assert(page >= startPage, "Page index out of bounds") assert(count == 0 || elements.count > 0, "Can't set empty elements page on non-empty array") let pageIndexForExpectedSize = (page > lastPage) ? lastPage : page let expectedSize = size(for: pageIndexForExpectedSize) if !updatesCountWhenSettingPages { assert(page <= lastPage, "Page index out of bounds") assert(elements.count == expectedSize, "Incorrect page size") } else { // High Chaparall mode, array can change in size count += elements.count-expectedSize if page > lastPage { count += (page-lastPage)*pageSize } } self.elements[page] = elements } /// Removes the elements corresponding to the page, replacing them with `nil` values public mutating func remove(_ page: PageIndex) { elements[page] = nil } /// Removes all loaded elements, replacing them with `nil` values public mutating func removeAllPages() { elements.removeAll(keepingCapacity: true) } } // MARK: SequenceType extension PagedArray : Sequence { public func makeIterator() -> IndexingIterator<PagedArray> { return IndexingIterator(_elements: self) } } // MARK: CollectionType extension PagedArray : BidirectionalCollection { public typealias Index = Int public var startIndex: Index { return 0 } public var endIndex: Index { return count } public func index(after i: Index) -> Index { return i+1 } public func index(before i: Index) -> Index { return i-1 } /// Accesses and sets elements for a given flat index position. /// Currently, setter can only be used to replace non-optional values. public subscript (position: Index) -> T? { get { let pageIndex = page(for: position) if let page = elements[pageIndex] { return page[position%pageSize] } else { // Return nil for all pages that haven't been set yet return nil } } set(newValue) { guard let newValue = newValue else { return } let pageIndex = page(for: position) var elementPage = elements[pageIndex] elementPage?[position % pageSize] = newValue elements[pageIndex] = elementPage } } } // MARK: Printable extension PagedArray : CustomStringConvertible { public var description: String { return "PagedArray(\(Array(self)))" } } // MARK: DebugPrintable extension PagedArray : CustomDebugStringConvertible { public var debugDescription: String { return "PagedArray(Pages: \(elements), Array representation: \(Array(self)))" } } // MARK: Private functions private extension PagedArray { func size(for page: PageIndex) -> Int { let indexes = self.indexes(for: page) return indexes.endIndex-indexes.startIndex } }
mit
584c1b4f4e242adc468da296e9b5a0b8
31.436019
100
0.631064
4.819718
false
false
false
false
danielsaidi/Vandelay
VandelayDemo/ViewController.swift
1
2514
// // ViewController.swift // VandelayExample // // Created by Daniel Saidi on 2018-09-12. // Copyright © 2018 Daniel Saidi. All rights reserved. // import UIKit import Vandelay class ViewController: UITableViewController { // MARK: - View lifecycle override func viewWillAppear(_ animated: Bool) { reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let id = segue.identifier else { return } switch id { case "PhotoSegue": let vc = segue.destination as? PhotoViewController vc?.repository = photoRepository case "TodoSegue": let vc = segue.destination as? TodoItemViewController vc?.repository = todoItemRepository default: break } } // MARK: - Dependencies let todoItemRepository = TodoItemRepository() let photoRepository = PhotoRepository() // MARK: - Properties let photoFile = "photoAlbum.vdl" var photoUrl: URL { FileExporter(fileName: photoFile).getFileUrl()! } let todoFile = "todoList.vdl" var todoUrl: URL { FileExporter(fileName: todoFile).getFileUrl()! } // MARK: - Outlets @IBOutlet weak var exportPhotoAlbumCell: UITableViewCell! @IBOutlet weak var exportTodoItemsCell: UITableViewCell! @IBOutlet weak var importPhotoAlbumCell: UITableViewCell! @IBOutlet weak var importTodoItemsCell: UITableViewCell! @IBOutlet weak var photoAlbumCell: UITableViewCell! @IBOutlet weak var todoItemCell: UITableViewCell! } // MARK: - Public Functions extension ViewController { func reloadData() { let items = todoItemRepository.getItems() let photos = photoRepository.getPhotos() todoItemCell.detailTextLabel?.text = "\(items.count) items" photoAlbumCell.detailTextLabel?.text = "\(photos.count) photos" } } // MARK: - UITableViewDelegate extension ViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) guard let cell = tableView.cellForRow(at: indexPath) else { return } switch cell { case exportPhotoAlbumCell: exportPhotoAlbum() case exportTodoItemsCell: exportTodoList() case importTodoItemsCell: importTodoList() case importPhotoAlbumCell: importPhotoAlbum() default: break } } }
mit
c87c0c9c8992a19f399bb2545441fc3e
27.556818
92
0.664942
4.898635
false
false
false
false
xuzhuoyi/EmbControl
embcontrol/yudpsocket.swift
1
6170
/* Copyright (c) <2014>, skysent All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by skysent. 4. Neither the name of the skysent nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY skysent ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL skysent BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation @asmname("yudpsocket_server") func c_yudpsocket_server(host:UnsafePointer<Int8>,port:Int32) -> Int32 @asmname("yudpsocket_recive") func c_yudpsocket_recive(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32 @asmname("yudpsocket_close") func c_yudpsocket_close(fd:Int32) -> Int32 @asmname("yudpsocket_client") func c_yudpsocket_client() -> Int32 @asmname("yudpsocket_get_server_ip") func c_yudpsocket_get_server_ip(host:UnsafePointer<Int8>,ip:UnsafePointer<Int8>) -> Int32 @asmname("yudpsocket_sentto") func c_yudpsocket_sentto(fd:Int32,buff:UnsafePointer<UInt8>,len:Int32,ip:UnsafePointer<Int8>,port:Int32) -> Int32 public class UDPClient: YSocket { public override init(addr a:String,port p:Int){ super.init() var remoteipbuff:[Int8] = [Int8](count:16,repeatedValue:0x0) var ret=c_yudpsocket_get_server_ip(a, ip: remoteipbuff) if ret==0{ if let ip=String(CString: remoteipbuff, encoding: NSUTF8StringEncoding){ self.addr=ip self.port=p var fd:Int32=c_yudpsocket_client() if fd>0{ self.fd=fd } } } } /* * send data * return success or fail with message */ public func send(data d:[UInt8])->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_yudpsocket_sentto(fd, buff: d, len: Int32(d.count), ip: self.addr,port: Int32(self.port)) if Int(sendsize)==d.count{ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * send string * return success or fail with message */ public func send(str s:String)->(Bool,String){ if let fd:Int32=self.fd{ var sendsize:Int32=c_yudpsocket_sentto(fd, buff: s, len: Int32(strlen(s)), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(strlen(s)){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } /* * * send nsdata */ public func send(data d:NSData)->(Bool,String){ if let fd:Int32=self.fd{ var buff:[UInt8] = [UInt8](count:d.length,repeatedValue:0x0) d.getBytes(&buff, length: d.length) var sendsize:Int32=c_yudpsocket_sentto(fd, buff: buff, len: Int32(d.length), ip: self.addr,port: Int32(self.port)) if sendsize==Int32(d.length){ return (true,"send success") }else{ return (false,"send error") } }else{ return (false,"socket not open") } } public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } //TODO add multycast and boardcast } public class UDPServer:YSocket{ public override init(addr a:String,port p:Int){ super.init(addr: a, port: p) var fd:Int32 = c_yudpsocket_server(self.addr, port: Int32(self.port)) if fd>0{ self.fd=fd } } //TODO add multycast and boardcast public func recv(expectlen:Int)->([UInt8]?,String,Int){ if let fd:Int32 = self.fd{ var buff:[UInt8] = [UInt8](count:expectlen,repeatedValue:0x0) var remoteipbuff:[Int8] = [Int8](count:16,repeatedValue:0x0) var remoteport:Int32=0 var readLen:Int32=c_yudpsocket_recive(fd, buff: buff, len: Int32(expectlen), ip: &remoteipbuff, port: &remoteport) var port:Int=Int(remoteport) var addr:String="" if let ip=String(CString: remoteipbuff, encoding: NSUTF8StringEncoding){ addr=ip } if readLen<=0{ return (nil,addr,port) } var rs=buff[0...Int(readLen-1)] var data:[UInt8] = Array(rs) return (data,addr,port) } return (nil,"no ip",0) } public func close()->(Bool,String){ if let fd:Int32=self.fd{ c_yudpsocket_close(fd) self.fd=nil return (true,"close success") }else{ return (false,"socket not open") } } }
gpl-3.0
2a35a9dd327611987e78583c8ed242cf
38.551282
158
0.626418
3.929936
false
false
false
false
haldun/MapleBacon
MapleBaconExample/MapleBaconExample/ImageManagerExample.swift
2
2419
// // Copyright (c) 2015 Zalando SE. All rights reserved. // import UIKit import MapleBacon class ImageCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView? override func prepareForReuse() { self.imageView?.image = nil } } class ImageExampleViewController: UICollectionViewController { var imageURLs = ["http://media.giphy.com/media/lI6nHr5hWXlu0/giphy.gif"] override func viewDidLoad() { if let file = NSBundle.mainBundle().pathForResource("imageURLs", ofType: "plist"), let paths = NSArray(contentsOfFile: file) { for url in paths { imageURLs.append(url as! String) } } collectionView?.reloadData() super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) let gradient = CAGradientLayer() gradient.frame = view.frame gradient.colors = [UIColor(red: 127 / 255, green: 187 / 255, blue: 154 / 255, alpha: 1).CGColor, UIColor(red: 14 / 255, green: 43 / 255, blue: 57 / 255, alpha: 1).CGColor] view.layer.insertSublayer(gradient, atIndex: 0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() MapleBaconStorage.sharedStorage.clearMemoryStorage() } @IBAction func clearCache(sender: AnyObject) { MapleBaconStorage.sharedStorage.clearStorage() } } extension ImageExampleViewController { // MARK: UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageURLs.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageCell", forIndexPath: indexPath) as! ImageCell let url = imageURLs[indexPath.row] if let imageURL = NSURL(string: imageURLs[indexPath.row]) { cell.imageView?.setImageWithURL(imageURL) { (_, error) in if error == nil { let transition = CATransition() cell.imageView?.layer.addAnimation(transition, forKey: "fade") } } } return cell } }
mit
7a139de23ed3f7b4281ae9f387900dfd
30.415584
139
0.640761
5.135881
false
false
false
false
spitzgoby/Tunits
Pod/Classes/TimeUnit+DateTraversal.swift
1
22034
// // TimeUnit+DateTraversal.swift // Pods // // Created by Tom on 12/27/15. // // 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. // // Large portions of this code were influenced by Matt Thompson (http://mattt.me). // The original code can be found at https://github.com/mattt/CupertinoYankee // import Foundation extension TimeUnit { // MARK: - Previous and Next Time Units // MARK: minutes /************** *** PLURAL *** **************/ /** Creates a new date by subtracting the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ public func minutesBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.minutesAfter(date, delta: -delta) } /** Creates a new date by subtracting the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ static public func minutesBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.minutesBefore(date, delta: delta) } /** Creates a new date by adding the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ static public func minutesAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.minutesAfter(date, delta: delta) } /** Creates a new date by adding the given number of minutes from the given date and truncating to the first second of the date's minute. - parameter date: The date from which to subtract minutes. - parameter delta: The number of minutes to be subtracted. - returns: The newly created date. */ public func minutesAfter(date:NSDate, delta:Int = 1) -> NSDate { let minute = self.calendar.dateByAddingUnit(.Minute, value: delta, toDate: date, options: [])! return self.beginningOfMinute(minute) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the minute prior to the given date. - parameter date: The date for which to find the previous minute. - returns: The newly created date. */ public func minuteBefore(date:NSDate) -> NSDate { return self.minutesBefore(date) } /** Creates a new date at the first second of the minute prior to the given date. - parameter date: The date for which to find the previous minute. - returns: The newly created date. */ static public func minuteBefore(date:NSDate) -> NSDate { return sharedInstance.minuteBefore(date) } /** Creates a new date at the first second of the minute following the given date. - parameter date: The date for which to calculate the next minute. - returns: The newly created date. */ public func minuteAfter(date:NSDate) -> NSDate { return self.minutesAfter(date) } /** Creates a new date at the first second of the minute following the given date. - parameter date: The date for which to calculate the next minute. - returns: The newly created date. */ static public func minuteAfter(date:NSDate) -> NSDate { return sharedInstance.minuteAfter(date) } // MARK: hours /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of hours to the given date and truncating to the first second of the date's hour. - parameter date: The date to which to add hours. - parameter delta: The number of hours to be added - returns: The newly created date. */ public func hoursAfter(date:NSDate, delta: Int = 1) -> NSDate { let hour = self.calendar.dateByAddingUnit(.Hour, value: delta, toDate: date, options: [])! return self.beginningOfHour(hour) } /** Creates a new date by adding the given number of hours to the given date and truncating to the first second of the date's hour. - parameter date: The date to which to add hours. - parameter delta: The number of hours to be added - returns: The newly created date. */ static public func hoursAfter(date:NSDate, delta: Int = 1) -> NSDate { return sharedInstance.hoursAfter(date, delta: delta) } /** Creates a new date by subtracting the given number of hours from the given date and truncating to the first second of the date's hour. - parameter date: The date from which to subtract hours. - parameter delta: The number of hours to be subtracted - returns: The newly created date. */ public func hoursBefore(date:NSDate, delta: Int = 1) -> NSDate { return self.hoursAfter(date, delta: -delta) } /** Creates a new date by subtracting the given number of hours from the given date and truncating to the first second of the date's hour. - parameter date: The date from which to subtract hours. - parameter delta: The number of hours to be subtracted - returns: The newly created date. */ static public func hoursBefore(date:NSDate, delta: Int = 1) -> NSDate { return sharedInstance.hoursBefore(date, delta: delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the hour prior to the given date. - parameter date: The date for which to find the previous hour - returns: The newly created date. */ public func hourBefore(date:NSDate) -> NSDate { return self.hoursBefore(date) } /** Creates a new date at the first second of the hour prior to the given date. - parameter date: The date for which to find the previous hour - returns: The newly created date. */ static public func hourBefore(date:NSDate) -> NSDate { return sharedInstance.hourBefore(date) } /** Creates a new date at the first second of the hour following the given date. - parameter date: The date for which to find the next hour - returns: The newly created date. */ public func hourAfter(date:NSDate) -> NSDate { return self.hoursAfter(date) } /** Creates a new date at the first second of the hour following the given date. - parameter date: The date for which to find the next hour - returns: The newly created date. */ static public func hourAfter(date:NSDate) -> NSDate { return sharedInstance.hourAfter(date) } // MARK: days /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of days to the given date and truncating to the first second of the date's day. - parameter date: The date to which to add days. - parameter delta: The number of days to be added - returns: The newly created date. */ public func daysAfter(date:NSDate, delta:Int = 1) -> NSDate { let day = self.calendar.dateByAddingUnit(.Day, value: delta, toDate: date, options: [])! return self.beginningOfDay(day) } /** Creates a new date by adding the given number of days to the given date and truncating to the first second of the date's day. - parameter date: The date to which to add days. - parameter delta: The number of days to be added - returns: The newly created date. */ static public func daysAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.daysAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of days from the given date and truncating to the first second of the date's day. - parameter date: The date from which to subtract days. - parameter delta: The number of days to be subtracted - returns: The newly created date. */ public func daysBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.daysAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of days from the given date and truncating to the first second of the date's day. - parameter date: The date from which to subtract days. - parameter delta: The number of days to be subtracted - returns: The newly created date. */ static public func daysBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.daysBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the day prior to the given date. - parameter date: The date for which to find the previous day. - returns: The newly created date. */ public func dayBefore(date:NSDate) -> NSDate { return self.daysBefore(date) } /** Creates a new date at the first second of the day prior to the given date. - parameter date: The date for which to find the previous day. - returns: The newly created date. */ static public func dayBefore(date:NSDate) -> NSDate { return sharedInstance.dayBefore(date) } /** Creates a new date at the first second of the day following the given date. - parameter date: The date for which to find the next day. - returns: The newly created date. */ public func dayAfter(date:NSDate) -> NSDate { return self.daysAfter(date) } /** Creates a new date at the first second of the day following the given date. - parameter date: The date for which to find the next day. - returns: The newly created date. */ static public func dayAfter(date:NSDate) -> NSDate { return sharedInstance.dayAfter(date) } // MARK: weeks /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of weeks to the given date and truncating to the first second of the date's week. - parameter date: The date to which to add weeks. - parameter delta: The number of weeks to be added - returns: The newly created date. */ public func weeksAfter(date:NSDate, delta:Int = 1) -> NSDate { let week = self.calendar.dateByAddingUnit(.WeekOfYear, value: delta, toDate: date, options: [])! return self.beginningOfWeek(week) } /** Creates a new date by adding the given number of weeks to the given date and truncating to the first second of the date's week. - parameter date: The date to which to add weeks. - parameter delta: The number of weeks to be added - returns: The newly created date. */ static public func weeksAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.weeksAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of weeks from the given date and truncating to the first second of the date's week. - parameter date: The date from which to subtract weeks. - parameter delta: The number of weeks to be subtracted - returns: The newly created date. */ public func weeksBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.weeksAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of weeks from the given date and truncating to the first second of the date's week. - parameter date: The date from which to subtract weeks. - parameter delta: The number of weeks to be subtracted - returns: The newly created date. */ static public func weeksBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.weeksBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the week prior to the given date. - parameter date: The date for which to find the previous week - returns: The newly created date. */ public func weekBefore(date:NSDate) -> NSDate { return self.weeksBefore(date) } /** Creates a new date at the first second of the week prior to the given date. - parameter date: The date for which to find the previous week - returns: The newly created date. */ static public func weekBefore(date:NSDate) -> NSDate { return sharedInstance.weekBefore(date) } /** Creates a new date at the first second of the week following the given date. - parameter date: The date for which to find the next week - returns: The newly created date. */ public func weekAfter(date:NSDate) -> NSDate { return self.weeksAfter(date) } /** Creates a new date at the first second of the week following the given date. - parameter date: The date for which to find the next week - returns: The newly created date. */ static public func weekAfter(date:NSDate) -> NSDate { return sharedInstance.weekAfter(date) } // MARK: months /************** *** PLURAL *** **************/ /** Creates a new date by adding the given number of months to the given date and truncating to the first second of the date's month. - parameter date: The date to which to add months. - parameter delta: The number of months to be added - returns: The newly created date. */ public func monthsAfter(date:NSDate, delta:Int = 1) -> NSDate { let month = self.calendar.dateByAddingUnit(.Month, value: delta, toDate: date, options: [])! return self.beginningOfMonth(month) } /** Creates a new date by adding the given number of months to the given date and truncating to the first second of the date's month. - parameter date: The date to which to add months. - parameter delta: The number of months to be added - returns: The newly created date. */ static public func monthsAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.monthsAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of months from the given date and truncating to the first second of the date's months. - parameter date: The date from which to subtract months. - parameter delta: The number of months to be subtracted - returns: The newly created date. */ public func monthsBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.monthsAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of months from the given date and truncating to the first second of the date's month. - parameter date: The date from which to add months. - parameter delta: The number of months to be subtracted. - returns: The newly created date. */ static public func monthsBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.monthsBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the month prior to the given date. - parameter date: The date for which to find the previous month. - returns: The newly created date. */ public func monthBefore(date:NSDate) -> NSDate { let previousMonth = self.calendar.dateByAddingUnit(.Month, value: -1, toDate: date, options: [])! return self.beginningOfMonth(previousMonth) } /** Creates a new date at the first second of the month prior to the given date. - parameter date: The date for which to find the previous month. - returns: The newly created date. */ static public func monthBefore(date:NSDate) -> NSDate { return sharedInstance.monthBefore(date) } /** Creates a new date at the first second of the month following the given date. - parameter date: The date for which to find the next month. - returns: The newly created date. */ public func monthAfter(date:NSDate) -> NSDate { let nextMonth = self.calendar.dateByAddingUnit(.Month, value: 1, toDate: date, options: [])! return self.beginningOfMonth(nextMonth) } /** Creates a new date at the first second of the month following the given date. - parameter date: The date for which to find the next month. - returns: The newly created date. */ static public func monthAfter(date:NSDate) -> NSDate { return sharedInstance.monthAfter(date) } // MARK: years /************** *** SINGLE *** **************/ /** Creates a new date by adding the given number of years to the given date and truncating to the first second of the date's year. - parameter date: The date to which to add years. - parameter delta: The number of years to be added. - returns: The newly created date. */ public func yearsAfter(date:NSDate, delta:Int = 1) -> NSDate { let year = self.calendar.dateByAddingUnit(.Year, value: delta, toDate: date, options: [])! return self.beginningOfYear(year) } /** Creates a new date by adding the given number of years to the given date and truncating to the first second of the date's year. - parameter date: The date to which to add year. - parameter delta: The number of years to be added. - returns: The newly created date. */ static public func yearsAfter(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.yearsAfter(date, delta:delta) } /** Creates a new date by subtracting the given number of years from the given date and truncating to the first second of the date's year. - parameter date: The date from which to add years. - parameter delta: The number of years to be subtracted. - returns: The newly created date. */ public func yearsBefore(date:NSDate, delta:Int = 1) -> NSDate { return self.yearsAfter(date, delta:-delta) } /** Creates a new date by subtracting the given number of years from the given date and truncating to the first second of the date's year. - parameter date: The date from which to add year. - parameter delta: The number of years to be subtracted. - returns: The newly created date. */ static public func yearsBefore(date:NSDate, delta:Int = 1) -> NSDate { return sharedInstance.yearsBefore(date, delta:delta) } /************** *** SINGLE *** **************/ /** Creates a new date at the first second of the year prior to the given date. - parameter date: The date for which to find the previous year. - returns: The newly created date. */ public func yearBefore(date:NSDate) -> NSDate { return self.yearsBefore(date) } /** Creates a new date at the first second of the year prior to the given date. - parameter date: The date for which to find the previous year. - returns: The newly created date. */ static public func yearBefore(date:NSDate) -> NSDate { return sharedInstance.yearBefore(date) } /** Creates a new date at the first second of the year following the given date. - parameter date: The date for which to find the next year. - returns: The newly created date. */ public func yearAfter(date:NSDate) -> NSDate { return self.yearsAfter(date) } /** Creates a new date at the first second of the year following the given date. - parameter date: The date for which to find the next year. - returns: The newly created date. */ static public func yearAfter(date:NSDate) -> NSDate { return sharedInstance.yearAfter(date) } }
mit
14728e7a601ab64afa74eebe989fc7be
31.546529
105
0.628529
4.630937
false
false
false
false
iosdevelopershq/code-challenges
CodeChallenge/Challenges/LetterCombinationsOfPhoneNumber/LetterCombinationsOfPhoneNumberChallenge.swift
1
1597
// // LetterCombinationsOfPhoneNumberChallenge.swift // CodeChallenge // // Created by Ryan Arana on 11/1/15. // Copyright © 2015 iosdevelopers. All rights reserved. // import Foundation /** https://leetcode.com/problems/letter-combinations-of-a-phone-number/ Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. ![keypad](http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png) Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. */ struct LetterCombinationsOfPhoneNumberChallenge: CodeChallengeType { typealias InputType = String typealias OutputType = [String] let title = "Letter Combinations of Phone Number" let entries: [CodeChallengeEntry<LetterCombinationsOfPhoneNumberChallenge>] = [ bugKrushaLetterCombinationOfPhoneNumberEntry, LoganWrightLetterCombinationOfPhoneNumberEntry, juliand665LetterCombinationOfPhoneNumberEntry ] func generateDataset() -> [InputType] { return ["23"] } func verifyOutput(_ output: OutputType, forInput input: InputType) -> Bool { guard let expected = verificationDictionary[input] else { return false } return output.sorted(by: <) == expected.sorted(by: <) } fileprivate let verificationDictionary = [ "23": ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"] ] }
mit
53dd8591ccbfaf642bc8887cf4aea09f
32.25
121
0.696742
4.050761
false
false
false
false
milseman/swift
stdlib/public/core/Reverse.swift
10
19479
//===--- Reverse.swift - Sequence and collection reversal -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension MutableCollection where Self : BidirectionalCollection { /// Reverses the elements of the collection in place. /// /// The following example reverses the elements of an array of characters: /// /// var characters: [Character] = ["C", "a", "f", "é"] /// characters.reverse() /// print(characters) /// // Prints "["é", "f", "a", "C"] /// /// - Complexity: O(*n*), where *n* is the number of elements in the /// collection. public mutating func reverse() { if isEmpty { return } var f = startIndex var l = index(before: endIndex) while f < l { swapAt(f, l) formIndex(after: &f) formIndex(before: &l) } } } /// An iterator that can be much faster than the iterator of a reversed slice. // TODO: See about using this in more places @_fixed_layout public struct _ReverseIndexingIterator< Elements : BidirectionalCollection > : IteratorProtocol, Sequence { @_inlineable @inline(__always) /// Creates an iterator over the given collection. public /// @testable init(_elements: Elements, _position: Elements.Index) { self._elements = _elements self._position = _position } @_inlineable @inline(__always) public mutating func next() -> Elements.Element? { guard _fastPath(_position != _elements.startIndex) else { return nil } _position = _elements.index(before: _position) return _elements[_position] } @_versioned internal let _elements: Elements @_versioned internal var _position: Elements.Index } // FIXME(ABI)#59 (Conditional Conformance): we should have just one type, // `ReversedCollection`, that has conditional conformances to // `RandomAccessCollection`, and possibly `MutableCollection` and // `RangeReplaceableCollection`. // rdar://problem/17144340 // FIXME: swift-3-indexing-model - should gyb ReversedXxx & ReversedRandomAccessXxx /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. @_fixed_layout public struct ReversedIndex<Base : Collection> : Comparable { /// Creates a new index into a reversed collection for the position before /// the specified index. /// /// When you create an index into a reversed collection using `base`, an /// index from the underlying collection, the resulting index is the /// position of the element *before* the element referenced by `base`. The /// following example creates a new `ReversedIndex` from the index of the /// `"a"` character in a string's character view. /// /// let name = "Horatio" /// let aIndex = name.index(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() /// let i = ReversedIndex<String>(aIndex) /// // reversedName[i] == "r" /// /// The element at the position created using `ReversedIndex<...>(aIndex)` is /// `"r"`, the character before `"a"` in the `name` string. /// /// - Parameter base: The position after the element to create an index for. @_inlineable public init(_ base: Base.Index) { self.base = base } /// The position after this position in the underlying collection. /// /// To find the position that corresponds with this index in the original, /// underlying collection, use that collection's `index(before:)` method /// with the `base` property. /// /// The following example declares a function that returns the index of the /// last even number in the passed array, if one is found. First, the /// function finds the position of the last even number as a `ReversedIndex` /// in a reversed view of the array of numbers. Next, the function calls the /// array's `index(before:)` method to return the correct position in the /// passed array. /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) /// } /// /// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51] /// if let lastEven = indexOfLastEven(numbers) { /// print("Last even number: \(numbers[lastEven])") /// } /// // Prints "Last even number: 40" public let base: Base.Index @_inlineable public static func == ( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { return lhs.base == rhs.base } @_inlineable public static func < ( lhs: ReversedIndex<Base>, rhs: ReversedIndex<Base> ) -> Bool { // Note ReversedIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } } /// A collection that presents the elements of its base collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having bidirectional indices. /// /// The `reversed()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reversed()` does not create new storage /// * `c.reversed().map(f)` maps eagerly and returns a new array /// * `c.lazy.reversed().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReversedRandomAccessCollection` @_fixed_layout public struct ReversedCollection< Base : BidirectionalCollection > : BidirectionalCollection { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) @_versioned @_inlineable internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedIndex<Base> public typealias IndexDistance = Base.IndexDistance @_fixed_layout public struct Iterator : IteratorProtocol, Sequence { @_inlineable @inline(__always) public /// @testable init(elements: Base, endPosition: Base.Index) { self._elements = elements self._position = endPosition } @_inlineable @inline(__always) public mutating func next() -> Base.Iterator.Element? { guard _fastPath(_position != _elements.startIndex) else { return nil } _position = _elements.index(before: _position) return _elements[_position] } @_versioned internal let _elements: Base @_versioned internal var _position: Base.Index } @_inlineable @inline(__always) public func makeIterator() -> Iterator { return Iterator(elements: _base, endPosition: _base.endIndex) } @_inlineable public var startIndex: Index { return ReversedIndex(_base.endIndex) } @_inlineable public var endIndex: Index { return ReversedIndex(_base.startIndex) } @_inlineable public func index(after i: Index) -> Index { return ReversedIndex(_base.index(before: i.base)) } @_inlineable public func index(before i: Index) -> Index { return ReversedIndex(_base.index(after: i.base)) } @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return ReversedIndex(_base.index(i.base, offsetBy: -n)) } @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { ReversedIndex($0) } } @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { return _base.distance(from: end.base, to: start.base) } @_inlineable public subscript(position: Index) -> Base.Element { return _base[_base.index(before: position.base)] } @_inlineable public subscript(bounds: Range<Index>) -> BidirectionalSlice<ReversedCollection> { return BidirectionalSlice(base: self, bounds: bounds) } public let _base: Base } /// An index that traverses the same positions as an underlying index, /// with inverted traversal direction. @_fixed_layout public struct ReversedRandomAccessIndex< Base : RandomAccessCollection > : Comparable { /// Creates a new index into a reversed collection for the position before /// the specified index. /// /// When you create an index into a reversed collection using the index /// passed as `base`, an index from the underlying collection, the resulting /// index is the position of the element *before* the element referenced by /// `base`. The following example creates a new `ReversedIndex` from the /// index of the `"a"` character in a string's character view. /// /// let name = "Horatio" /// let aIndex = name.index(of: "a")! /// // name[aIndex] == "a" /// /// let reversedName = name.reversed() /// let i = ReversedIndex<String>(aIndex) /// // reversedName[i] == "r" /// /// The element at the position created using `ReversedIndex<...>(aIndex)` is /// `"r"`, the character before `"a"` in the `name` string. Viewed from the /// perspective of the `reversedCharacters` collection, of course, `"r"` is /// the element *after* `"a"`. /// /// - Parameter base: The position after the element to create an index for. @_inlineable public init(_ base: Base.Index) { self.base = base } /// The position after this position in the underlying collection. /// /// To find the position that corresponds with this index in the original, /// underlying collection, use that collection's `index(before:)` method /// with this index's `base` property. /// /// The following example declares a function that returns the index of the /// last even number in the passed array, if one is found. First, the /// function finds the position of the last even number as a `ReversedIndex` /// in a reversed view of the array of numbers. Next, the function calls the /// array's `index(before:)` method to return the correct position in the /// passed array. /// /// func indexOfLastEven(_ numbers: [Int]) -> Int? { /// let reversedNumbers = numbers.reversed() /// guard let i = reversedNumbers.index(where: { $0 % 2 == 0 }) /// else { return nil } /// /// return numbers.index(before: i.base) /// } /// /// let numbers = [10, 20, 13, 19, 30, 52, 17, 40, 51] /// if let lastEven = indexOfLastEven(numbers) { /// print("Last even number: \(numbers[lastEven])") /// } /// // Prints "Last even number: 40" public let base: Base.Index @_inlineable public static func == ( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { return lhs.base == rhs.base } @_inlineable public static func < ( lhs: ReversedRandomAccessIndex<Base>, rhs: ReversedRandomAccessIndex<Base> ) -> Bool { // Note ReversedRandomAccessIndex has inverted logic compared to base Base.Index return lhs.base > rhs.base } } /// A collection that presents the elements of its base collection /// in reverse order. /// /// - Note: This type is the result of `x.reversed()` where `x` is a /// collection having random access indices. /// - See also: `ReversedCollection` @_fixed_layout public struct ReversedRandomAccessCollection< Base : RandomAccessCollection > : RandomAccessCollection { // FIXME: swift-3-indexing-model: tests for ReversedRandomAccessIndex and // ReversedRandomAccessCollection. /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) @_versioned @_inlineable internal init(_base: Base) { self._base = _base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReversedRandomAccessIndex<Base> public typealias IndexDistance = Base.IndexDistance /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. public typealias Iterator = IndexingIterator< ReversedRandomAccessCollection > @_inlineable public var startIndex: Index { return ReversedRandomAccessIndex(_base.endIndex) } @_inlineable public var endIndex: Index { return ReversedRandomAccessIndex(_base.startIndex) } @_inlineable public func index(after i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(before: i.base)) } @_inlineable public func index(before i: Index) -> Index { return ReversedRandomAccessIndex(_base.index(after: i.base)) } @_inlineable public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return ReversedRandomAccessIndex(_base.index(i.base, offsetBy: -n)) } @_inlineable public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: `-n` can trap on Int.min. // FIXME: swift-3-indexing-model: tests. return _base.index(i.base, offsetBy: -n, limitedBy: limit.base).map { Index($0) } } @_inlineable public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: tests. return _base.distance(from: end.base, to: start.base) } @_inlineable public subscript(position: Index) -> Base.Element { return _base[_base.index(before: position.base)] } // FIXME: swift-3-indexing-model: the rest of methods. public let _base: Base } extension BidirectionalCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A `ReversedCollection` /// instance wraps an underlying collection and provides access to its /// elements in reverse order. This example prints the characters of a /// string in reverse order: /// /// let word = "Backwards" /// for char in word.reversed() { /// print(char, terminator: "") /// } /// // Prints "sdrawkcaB" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of a string, reverse its /// characters and initialize a new `String` instance from the result. /// /// let reversedWord = String(word.reversed()) /// print(reversedWord) /// // Prints "sdrawkcaB" /// /// - Complexity: O(1) @_inlineable public func reversed() -> ReversedCollection<Self> { return ReversedCollection(_base: self) } } extension RandomAccessCollection { /// Returns a view presenting the elements of the collection in reverse /// order. /// /// You can reverse a collection without allocating new space for its /// elements by calling this `reversed()` method. A /// `ReversedRandomAccessCollection` instance wraps an underlying collection /// and provides access to its elements in reverse order. This example /// prints the elements of an array in reverse order: /// /// let numbers = [3, 5, 7] /// for number in numbers.reversed() { /// print(number) /// } /// // Prints "7" /// // Prints "5" /// // Prints "3" /// /// If you need a reversed collection of the same type, you may be able to /// use the collection's sequence-based or collection-based initializer. For /// example, to get the reversed version of an array, initialize a new /// `Array` instance from the result of this `reversed()` method. /// /// let reversedNumbers = Array(numbers.reversed()) /// print(reversedNumbers) /// // Prints "[7, 5, 3]" /// /// - Complexity: O(1) @_inlineable public func reversed() -> ReversedRandomAccessCollection<Self> { return ReversedRandomAccessCollection(_base: self) } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { /// Returns the elements of the collection in reverse order. /// /// - Complexity: O(1) @_inlineable public func reversed() -> LazyBidirectionalCollection< ReversedCollection<Elements> > { return ReversedCollection(_base: elements).lazy } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { /// Returns the elements of the collection in reverse order. /// /// - Complexity: O(1) @_inlineable public func reversed() -> LazyRandomAccessCollection< ReversedRandomAccessCollection<Elements> > { return ReversedRandomAccessCollection(_base: elements).lazy } } @available(*, unavailable, renamed: "ReversedCollection") public typealias ReverseCollection<Base : BidirectionalCollection> = ReversedCollection<Base> @available(*, unavailable, renamed: "ReversedRandomAccessCollection") public typealias ReverseRandomAccessCollection<Base : RandomAccessCollection> = ReversedRandomAccessCollection<Base> extension ReversedCollection { @available(*, unavailable, renamed: "BidirectionalCollection.reversed(self:)") public init(_ base: Base) { Builtin.unreachable() } } extension ReversedRandomAccessCollection { @available(*, unavailable, renamed: "RandomAccessCollection.reversed(self:)") public init(_ base: Base) { Builtin.unreachable() } } extension BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedCollection<Self> { Builtin.unreachable() } } extension RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> ReversedRandomAccessCollection<Self> { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : BidirectionalCollection, Elements : BidirectionalCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedCollection<Elements> > { Builtin.unreachable() } } extension LazyCollectionProtocol where Self : RandomAccessCollection, Elements : RandomAccessCollection { @available(*, unavailable, renamed: "reversed()") public func reverse() -> LazyCollection< ReversedRandomAccessCollection<Elements> > { Builtin.unreachable() } } // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
apache-2.0
b4e6a183684f3c031449ead6006aea91
31.300166
93
0.6692
4.355322
false
false
false
false
skedgo/tripkit-ios
Sources/TripKit/model/API/LocationAPIModel.swift
1
12686
// // TKHelperTypes.swift // TripKit // // Created by Adrian Schoenig on 28/10/16. // Copyright © 2016 SkedGo. All rights reserved. // import Foundation import CoreLocation protocol RealTimeUpdatable { var hasRealTime: Bool { get } } extension TKAPI { public struct BikePodInfo: Codable, Hashable, RealTimeUpdatable { // static information public let identifier: String public let operatorInfo: TKAPI.CompanyInfo public let source: TKAPI.DataAttribution? public let deepLink: URL? // availability information (usually real-time) public let inService: Bool public let availableBikes: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case operatorInfo = "operator" case source case deepLink case inService case availableBikes case totalSpaces case lastUpdate } public var availableSpaces: Int? { guard let total = totalSpaces, let bikes = availableBikes else { return nil } // available bikes can exceed number of spaces! return max(0, total - bikes) } public var hasRealTime: Bool { return inService && availableBikes != nil } } public struct CarPodInfo: Codable, Hashable, RealTimeUpdatable { // static information public let identifier: String public let operatorInfo: TKAPI.CompanyInfo public let deepLink: URL? // real-time availability information public let availabilityMode: TKAPI.AvailabilityMode? public let availabilities: [TKAPI.CarAvailability]? public let inService: Bool? public let availableVehicles: Int? public let availableChargingSpaces: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case operatorInfo = "operator" case deepLink case availabilityMode case availabilities case inService case availableVehicles case availableChargingSpaces case totalSpaces case lastUpdate } public var availableSpaces: Int? { guard let total = totalSpaces, let vehicles = availableVehicles else { return nil } // available vehicles can exceed number of spaces! return max(0, total - vehicles) } public var hasRealTime: Bool { return inService != false && availableVehicles != nil } } public struct CarParkInfo: Codable, Hashable, RealTimeUpdatable { public enum EntranceType: String, Codable { case entranceAndExit = "ENTRANCE_EXIT" case entranceOnly = "ENTRANCE_ONLY" case exitOnly = "EXIT_ONLY" case pedestrian = "PEDESTRIAN" case disabledPedestrian = "DISABLED_PEDESTRIAN" case permit = "PERMIT" } public struct Entrance: Codable, Hashable { public let type: EntranceType public let lat: CLLocationDegrees public let lng: CLLocationDegrees public let address: String? } public let identifier: String public let name: String public let operatorInfo: TKAPI.CompanyInfo? public let source: TKAPI.DataAttribution? public let deepLink: URL? /// Additional information text from the provider. Can be long and over multiple lines. public let info: String? /// The polygon defining the parking area as an encoded polyline. /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedParkingArea: String? public let entrances: [Entrance]? public let openingHours: TKAPI.OpeningHours? public let pricingTables: [TKAPI.PricingTable]? public let availableSpaces: Int? public let totalSpaces: Int? public let lastUpdate: Date? private enum CodingKeys: String, CodingKey { case identifier case name case operatorInfo = "operator" case source case deepLink case encodedParkingArea case info case entrances case openingHours case pricingTables case availableSpaces case totalSpaces case lastUpdate } public var hasRealTime: Bool { return availableSpaces != nil } } public struct CarRentalInfo: Codable, Hashable, RealTimeUpdatable { public let identifier: String public let company: TKAPI.CompanyInfo public let openingHours: TKAPI.OpeningHours? public let source: TKAPI.DataAttribution? public var hasRealTime: Bool { false } } @available(*, unavailable, renamed: "SharedVehicleInfo") public typealias FreeFloatingVehicleInfo = SharedVehicleInfo public enum VehicleFormFactor: String, Codable { case bicycle = "BICYCLE" case car = "CAR" case scooter = "SCOOTER" case moped = "MOPED" case other = "OTHER" } public enum VehiclePropulsionType: String, Codable { case human = "HUMAN" case electric = "ELECTRIC" case electricAssist = "ELECTRIC_ASSIST" case combustion = "COMBUSTION" } public struct VehicleTypeInfo: Codable, Hashable { public let name: String? public let formFactor: VehicleFormFactor public let propulsionType: VehiclePropulsionType? public let maxRangeMeters: Int? } public struct SharedVehicleInfo: Codable, Hashable, RealTimeUpdatable { public let identifier: String public let name: String? public let details: String? public let operatorInfo: TKAPI.CompanyInfo public let vehicleType: VehicleTypeInfo public let source: TKAPI.DataAttribution? public let deepLink: URL? public let imageURL: URL? public let licensePlate: String? public let isDisabled: Bool public let isReserved: Bool? public let batteryLevel: Int? // percentage, i.e., 0-100 public let currentRange: CLLocationDistance? // metres public let lastReported: Date? private enum CodingKeys: String, CodingKey { case identifier case name case batteryLevel case operatorInfo = "operator" case licensePlate case vehicleType = "vehicleTypeInfo" case isDisabled = "disabled" case isReserved = "reserved" case lastReported case currentRange = "currentRangeMeters" case imageURL // NOT DOCUMENTED case details = "description" case source case deepLink = "deepLinks" // NOT DOCUMENTED } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) identifier = try container.decode(String.self, forKey: .identifier) operatorInfo = try container.decode(TKAPI.CompanyInfo.self, forKey: .operatorInfo) vehicleType = try container.decode(VehicleTypeInfo.self, forKey: .vehicleType) isDisabled = try container.decode(Bool.self, forKey: .isDisabled) source = try? container.decode(TKAPI.DataAttribution.self, forKey: .source) if let deepLinkDict = try? container.decode([String: String].self, forKey: .deepLink), let link = deepLinkDict["ios"], let linkURL = URL(string: link) { deepLink = linkURL } else { deepLink = nil } name = try? container.decode(String.self, forKey: .name) details = try? container.decode(String.self, forKey: .details) imageURL = try? container.decode(URL.self, forKey: .imageURL) licensePlate = try? container.decode(String.self, forKey: .licensePlate) isReserved = try? container.decode(Bool.self, forKey: .isReserved) batteryLevel = try? container.decode(Int.self, forKey: .batteryLevel) currentRange = try? container.decode(CLLocationDistance.self, forKey: .currentRange) lastReported = try? container.decode(Date.self, forKey: .lastReported) } public var hasRealTime: Bool { true } public var isAvailable: Bool { !isDisabled && (isReserved != true) } } public struct OnStreetParkingInfo: Codable, Hashable, RealTimeUpdatable { public enum PaymentType: String, Codable { case meter = "METER" case creditCard = "CREDIT_CARD" case phone = "PHONE" case coins = "COINS" case app = "APP" } public enum AvailableContent: String, Codable, CaseIterable { public init(from decoder: Decoder) throws { // We do this manually rather than using the default Codable // implementation, to flag unknown content as `.unknown`. let single = try decoder.singleValueContainer() let string = try single.decode(String.self) let match = AvailableContent.allCases.first { $0.rawValue == string } if let known = match { self = known } else { self = .unknown } } public func encode(to encoder: Encoder) throws { var single = encoder.singleValueContainer() try single.encode(rawValue) } case restrictions case paymentTypes case totalSpaces case availableSpaces case actualRate case unknown } public enum Vacancy: String, Codable { case unknown = "UNKNOWN" case full = "NO_VACANCY" case limited = "LIMITED_VACANCY" case plenty = "PLENTY_VACANCY" } public struct Restriction: Codable, Hashable { public let color: String public let maximumParkingMinutes: Int public let parkingSymbol: String public let daysAndTimes: OpeningHours public let type: String } public let actualRate: String? public let identifier: String public let description: String public let availableContent: [AvailableContent]? public let source: TKAPI.DataAttribution? public let paymentTypes: [PaymentType]? public let restrictions: [Restriction]? public let availableSpaces: Int? public let totalSpaces: Int? public let occupiedSpaces: Int? public let parkingVacancy: Vacancy? public let lastUpdate: Date? /// The polyline defining the parking area along the street as an encoded polyline. /// /// This is optional as some on-street parking isn't defined by a line, /// but by an area. See `encodedPolygon` /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedPolyline: String? /// The polygon defining the parking area as an encoded polyline. /// /// This is optional as most on-street parking isn't defined by an area, /// but by a line. See `encodedPolyline` /// /// See `CLLocationCoordinate2D.decodePolyline` public let encodedPolygon: String? public var hasRealTime: Bool { return availableSpaces != nil } } public struct LocationInfo : Codable, Hashable, RealTimeUpdatable { public struct Details: Codable, Hashable { public let w3w: String? public let w3wInfoURL: URL? } public let details: Details? public let alerts: [Alert]? public let stop: TKStopCoordinate? public let bikePod: TKAPI.BikePodInfo? public let carPod: TKAPI.CarPodInfo? public let carPark: TKAPI.CarParkInfo? public let carRental: TKAPI.CarRentalInfo? public let freeFloating: TKAPI.SharedVehicleInfo? // TODO: Also add to API specs public let onStreetParking: TKAPI.OnStreetParkingInfo? public var hasRealTime: Bool { let sources: [RealTimeUpdatable?] = [bikePod, carPod, carPod, carRental, freeFloating, onStreetParking] return sources.contains { $0?.hasRealTime == true } } } public struct LocationsResponse: Codable, Hashable { public static let empty: LocationsResponse = LocationsResponse(groups: []) public let groups: [Group] public struct Group: Codable, Hashable { public let key: String public let hashCode: Int public let stops: [TKStopCoordinate]? public let bikePods: [TKBikePodLocation]? public let carPods: [TKCarPodLocation]? public let carParks: [TKCarParkLocation]? public let carRentals: [TKCarRentalLocation]? public let freeFloating: [TKFreeFloatingVehicleLocation]? public let onStreetParking: [TKOnStreetParkingLocation]? public var all: [TKModeCoordinate] { return (stops ?? []) as [TKModeCoordinate] + (bikePods ?? []) as [TKModeCoordinate] + (carPods ?? []) as [TKModeCoordinate] + (carParks ?? []) as [TKModeCoordinate] + (carRentals ?? []) as [TKModeCoordinate] + (freeFloating ?? []) as [TKModeCoordinate] + (onStreetParking ?? []) as [TKModeCoordinate] } } } }
apache-2.0
3b8f98a3bfdaec6d16985a3b6eb6ec53
30.633416
109
0.670162
4.733209
false
false
false
false
franklinsch/usagi
iOS/usagi-iOS/usagi-iOS/AddTaskTableViewController.swift
1
4095
// // AddTaskTableViewController.swift // usagi-iOS // // Created by Franklin Schrans on 31/01/2016. // Copyright © 2016 Franklin Schrans. All rights reserved. // import UIKit class AddTaskTableViewController: UITableViewController { var projectName: String? var tasks = [Project]() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return tasks.count } @IBAction func addNewTask(sender: UIStoryboardSegue) { guard let sourceViewController = sender.sourceViewController as? NewTaskTableViewController else { fatalError() } let newTask = Project(name: sourceViewController.taskNameField.text!, description: sourceViewController.descriptionField.text!, participants: [], subtasks: [], progress: 0, timeLeft: "1h00", dependsOnTasks: sourceViewController.dependencies) tasks.append(newTask) tableView.reloadData() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("taskCell", forIndexPath: indexPath) let task = tasks[indexPath.row] cell.textLabel!.text = task.name return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "newTaskSegue" { guard let destinationViewController = segue.destinationViewController as? NewTaskTableViewController else { fatalError() } destinationViewController.projectName = projectName destinationViewController.tasks = tasks } } }
mit
84715c10776f2ef80808fe9e8338bf01
35.553571
249
0.685149
5.662517
false
false
false
false
cooliean/CLLKit
XLForm/Examples/Swift/SwiftExample/PredicateExamples/PredicateFormViewController.swift
14
5028
// // PredicateFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. class PredicateFormViewController : XLFormViewController { private struct Tags { static let Text = "text" static let Integer = "integer" static let Switch = "switch" static let Date = "date" static let Account = "account" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initializeForm() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeForm() } func initializeForm() { let form : XLFormDescriptor var section : XLFormSectionDescriptor var row : XLFormRowDescriptor form = XLFormDescriptor(title: "Predicates example") section = XLFormSectionDescriptor() section.title = "Independent rows" form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.Text, rowType: XLFormRowDescriptorTypeAccount, title:"Text") row.cellConfigAtConfigure["textField.placeholder"] = "Type disable" section.addFormRow(row) row = XLFormRowDescriptor(tag: Tags.Integer, rowType: XLFormRowDescriptorTypeInteger, title:"Integer") row.hidden = NSPredicate(format: "$\(Tags.Switch).value==0") section.addFormRow(row) row = XLFormRowDescriptor(tag: Tags.Switch, rowType: XLFormRowDescriptorTypeBooleanSwitch, title:"Boolean") row.value = true section.addFormRow(row) form.addFormSection(section) section = XLFormSectionDescriptor() section.title = "Dependent section" section.footerTitle = "Type disable in the textfield, a number between 18 and 60 in the integer field or use the switch to disable the last row. By doing all three the last section will hide.\nThe integer field hides when the boolean switch is set to 0." form.addFormSection(section) // Predicate Disabling row = XLFormRowDescriptor(tag: Tags.Date, rowType: XLFormRowDescriptorTypeDateInline, title:"Disabled") row.value = NSDate() section.addFormRow(row) row.disabled = NSPredicate(format: "$\(Tags.Text).value contains[c] 'disable' OR ($\(Tags.Integer).value between {18, 60}) OR ($\(Tags.Switch).value == 0)") section.hidden = NSPredicate(format: "($\(Tags.Text).value contains[c] 'disable') AND ($\(Tags.Integer).value between {18, 60}) AND ($\(Tags.Switch).value == 0)") section = XLFormSectionDescriptor() section.title = "More predicates..." section.footerTitle = "This row hides when the row of the previous section is disabled and the textfield in the first section contains \"out\"\n\nPredicateFormViewController.swift" form.addFormSection(section) row = XLFormRowDescriptor(tag: "thirds", rowType:XLFormRowDescriptorTypeAccount, title:"Account") section.addFormRow(row) row.hidden = NSPredicate(format: "$\(Tags.Date).isDisabled == 1 AND $\(Tags.Text).value contains[c] 'Out'") row.onChangeBlock = { [weak self] oldValue, newValue, _ in let noValue = "No Value" let message = "Old value: \(oldValue ?? noValue), New value: \(newValue ?? noValue)" let alertView = UIAlertController(title: "Account Field changed", message: message, preferredStyle: .ActionSheet) alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) self?.navigationController?.presentViewController(alertView, animated: true, completion: nil) } self.form = form } }
mit
cfb41015a96d1da59839b5dbf1699315
40.553719
262
0.66965
4.939096
false
false
false
false
jmgc/swift
test/Driver/Dependencies/driver-show-incremental-mutual-fine.swift
1
1665
/// main <==> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/mutual-with-swiftdeps-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-DAG: Handled main.swift // CHECK-FIRST-DAG: Handled other.swift // CHECK-FIRST-DAG: Disabling incremental build: could not read build record // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // CHECK-SECOND-NOT: Queuing // RUN: touch -t 201401240006 %t/other.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD: Queuing (initial): {compile: other.o <= other.swift} // CHECK-THIRD-DAG: Queuing because of the initial set: {compile: main.o <= main.swift} // CHECK-THIRD-DAG: interface of top-level name 'a' in other.swift -> interface of source file main.swiftdeps
apache-2.0
f2fbfce1516d6a05a99ee7d0d0579841
86.631579
341
0.72973
3.27112
false
false
true
false
quadro5/swift3_L
Swift_api.playground/Pages/Pass Reference Value.xcplaygroundpage/Contents.swift
1
1261
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) func test() { var num = 1 func passRef(_ input: inout Int) { print("input: \(input)") print("num: \(num)") input = 2 print("input: \(input)") print("num: \(num)") } print("before num: \(num)") passRef(&num) print("after num: \(num)") } test() print("\ntestArray") func testArray() { var num = [1, 2, 3] func passRef(_ input: inout [Int]) { print("input: \(input)") print("num: \(num)") input = [1,2] print("input: \(input)") print("num: \(num)") } print("before num: \(num)") passRef(&num) print("after num: \(num)") } testArray() print("\ntestArray2") class TestArray { var num = [1, 2, 3] func testArray() { print("before num: \(num)") passRef(&num) print("after num: \(num)") } func passRef(_ input: inout [Int]) { print("input: \(input)") print("num: \(self.num)") input = [1,2] print("input: \(input)") print("num: \(self.num)") } } let testArrayClass = TestArray() testArrayClass.testArray()
unlicense
07c3794ae661c5649404afe912a077a6
16.040541
40
0.485329
3.572238
false
true
false
false
yangyueguang/MyCocoaPods
Extension/Collection+Extension.swift
1
6247
// // Collection+Extension.swift // MyCocoaPods // // Created by Chao Xue 薛超 on 2018/12/12. // Copyright © 2018 Super. All rights reserved. // import Foundation public extension Array{ /// 返回对象数组对应的json数组 前提element一定是AnyObject类型 func jsonArray() -> [[String: Any]] { var jsonObjects: [[String: Any]] = [] for element in self { let model: AnyObject = element as AnyObject let jsonDict = model.dictionaryRepresentation() jsonObjects.append(jsonDict) } return jsonObjects } /// 安全的取值 public func item(at index: Int) -> Element? { guard startIndex..<endIndex ~= index else { return nil } return self[index] } /// 交换 public mutating func swap(from index: Int, to: Int) { guard index != to, startIndex..<endIndex ~= index, startIndex..<endIndex ~= to else { return } swapAt(index, to) } /// 找到的元素的地址列表 public func indexs(where condition: (Element) throws -> Bool) rethrows -> [Int] { var indicies: [Int] = [] for (index, value) in lazy.enumerated() { if try condition(value) { indicies.append(index) } } return indicies } /// 是否全是某种条件的对象 public func isAll(Where condition: (Element) throws -> Bool) rethrows -> Bool { return try !contains { try !condition($0) } } /// 是否全不是某种条件对象 public func isNone(Where condition: (Element) throws -> Bool) rethrows -> Bool { return try !contains { try condition($0) } } /// 对满足条件的每个对象采取行动 public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows { for element in self where try condition(element) { try body(element) } } /// 数组筛选 public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] { #if swift(>=4.1) return try compactMap({ if try isIncluded($0) { return try transform($0) } return nil }) #else return try flatMap({ if try isIncluded($0) { return try transform($0) } return nil }) #endif } /// 分组 public func group(by size: Int) -> [[Element]] { guard size > 0, !isEmpty else { return [] } var value: Int = 0 var slices: [[Element]] = [] while value < count { slices.append(Array(self[Swift.max(value, startIndex)..<Swift.min(value + size, endIndex)])) value += size } return slices } /// 分为满足和不满足条件的两组 public func divided(by condition: (Element) throws -> Bool) rethrows -> (matching: [Element], nonMatching: [Element]) { var matching = [Element]() var nonMatching = [Element]() for element in self { if try condition(element) { matching.append(element) } else { nonMatching.append(element) } } return (matching, nonMatching) } /// 排序 public func sorted<T: Comparable>(by path: KeyPath<Element, T?>, ascending: Bool = true) -> [Element] { return sorted(by: { (lhs, rhs) -> Bool in guard let lhsValue = lhs[keyPath: path], let rhsValue = rhs[keyPath: path] else { return false } if ascending { return lhsValue < rhsValue } return lhsValue > rhsValue }) } } public extension Array where Element: Equatable { /// 是否包含 public func contains(_ elements: [Element]) -> Bool { guard !elements.isEmpty else { return true } var found = true for element in elements { if !contains(element) { found = false } } return found } /// 删除 public mutating func removeAll(_ items: [Element]) { guard !items.isEmpty else { return } self = filter { !items.contains($0) } } /// 去重 public mutating func removeDuplicates() { self = reduce(into: [Element]()) { if !$0.contains($1) { $0.append($1) } } } func index(_ e: Element) -> Int? { for (index, value) in lazy.enumerated() where value == e { return index } return nil } } public extension Dictionary{ func jsonString(prettify: Bool = false) -> String { guard JSONSerialization.isValidJSONObject(self) else { return "" } let options = (prettify == true) ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions() guard let jsonData = try? JSONSerialization.data(withJSONObject: self, options: options) else { return "" } return String(data: jsonData, encoding: .utf8) ?? "" } /// let result = dict + dict2 public static func + (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] { var result = lhs rhs.forEach { result[$0] = $1 } return result } /// dict += dict2 public static func += (lhs: inout [Key: Value], rhs: [Key: Value]) { rhs.forEach { lhs[$0] = $1} } /// let result = dict-["key1", "key2"] public static func - (lhs: [Key: Value], keys: [Key]) -> [Key: Value] { var result = lhs result.removeAll(keys: keys) return result } /// dict-=["key1", "key2"] public static func -= (lhs: inout [Key: Value], keys: [Key]) { lhs.removeAll(keys: keys) } public mutating func removeAll(keys: [Key]) { keys.forEach({ removeValue(forKey: $0)}) } public func count(where condition: @escaping ((key: Key, value: Value)) throws -> Bool) rethrows -> Int { var count: Int = 0 try self.forEach { if try condition($0) { count += 1 } } return count } }
mit
4ef3c420857e3fdbeb36ed68776aaf82
28.048077
126
0.542039
4.228132
false
false
false
false
SummerHF/SinaPractice
sina/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Anvil.swift
5
11271
// // LTMorphingLabel+Anvil.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2016 Lex Tang, http://lexrus.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 extension LTMorphingLabel { func AnvilLoad() { startClosures["Anvil\(LTMorphingPhases.Start)"] = { self.emitterView.removeAllEmitters() guard self.newRects.count > 0 else { return } let centerRect = self.newRects[Int(self.newRects.count / 2)] self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = kCAEmitterLayerSurface cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = 70 cell.emissionLongitude = CGFloat(-M_PI_2) cell.emissionRange = CGFloat(M_PI_4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = 10 cell.alphaSpeed = -0.5 / self.morphingDuration } self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize(width: 1, height: 1) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) layer.renderMode = kCAEmitterLayerSurface cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 130 cell.birthRate = 60 cell.velocity = CGFloat(80 + Int(arc4random_uniform(60))) cell.velocityRange = 100 cell.yAcceleration = -40 cell.xAcceleration = -70 cell.emissionLongitude = CGFloat(M_PI_2) cell.emissionRange = CGFloat(-M_PI_4) / 5.0 cell.lifetime = self.morphingDuration * 2.0 cell.spin = -10 cell.alphaSpeed = -0.5 / self.morphingDuration } self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3 ) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.CGColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(-M_PI_2) cell.emissionRange = CGFloat(M_PI_4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.CGColor cell.birthRate = 60 cell.velocity = 350 cell.yAcceleration = 0 cell.xAcceleration = CGFloat(-10 * Int(arc4random_uniform(10))) cell.emissionLongitude = CGFloat(M_PI_2) cell.emissionRange = CGFloat(-M_PI_4) / 5.0 cell.alphaSpeed = -2 cell.lifetime = self.morphingDuration } self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) { (layer, cell) in layer.emitterSize = CGSize( width: self.font.pointSize, height: 1 ) layer.emitterPosition = CGPoint( x: centerRect.origin.x, y: centerRect.origin.y + centerRect.size.height / 1.3) cell.scale = self.font.pointSize / 90.0 cell.scaleSpeed = self.font.pointSize / 40.0 cell.color = self.textColor.CGColor cell.birthRate = 60 cell.velocity = 250 cell.velocityRange = CGFloat(Int(arc4random_uniform(20)) + 30) cell.yAcceleration = 500 cell.emissionLongitude = 0 cell.emissionRange = CGFloat(M_PI_2) cell.alphaSpeed = -1 cell.lifetime = self.morphingDuration } } progressClosures["Anvil\(LTMorphingPhases.Progress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress)) } let j = Float(sin(Float(index))) * 1.7 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } effectClosures["Anvil\(LTMorphingPhases.Disappear)"] = { char, index, progress in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0) } effectClosures["Anvil\(LTMorphingPhases.Appear)"] = { char, index, progress in var rect = self.newRects[index] if progress < 1.0 { let easingValue = LTEasing.easeOutBounce(progress, 0.0, 1.0) rect.origin.y = CGFloat(Float(rect.origin.y) * easingValue) } if progress > self.morphingDuration * 0.5 { let end = self.morphingDuration * 0.55 self.emitterView.createEmitter( "fragments", particleName: "Fragment", duration: 0.6 ) {_ in}.update { (layer, cell) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "leftFragments", particleName: "Fragment", duration: 0.6 ) {_ in}.update { (layer, cell) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightFragments", particleName: "Fragment", duration: 0.6 ) {_ in}.update { (layer, cell) in if progress > end { layer.birthRate = 0 } }.play() } if progress > self.morphingDuration * 0.63 { let end = self.morphingDuration * 0.7 self.emitterView.createEmitter( "leftSmoke", particleName: "Smoke", duration: 0.6 ) {_ in}.update { (layer, cell) in if progress > end { layer.birthRate = 0 } }.play() self.emitterView.createEmitter( "rightSmoke", particleName: "Smoke", duration: 0.6 ) {_ in}.update { (layer, cell) in if progress > end { layer.birthRate = 0 } }.play() } return LTCharacterLimbo( char: char, rect: rect, alpha: CGFloat(self.morphingProgress), size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } } }
mit
6da6d37573c58c59aebbe0ab8dbb82d3
40.714815
84
0.464974
5.401918
false
false
false
false
sschiau/swift
test/Sema/enum_raw_representable.swift
2
6816
// RUN: %target-typecheck-verify-swift enum Foo : Int { case a, b, c } var raw1: Int = Foo.a.rawValue var raw2: Foo.RawValue = raw1 var cooked1: Foo? = Foo(rawValue: 0) var cooked2: Foo? = Foo(rawValue: 22) enum Bar : Double { case a, b, c } func localEnum() -> Int { enum LocalEnum : Int { case a, b, c } return LocalEnum.a.rawValue } enum MembersReferenceRawType : Int { case a, b, c init?(rawValue: Int) { self = MembersReferenceRawType(rawValue: rawValue)! } func successor() -> MembersReferenceRawType { return MembersReferenceRawType(rawValue: rawValue + 1)! } } func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] { return values.map { $0.rawValue } } func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] { return serialized.map { T(rawValue: $0)! } } var ints: [Int] = serialize([Foo.a, .b, .c]) var doubles: [Double] = serialize([Bar.a, .b, .c]) var foos: [Foo] = deserialize([1, 2, 3]) var bars: [Bar] = deserialize([1.2, 3.4, 5.6]) // Infer RawValue from witnesses. enum Color : Int { case red case blue init?(rawValue: Double) { return nil } var rawValue: Double { return 1.0 } } var colorRaw: Color.RawValue = 7.5 // Mismatched case types enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-note {{do you want to add protocol stubs?}} case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}} } // Recursive diagnostics issue in tryRawRepresentableFixIts() class Outer { // The setup is that we have to trigger the conformance check // while diagnosing the conversion here. For the purposes of // the test I'm putting everything inside a class in the right // order, but the problem can trigger with a multi-file // scenario too. let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}} enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}} case a } } // rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals func rdar32431736() { enum E : String { case A = "A" case B = "B" } let items1: [String] = ["A", "a"] let items2: [String]? = ["A"] let myE1: E = items1.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}} let myE2: E = items2?.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}} } // rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch enum E_32431165 : String { case foo = "foo" case bar = "bar" // expected-note {{'bar' declared here}} } func rdar32431165_1(_: E_32431165) {} func rdar32431165_1(_: Int) {} func rdar32431165_1(_: Int, _: E_32431165) {} rdar32431165_1(E_32431165.baz) // expected-error@-1 {{type 'E_32431165' has no member 'baz'; did you mean 'bar'?}} rdar32431165_1(.baz) // expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}} rdar32431165_1("") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{16-16=E_32431165(rawValue: }} {{18-18=)}} rdar32431165_1(42, "") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}} func rdar32431165_2(_: String) {} func rdar32431165_2(_: Int) {} func rdar32431165_2(_: Int, _: String) {} rdar32431165_2(E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{16-16=}} {{30-30=.rawValue}} rdar32431165_2(42, E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}} E_32431165.bar == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}} "bar" == E_32431165.bar // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}} func rdar32432253(_ condition: Bool = false) { let choice: E_32431165 = condition ? .foo : .bar let _ = choice == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}} } func sr8150_helper1(_: Int) {} func sr8150_helper1(_: Double) {} func sr8150_helper2(_: Double) {} func sr8150_helper2(_: Int) {} func sr8150_helper3(_: Foo) {} func sr8150_helper3(_: Bar) {} func sr8150_helper4(_: Bar) {} func sr8150_helper4(_: Foo) {} func sr8150(bar: Bar) { sr8150_helper1(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} sr8150_helper2(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} sr8150_helper3(0.0) // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}} sr8150_helper4(0.0) // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}} } class SR8150Box { var bar: Bar init(bar: Bar) { self.bar = bar } } // Bonus problem with mutable values being passed. func sr8150_mutable(obj: SR8150Box) { sr8150_helper1(obj.bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{25-25=.rawValue}} var bar = obj.bar sr8150_helper1(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} } struct NotEquatable { } enum ArrayOfNewEquatable : Array<NotEquatable> { } // expected-error@-1{{raw type 'Array<NotEquatable>' is not expressible by a string, integer, or floating-point literal}} // expected-error@-2{{'ArrayOfNewEquatable' declares raw type 'Array<NotEquatable>', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-3{{RawRepresentable conformance cannot be synthesized because raw type 'Array<NotEquatable>' is not Equatable}} // expected-note@-4{{do you want to add protocol stubs?}} // expected-error@-5 {{an enum with no cases cannot declare a raw type}}
apache-2.0
cdf8ff186ef94f857072cf6b86759404
34.5
216
0.675763
3.421687
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Features/Shared/Reachability.swift
2
10679
// // Reachability.swift // Operations // // Created by Daniel Thorpe on 24/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation import SystemConfiguration // swiftlint:disable variable_name public struct Reachability { /// Errors which can be thrown or returned. public enum Error: ErrorType { case FailedToCreateDefaultRouteReachability case FailedToSetNotifierCallback case FailedToSetDispatchQueue } /// The kind of `Reachability` connectivity public enum Connectivity { case AnyConnectionKind, ViaWWAN, ViaWiFi } /// The `NetworkStatus` public enum NetworkStatus { case NotReachable case Reachable(Connectivity) } /// The ObserverBlockType public typealias ObserverBlockType = NetworkStatus -> Void struct Observer { let connectivity: Connectivity let whenConnectedBlock: () -> Void } } protocol NetworkReachabilityDelegate: class { func reachabilityDidChange(flags: SCNetworkReachabilityFlags) } protocol NetworkReachabilityType { weak var delegate: NetworkReachabilityDelegate? { get set } func startNotifierOnQueue(queue: dispatch_queue_t) throws func stopNotifier() func reachabilityFlagsForHostname(host: String) -> SCNetworkReachabilityFlags? } protocol ReachabilityManagerType { init(_ network: NetworkReachabilityType) } protocol SystemReachabilityType: ReachabilityManagerType { func whenConnected(conn: Reachability.Connectivity, block: () -> Void) } protocol HostReachabilityType: ReachabilityManagerType { func reachabilityForURL(url: NSURL, completion: Reachability.ObserverBlockType) } final class ReachabilityManager { typealias Status = Reachability.NetworkStatus static let sharedInstance = ReachabilityManager(DeviceReachability()) let queue = Queue.Utility.serial("me.danthorpe.Operations.Reachability") var network: NetworkReachabilityType var _observers = Protector(Array<Reachability.Observer>()) var observers: [Reachability.Observer] { return _observers.read { $0 } } var numberOfObservers: Int { return observers.count } required init(_ net: NetworkReachabilityType) { network = net network.delegate = self } } extension ReachabilityManager: NetworkReachabilityDelegate { func reachabilityDidChange(flags: SCNetworkReachabilityFlags) { let status = Status(flags: flags) let observersToCheck = _observers.read { $0 } _observers.write { (inout mutableObservers: Array<Reachability.Observer>) in mutableObservers = observersToCheck.filter { observer in let shouldRemove = status.isConnected(observer.connectivity) if shouldRemove { dispatch_async(Queue.Main.queue, observer.whenConnectedBlock) } return !shouldRemove } } if numberOfObservers == 0 { network.stopNotifier() } } } extension ReachabilityManager: SystemReachabilityType { // swiftlint:disable force_try func whenConnected(conn: Reachability.Connectivity, block: () -> Void) { _observers.write({ (inout mutableObservers: [Reachability.Observer]) in mutableObservers.append(Reachability.Observer(connectivity: conn, whenConnectedBlock: block)) }, completion: { try! self.network.startNotifierOnQueue(self.queue) }) } // swiftlint:enable force_try } extension ReachabilityManager: HostReachabilityType { func reachabilityForURL(url: NSURL, completion: Reachability.ObserverBlockType) { dispatch_async(queue) { [reachabilityFlagsForHostname = network.reachabilityFlagsForHostname] in if let host = url.host, flags = reachabilityFlagsForHostname(host) { completion(Status(flags: flags)) } else { completion(.NotReachable) } } } } class DeviceReachability: NetworkReachabilityType { typealias Error = Reachability.Error var __defaultRouteReachability: SCNetworkReachability? = .None var threadSafeProtector = Protector(false) weak var delegate: NetworkReachabilityDelegate? var notifierIsRunning: Bool { get { return threadSafeProtector.read { $0 } } set { threadSafeProtector.write { (inout isRunning: Bool) in isRunning = newValue } } } init() { } func defaultRouteReachability() throws -> SCNetworkReachability { if let reachability = __defaultRouteReachability { return reachability } var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(&zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { throw Error.FailedToCreateDefaultRouteReachability } __defaultRouteReachability = reachability return reachability } func reachabilityForHost(host: String) -> SCNetworkReachability? { return SCNetworkReachabilityCreateWithName(nil, (host as NSString).UTF8String) } func getFlagsForReachability(reachability: SCNetworkReachability) -> SCNetworkReachabilityFlags { var flags = SCNetworkReachabilityFlags() guard withUnsafeMutablePointer(&flags, { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) }) else { return SCNetworkReachabilityFlags() } return flags } func reachabilityDidChange(flags: SCNetworkReachabilityFlags) { delegate?.reachabilityDidChange(flags) } func check(reachability: SCNetworkReachability, queue: dispatch_queue_t) { dispatch_async(queue) { [weak self] in if let delegate = self?.delegate, flags = self?.getFlagsForReachability(reachability) { delegate.reachabilityDidChange(flags) } } } func startNotifierOnQueue(queue: dispatch_queue_t) throws { assert(delegate != nil, "Reachability Delegate not set.") let reachability = try defaultRouteReachability() if !notifierIsRunning { notifierIsRunning = true var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) guard SCNetworkReachabilitySetCallback(reachability, __device_reachability_callback, &context) else { stopNotifier() throw Error.FailedToSetNotifierCallback } guard SCNetworkReachabilitySetDispatchQueue(reachability, queue) else { stopNotifier() throw Error.FailedToSetDispatchQueue } } check(reachability, queue: queue) } func stopNotifier() { if let reachability = try? defaultRouteReachability() { SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetCurrent(), kCFRunLoopCommonModes) SCNetworkReachabilitySetCallback(reachability, nil, nil) } notifierIsRunning = false } func reachabilityFlagsForHostname(host: String) -> SCNetworkReachabilityFlags? { guard let reachability = reachabilityForHost(host) else { return .None } return getFlagsForReachability(reachability) } } private func __device_reachability_callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) { let handler = Unmanaged<DeviceReachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue() dispatch_async(Queue.Default.queue) { handler.delegate?.reachabilityDidChange(flags) } } extension Reachability.NetworkStatus: Equatable { } public func == (lhs: Reachability.NetworkStatus, rhs: Reachability.NetworkStatus) -> Bool { switch (lhs, rhs) { case (.NotReachable, .NotReachable): return true case let (.Reachable(aConnectivity), .Reachable(bConnectivity)): return aConnectivity == bConnectivity default: return false } } extension Reachability.NetworkStatus { public init(flags: SCNetworkReachabilityFlags) { if flags.isReachableViaWiFi { self = .Reachable(.ViaWiFi) } else if flags.isReachableViaWWAN { #if os(iOS) self = .Reachable(.ViaWWAN) #else self = .Reachable(.AnyConnectionKind) #endif } else { self = .NotReachable } } func isConnected(target: Reachability.Connectivity) -> Bool { switch (self, target) { case (.NotReachable, _): return false case (.Reachable(.ViaWWAN), .ViaWiFi): return false case (.Reachable(_), _): return true } } } // MARK: - Conformance extension SCNetworkReachabilityFlags { var isReachable: Bool { return contains(.Reachable) } var isConnectionRequired: Bool { return contains(.ConnectionRequired) } var isInterventionRequired: Bool { return contains(.InterventionRequired) } var isConnectionOnTraffic: Bool { return contains(.ConnectionOnTraffic) } var isConnectionOnDemand: Bool { return contains(.ConnectionOnDemand) } var isTransientConnection: Bool { return contains(.TransientConnection) } var isLocalAddress: Bool { return contains(.IsLocalAddress) } var isDirect: Bool { return contains(.IsDirect) } var isConnectionOnTrafficOrDemand: Bool { return isConnectionOnTraffic || isConnectionOnDemand } var isConnectionRequiredOrTransient: Bool { return isConnectionRequired || isTransientConnection } var isConnected: Bool { return isReachable && !isConnectionRequired } var isOnWWAN: Bool { #if os(iOS) return contains(.IsWWAN) #else return false #endif } var isReachableViaWWAN: Bool { #if os(iOS) return isConnected && isOnWWAN #else return isReachable #endif } var isReachableViaWiFi: Bool { #if os(iOS) return isConnected && !isOnWWAN #else return isConnected #endif } } // swiftlint:enable variable_name
gpl-3.0
e21bd7db78b912509c04a5f2bd5aee9b
28.337912
151
0.664763
5.5389
false
false
false
false
sggtgb/Sea-Cow
seaCow/ReadingList.swift
1
1925
// // ReadingList.swift // seaCow // // Created by Scott Gavin on 5/7/15. // Copyright (c) 2015 Scott G Gavin. All rights reserved. // import UIKit import Foundation class ReadingList: NSObject , NSCoding { var articles: [ArticleData]! = [] override init() { println("Initalizing Reading List") } func addArticle(article: ArticleData) { println("Adding article") articles.append(article) } func removeArticle(index: Int) { println("Removing article") articles.removeAtIndex(index) } func getArticles() -> [ArticleData] { println("Returning list") return articles! } // MARK: NSCoding func encodeWithCoder(coder: NSCoder) { println("trying to encode articles, value: ") println(articles) coder.encodeObject(articles, forKey: "article") } required init(coder aDecoder: NSCoder) { var temp: AnyObject? = aDecoder.decodeObjectForKey("article") println("trying to load reading list in init...") if (temp != nil) { println("reading list loaded") //test = (temp as! ReadingList).test articles = temp as! [ArticleData] } else { println("failed") } } func save() { println("trying to save") let data = NSKeyedArchiver.archivedDataWithRootObject(self) println("data created, trying to write") NSUserDefaults.standardUserDefaults().setObject(data, forKey: "readingList") println("success") } func load() -> Bool { if let data = NSUserDefaults.standardUserDefaults().objectForKey("readingList") as? NSData { let temp = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! ReadingList articles = temp.articles return true } return false } }
mpl-2.0
baad0b48f5641fd2c2fb75122d445ad0
25.736111
100
0.593766
4.861111
false
false
false
false
huonw/swift
validation-test/compiler_crashers_fixed/00875-getselftypeforcontainer.swift
65
874
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol c { class A { if true { func f: NSObject { enum A { } if c = c(v: NSObject { } f = b: e == T) { func compose<T: C { } typealias e = c() -> V { func a(f: A: A { } var d where T>) -> { let d<T : P { } let c: P { } protocol c = e, V>: Array) { } self] { print() -> { } protocol P { } } var b = { protocol P { } } enum S<T) { return g<T>: A() { } deinit { } } } } } } extension NSSet { } } } var e: e!.e == c: String = compose(false) protocol P { } typealias e : e == ni
apache-2.0
8565a3e8527a2985d4fa20d282a92405
14.333333
79
0.617849
2.748428
false
false
false
false
vector-im/riot-ios
Riot/Modules/KeyBackup/Recover/Passphrase/KeyBackupRecoverFromPassphraseViewController.swift
2
9609
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class KeyBackupRecoverFromPassphraseViewController: UIViewController { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var shieldImageView: UIImageView! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var passphraseTitleLabel: UILabel! @IBOutlet private weak var passphraseTextField: UITextField! @IBOutlet private weak var passphraseTextFieldBackgroundView: UIView! @IBOutlet private weak var passphraseVisibilityButton: UIButton! @IBOutlet private weak var unknownPassphraseButton: UIButton! @IBOutlet private weak var recoverButtonBackgroundView: UIView! @IBOutlet private weak var recoverButton: UIButton! // MARK: Private private var viewModel: KeyBackupRecoverFromPassphraseViewModelType! private var keyboardAvoider: KeyboardAvoider? private var theme: Theme! private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! // MARK: Public // MARK: - Setup class func instantiate(with viewModel: KeyBackupRecoverFromPassphraseViewModelType) -> KeyBackupRecoverFromPassphraseViewController { let viewController = StoryboardScene.KeyBackupRecoverFromPassphraseViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = VectorL10n.keyBackupRecoverTitle self.vc_removeBackTitle() self.setupViews() self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView) self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func setupViews() { let cancelBarButtonItem = MXKBarButtonItem(title: VectorL10n.cancel, style: .plain) { [weak self] in self?.viewModel.process(viewAction: .cancel) } self.navigationItem.rightBarButtonItem = cancelBarButtonItem self.scrollView.keyboardDismissMode = .interactive let shieldImage = Asset.Images.keyBackupLogo.image.withRenderingMode(.alwaysTemplate) self.shieldImageView.image = shieldImage let visibilityImage = Asset.Images.revealPasswordButton.image.withRenderingMode(.alwaysTemplate) self.passphraseVisibilityButton.setImage(visibilityImage, for: .normal) self.informationLabel.text = VectorL10n.keyBackupRecoverFromPassphraseInfo self.passphraseTitleLabel.text = VectorL10n.keyBackupRecoverFromPassphrasePassphraseTitle self.passphraseTextField.addTarget(self, action: #selector(passphraseTextFieldDidChange(_:)), for: .editingChanged) self.unknownPassphraseButton.vc_enableMultiLinesTitle() self.recoverButton.vc_enableMultiLinesTitle() self.recoverButton.setTitle(VectorL10n.keyBackupRecoverFromPassphraseRecoverAction, for: .normal) self.updateRecoverButton() } private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.informationLabel.textColor = theme.textPrimaryColor self.shieldImageView.tintColor = theme.textPrimaryColor self.passphraseTextFieldBackgroundView.backgroundColor = theme.backgroundColor self.passphraseTitleLabel.textColor = theme.textPrimaryColor theme.applyStyle(onTextField: self.passphraseTextField) self.passphraseTextField.attributedPlaceholder = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphrasePassphrasePlaceholder, attributes: [.foregroundColor: theme.placeholderTextColor]) self.theme.applyStyle(onButton: self.passphraseVisibilityButton) self.recoverButtonBackgroundView.backgroundColor = theme.backgroundColor theme.applyStyle(onButton: self.recoverButton) let unknownRecoveryKeyAttributedString = NSMutableAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart1, attributes: [.foregroundColor: self.theme.textPrimaryColor]) let unknownRecoveryKeyAttributedStringPart2 = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart2, attributes: [.foregroundColor: self.theme.tintColor]) let unknownRecoveryKeyAttributedStringPart3 = NSAttributedString(string: VectorL10n.keyBackupRecoverFromPassphraseLostPassphraseActionPart3, attributes: [.foregroundColor: self.theme.textPrimaryColor]) unknownRecoveryKeyAttributedString.append(unknownRecoveryKeyAttributedStringPart2) unknownRecoveryKeyAttributedString.append(unknownRecoveryKeyAttributedStringPart3) self.unknownPassphraseButton.setAttributedTitle(unknownRecoveryKeyAttributedString, for: .normal) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func updateRecoverButton() { self.recoverButton.isEnabled = self.viewModel.isFormValid } private func render(viewState: KeyBackupRecoverFromPassphraseViewState) { switch viewState { case .loading: self.renderLoading() case .loaded: self.renderLoaded() case .error(let error): self.render(error: error) } } private func renderLoading() { self.view.endEditing(true) self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded() { self.activityPresenter.removeCurrentActivityIndicator(animated: true) } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) if (error as NSError).domain == MXKeyBackupErrorDomain && (error as NSError).code == Int(MXKeyBackupErrorInvalidRecoveryKeyCode.rawValue) { self.errorPresenter.presentError(from: self, title: VectorL10n.keyBackupRecoverInvalidPassphraseTitle, message: VectorL10n.keyBackupRecoverInvalidPassphrase, animated: true, handler: nil) } else { self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } } // MARK: - Actions @IBAction private func passphraseVisibilityButtonAction(_ sender: Any) { self.passphraseTextField.isSecureTextEntry = !self.passphraseTextField.isSecureTextEntry } @objc private func passphraseTextFieldDidChange(_ textField: UITextField) { self.viewModel.passphrase = textField.text self.updateRecoverButton() } @IBAction private func recoverButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .recover) } @IBAction private func unknownPassphraseButtonAction(_ sender: Any) { self.viewModel.process(viewAction: .unknownPassphrase) } } // MARK: - UITextFieldDelegate extension KeyBackupRecoverFromPassphraseViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } } // MARK: - KeyBackupRecoverFromPassphraseViewModelViewDelegate extension KeyBackupRecoverFromPassphraseViewController: KeyBackupRecoverFromPassphraseViewModelViewDelegate { func keyBackupRecoverFromPassphraseViewModel(_ viewModel: KeyBackupRecoverFromPassphraseViewModelType, didUpdateViewState viewSate: KeyBackupRecoverFromPassphraseViewState) { self.render(viewState: viewSate) } }
apache-2.0
b66c93cfdacf0e0f1b3fbda6a2139bcf
40.418103
211
0.706837
6.215395
false
false
false
false
eofster/Telephone
ReceiptValidation/DeviceGUID.swift
1
1901
// // DeviceGUID.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 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 Foundation import IOKit struct DeviceGUID { let dataValue: Data init() { dataValue = makeGUID() } } private func makeGUID() -> Data { let iterator = makeIterator() guard iterator != 0 else { return Data() } var mac = Data() var service = IOIteratorNext(iterator) while service != 0 { var parent: io_object_t = 0 let status = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent) if status == KERN_SUCCESS { mac = (IORegistryEntryCreateCFProperty(parent, "IOMACAddress" as CFString, kCFAllocatorDefault, 0).takeRetainedValue() as! CFData) as Data IOObjectRelease(parent) } IOObjectRelease(service) service = IOIteratorNext(iterator) } IOObjectRelease(iterator) return mac } private func makeIterator() -> io_iterator_t { var port: mach_port_t = 0 var status = IOMasterPort(mach_port_t(MACH_PORT_NULL), &port) guard status == KERN_SUCCESS else { return 0 } guard let match = IOBSDNameMatching(port, 0, "en0") else { return 0 } var iterator: io_iterator_t = 0 status = IOServiceGetMatchingServices(port, match, &iterator) guard status == KERN_SUCCESS else { return 0 } return iterator }
gpl-3.0
01d5a0bb39909d1ad09fa26b871e3549
30.131148
150
0.681411
4.006329
false
false
false
false
simonnarang/Fandom
Desktop/Fandom-IOS-master/Fandomm/ShareToFandomTableViewController.swift
1
8471
// // ShareToFandomTableViewController.swift // Fandomm // // Created by Simon Narang on 1/9/16. // Copyright © 2016 Simon Narang. All rights reserved. // import UIKit class ShareToFandomTableViewController: UITableViewController { @IBOutlet weak var labell: UILabel! var counter = Int() let redisClient:RedisClient = RedisClient(host:"localhost", port:6379, loggingBlock:{(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in var debugString:String = message debugString = debugString.stringByReplacingOccurrencesOfString("\r", withString: "\\r") debugString = debugString.stringByReplacingOccurrencesOfString("\n", withString: "\\n") print("Log (\(severity.rawValue)): \(debugString)") }) var usernameThreeTextOne = String() var shareImage: UIImage? = nil var shareLinky: String? = nil var fandomsArray: [String] = [] override func viewDidLoad() { super.viewDidLoad() let linkShareActionSheetMenu = UIAlertController(title: nil, message: "which fandoms do you want to share this with?", preferredStyle: .ActionSheet) let backAction = UIAlertAction(title: "back", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in print("Cancelled Link Share") }) linkShareActionSheetMenu.addAction(backAction) presentViewController(linkShareActionSheetMenu, animated: true) { () -> Void in self.redisClient.lRange("\(self.usernameThreeTextOne)fandoms", start: 0, stop: 999999, completionHandler: { (array, error) -> Void in if error != nil { } else{ for fandom in array { print(fandom) self.counter += 1 let bla = UIAlertAction(title: fandom as? String, style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("bla") if self.shareLinky != nil && self.shareImage == nil { self.redisClient.lPush(fandom as! String, values: [self.shareLinky! as String], completionHandler: { (int, error) -> Void in if error != nil { }else{ self.performSegueWithIdentifier("doneSharing", sender: nil) } }) }else if self.shareLinky == nil && self.shareImage != nil { } }) linkShareActionSheetMenu.addAction(bla) } } }) self.counter = 0 } counter = 0 let networkErrorAlertOne = UIAlertController(title: "Network troubles...", message: "Sorry about that... Perhaps check the app store to see if you need to update fandom... If not I'm already working on a fix so try again soon", preferredStyle: .Alert) let networkErrorAlertOneOkButton = UIAlertAction(title: "☹️okay☹️", style: .Default) { (action) in } networkErrorAlertOne.addAction(networkErrorAlertOneOkButton) let noFandomsErrorAlertOne = UIAlertController(title: "Youre not in any Fandoms!", message: "id recomend searching gor what your interested in and joining it!", preferredStyle: .Alert) let noFandomsErrorAlertOneOkButton = UIAlertAction(title: "okay", style: .Default) { (action) in } let noFandomsErrorAlertOneOkButton2 = UIAlertAction(title: "search", style: .Default) { (action) in self.performSegueWithIdentifier("segueSeven", sender: nil) } noFandomsErrorAlertOne.addAction(noFandomsErrorAlertOneOkButton) noFandomsErrorAlertOne.addAction(noFandomsErrorAlertOneOkButton2) /* redisClient.lRange("\(self.usernameThreeTextOne)fandoms", start: 0, stop: 99999999) { (array, error) -> Void in if error != nil { print(error) self.presentViewController(networkErrorAlertOne, animated: true) {} }else if array == nil { print("you have no friends because you have no fandoms") self.presentViewController(noFandomsErrorAlertOne, animated: true) {} }else if error == nil{ print("jubs") print("\(self.usernameThreeTextOne)'s fandoms is/are \(array)") for fandom in array { print(fandom) self.counter += 1 self.fandomsArray.append(fandom as! String) print("counter = \(self.counter)") print("hi") } print("array of fandoms is \(self.fandomsArray)") }else{ } }*/ // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return counter } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { /*let cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell") //let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) let(fandomconstant) = fandomsArray[indexPath.row] cell!.textLabel?.text = fandomconstant print(fandomconstant) if cell == nil { print("wow") print("bad") }else{ print("life") } return cell!*/ let cell = UITableViewCell() let label = UILabel(frame: CGRect(x:0, y:0, width:200, height:50)) label.text = "Hello Man" cell.addSubview(label) return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
unlicense
16ffd1e0f5d047ddd0fa1e3034f5fe06
43.303665
259
0.60813
5.417414
false
false
false
false
rayho/CodePathTwitter
CodePathTwitter/DetailController.swift
1
7136
// // DetailController.swift // CodePathTwitter // // Created by Ray Ho on 9/29/14. // Copyright (c) 2014 Prime Rib Software. All rights reserved. // import UIKit class DetailController: UIViewController, TweetActionButtonsDelegate { var tweet: Tweet! var avatarView: UIImageView! var tweetTextView: UILabel! var realNameView: UILabel! var screenNameView: UILabel! var timeView: UILabel! var numRetweetView: UILabel! var numRetweetLabel: UILabel! var numFavoriteView: UILabel! var numFavoriteLabel: UILabel! var tweetActions: TweetActionButtons! // Convenience method to launch this view controller class func launch(fromNavController: UINavigationController, tweet: Tweet) { var toViewController: DetailController = DetailController() toViewController.tweet = tweet var toNavController: UINavigationController = UINavigationController(rootViewController: toViewController) fromNavController.pushViewController(toViewController, animated: true) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Tweet" // Initialize views self.view.backgroundColor = UIColor.whiteColor() avatarView = UIImageView() avatarView.setTranslatesAutoresizingMaskIntoConstraints(false) realNameView = UILabel() realNameView.setTranslatesAutoresizingMaskIntoConstraints(false) realNameView.numberOfLines = 1 screenNameView = UILabel() screenNameView.setTranslatesAutoresizingMaskIntoConstraints(false) screenNameView.numberOfLines = 1 timeView = UILabel() timeView.setTranslatesAutoresizingMaskIntoConstraints(false) timeView.numberOfLines = 1 tweetTextView = UILabel() tweetTextView.setTranslatesAutoresizingMaskIntoConstraints(false) tweetTextView.numberOfLines = 0 numRetweetView = UILabel() numRetweetView.setTranslatesAutoresizingMaskIntoConstraints(false) numRetweetView.numberOfLines = 1 numRetweetLabel = UILabel() numRetweetLabel.setTranslatesAutoresizingMaskIntoConstraints(false) numRetweetLabel.numberOfLines = 1 numFavoriteView = UILabel() numFavoriteView.setTranslatesAutoresizingMaskIntoConstraints(false) numFavoriteView.numberOfLines = 1 numFavoriteLabel = UILabel() numFavoriteLabel.setTranslatesAutoresizingMaskIntoConstraints(false) numFavoriteLabel.numberOfLines = 1 tweetActions = NSBundle.mainBundle().loadNibNamed("TweetActionButtons", owner: self, options: nil)[0] as TweetActionButtons tweetActions.setTranslatesAutoresizingMaskIntoConstraints(false) tweetActions.delegate = self let viewDictionary: Dictionary = ["tweetTextView": tweetTextView, "avatarView": avatarView, "realNameView": realNameView, "screenNameView": screenNameView, "timeView": timeView, "numRetweetView": numRetweetView, "numRetweetLabel": numRetweetLabel, "numFavoriteView": numFavoriteView, "numFavoriteLabel": numFavoriteLabel, "tweetActions": tweetActions] self.view.addSubview(avatarView) self.view.addSubview(realNameView) self.view.addSubview(screenNameView) self.view.addSubview(timeView) self.view.addSubview(tweetTextView) self.view.addSubview(numRetweetView) self.view.addSubview(numRetweetLabel) self.view.addSubview(numFavoriteView) self.view.addSubview(numFavoriteLabel) self.view.addSubview(tweetActions) self.view.layoutIfNeeded() self.view.addConstraint(NSLayoutConstraint(item: avatarView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 8)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[avatarView(48)]-[realNameView]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllTop, metrics: nil, views: viewDictionary)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[tweetTextView]-8-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: viewDictionary)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[numRetweetView]-4-[numRetweetLabel]-[numFavoriteView]-4-[numFavoriteLabel]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: nil, views: viewDictionary)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[avatarView(48)]-[tweetTextView]-[timeView]-[numRetweetView]-[tweetActions]", options: NSLayoutFormatOptions.AlignAllLeft, metrics: nil, views: viewDictionary)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[realNameView]-0-[screenNameView]-(>=8)-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: nil, views: viewDictionary)) } func clicked(sender: AnyObject) { NSLog("clicked") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) updateUI() } func updateUI() { avatarView.image = nil let avatarUrl: NSString? = tweet.user.avatarUrl if (avatarUrl != nil) { avatarView.setImageWithURL(NSURL.URLWithString(avatarUrl!)) } // Names, tweet text let realName: NSString? = tweet.user.realName realNameView.text = realName != nil ? realName! : "" screenNameView.text = "@\(tweet.user.screenName)" tweetTextView.text = tweet.text // Time var dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "M/d/yy, h:mm a" timeView.text = dateFormatter.stringFromDate(tweet.timestamp) // Retweets and favorites numRetweetView.text = "\(tweet.numRetweets)" numRetweetLabel.text = (tweet.numRetweets == 0 || tweet.numRetweets > 1) ? "RETWEETS" : "RETWEET" numFavoriteView.text = "\(tweet.numFavorites)" numFavoriteLabel.text = (tweet.numFavorites == 0 || tweet.numFavorites > 1) ? "FAVORITES" : "FAVORITE" // Action buttons tweetActions.updateUI(tweet) } func tweetActionReply(sender: TweetActionButtons) { NSLog("Launching reply controller ...") ComposeController.launch(self, inReplyToTweet: tweet) } func tweetActionRetweet(sender: TweetActionButtons) { if (tweet.didRetweet) { NSLog("Already retweeted. Ignoring request.") } else { NSLog("Retweeting ...") tweet.didRetweet = true TWTR.postRetweet(tweet.id) } tweetActions.updateUI(tweet) } func tweetActionFavorite(sender: TweetActionButtons) { if (tweet.didFavorite) { NSLog("Favoriting ...") tweet.didFavorite = false TWTR.removeFavorite(tweet.id) } else { NSLog("Un-favoriting ...") tweet.didFavorite = true TWTR.postFavorite(tweet.id) } tweetActions.updateUI(tweet) } }
mit
db0e6d0041a357b2ce110a5185496515
45.640523
359
0.705437
5.485012
false
false
false
false
mattiasjahnke/arduino-projects
matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/Delegate.swift
1
1951
// // Delegate.swift // Flow // // Created by Måns Bernhardt on 2017-01-16. // Copyright © 2017 iZettle. All rights reserved. // import Foundation /// Helper to manage the life time of a delegate `(Arg) -> Ret`. public final class Delegate<Arg, Ret> { private var callbackAndDisposable: (callback: (Arg) -> Ret, disposable: Disposable)? = nil private let onSet: (@escaping (Arg) -> Ret) -> Disposable /// Creates a new instance. /// - Parameter onSet: When `set()` is called with a new callback, `onSet` will be called with the same callback /// and the `Disposable` returned from `onSet` will be hold on to and not disposed until the callback is unset. public init(onSet: @escaping (@escaping (Arg) -> Ret) -> Disposable = { _ in NilDisposer() }) { self.onSet = onSet } /// Sets the callback to be called when calling `call()` on `self`. /// - Returns: A disposable that will unset the callback once being disposed. /// - Note: If a callback was already set, it will be unset before the new callback is set. public func set(_ callback: @escaping (Arg) -> Ret) -> Disposable { callbackAndDisposable?.disposable.dispose() let bag = DisposeBag() bag += onSet(callback) bag += { self.callbackAndDisposable = nil } callbackAndDisposable = (callback, bag) return bag } /// Is a callback currently set? public var isSet: Bool { return callbackAndDisposable != nil } /// Call any currently set callback with `arg` and return the result, or return nil if no callback is set. public func call(_ arg: Arg) -> Ret? { return callbackAndDisposable?.callback(arg) } } extension Delegate where Arg == () { /// Call any currently set callback and return the result, or return nil if no callback is set. public func call() -> Ret? { return call(()) } }
mit
11c4637167b55179f2a593beb5b41169
34.436364
117
0.633145
4.340757
false
false
false
false
cactis/SwiftEasyKit
Source/Classes/Scrollable2ViewController.swift
1
2443
// // Scrollable2ViewController.swift import UIKit open class Scrollable2ViewController: DefaultViewController { public var contentView = UIScrollView() override open func viewDidLoad() { super.viewDidLoad() } override open func layoutUI() { super.layoutUI() contentView = view.addScrollView() view.layout([contentView]) } override open func bindUI() { super.bindUI() // registerKeyboardNotifications() } override open func updateViewConstraints() { super.updateViewConstraints() contentView.fillSuperview() } // // override func viewWillDisappear(animated: Bool) { // super.viewWillDisappear(animated) // unregisterKeyboardNotifications() // } // override open func keyboardDidShow(_ notification: NSNotification) { super.keyboardDidShow(notification) // let userInfo: NSDictionary = notification.userInfo! // let // keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) contentView.contentInset = contentInsets contentView.scrollIndicatorInsets = contentInsets } override open func keyboardWillHide(_ notification: NSNotification) { super.keyboardWillHide(notification) contentView.contentInset = .zero contentView.scrollIndicatorInsets = .zero } func textViewDidBeginEditing(textView: UITextView) { makeTargetVisible(textView.superview!) } private func makeTargetVisible(_ target: UIView) { // var viewRect = view.frame // viewRect.size.height -= keyboardSize.height // let y = target.frame.origin.y var y: CGFloat = 0 if target.bottomEdge() > 200 { y = target.bottomEdge() - 100 } let scrollPoint = CGPoint(x: 0, y: y) contentView.setContentOffset(scrollPoint, animated: true) } func textFieldDidBeginEditing(textField: UITextField) { makeTargetVisible(textField.superview!) } // // // func registerKeyboardNotifications() { // NSNotificationCenter.default().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) // NSNotificationCenter.default().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) // } // // func unregisterKeyboardNotifications() { // NSNotificationCenter.default().removeObserver(self) // } }
mit
44064170ed73972a32760f52f0b43c96
29.924051
138
0.714695
4.945344
false
false
false
false
chatappcodepath/ChatAppSwift
LZChat/SignInViewController.swift
1
3116
// // // License // Copyright (c) 2017 chatappcodepath // Released under an MIT license: http://opensource.org/licenses/MIT // import UIKit import Firebase @objc(SignInViewController) class SignInViewController: UIViewController, GIDSignInUIDelegate { @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var googleSigninButton: GIDSignInButton! override func viewDidAppear(_ animated: Bool) { if let user = FIRAuth.auth()?.currentUser { self.signedIn(user) } } override func viewDidLoad() { GIDSignIn.sharedInstance().uiDelegate = self } @IBAction func didTapSignIn(_ sender: AnyObject) { // Sign In with credentials. guard let email = emailField.text, let password = passwordField.text else { return } FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in if let error = error { print(error.localizedDescription) return } self.signedIn(user!) } } @IBAction func didTapSignUp(_ sender: AnyObject) { guard let email = emailField.text, let password = passwordField.text else { return } FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in if let error = error { print(error.localizedDescription) return } self.setDisplayName(user!) } } func setDisplayName(_ user: FIRUser?) { guard let user = user else { return; } let changeRequest = user.profileChangeRequest() changeRequest.displayName = user.email!.components(separatedBy: "@")[0] changeRequest.commitChanges(){ (error) in if let error = error { print(error.localizedDescription) return } self.signedIn(FIRAuth.auth()?.currentUser) } } @IBAction func didRequestPasswordReset(_ sender: AnyObject) { let prompt = UIAlertController.init(title: nil, message: "Email:", preferredStyle: .alert) let okAction = UIAlertAction.init(title: "OK", style: .default) { (action) in let userInput = prompt.textFields![0].text if (userInput!.isEmpty) { return } FIRAuth.auth()?.sendPasswordReset(withEmail: userInput!) { (error) in if let error = error { print(error.localizedDescription) return } } } prompt.addTextField(configurationHandler: nil) prompt.addAction(okAction) present(prompt, animated: true, completion: nil); } public func signedIn(_ user: FIRUser?) { MeasurementHelper.sendLoginEvent() AppState.sharedInstance.displayName = user?.displayName ?? user?.email AppState.sharedInstance.photoURL = user?.photoURL AppState.sharedInstance.signedIn = true let notificationName = Notification.Name(rawValue: Constants.NotificationKeys.SignedIn) NotificationCenter.default.post(name: notificationName, object: nil, userInfo: nil) performSegue(withIdentifier: Constants.Segues.SignInToFp, sender: nil) } }
mit
722e8ee38a32ee1a1a370c2a3be72087
30.474747
94
0.660141
4.678679
false
false
false
false
Keenan144/SpaceKase
SpaceKase/GameScene.swift
1
9887
// // GameScene.swift // SpaceKase // // Created by Keenan Sturtevant on 5/29/16. // Copyright (c) 2016 Keenan Sturtevant. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { let shipCategory: UInt32 = 0x1 << 1 let rockCategory: UInt32 = 0x1 << 2 let boundaryCategory: UInt32 = 0x1 << 3 let healthCategory: UInt32 = 0x2 << 4 var score = NSInteger() var label = SKLabelNode(fontNamed: "Arial") var ship = SKSpriteNode() var rock = SKSpriteNode() var health = SKSpriteNode() var boosterRateTimer = NSTimer() var rockRateTimer = NSTimer() var healthRateTimer = NSTimer() var scoreLabel = SKLabelNode(fontNamed: "Arial") var exitLabel = SKLabelNode(fontNamed: "Arial") var invincibleLabel = SKLabelNode() var invincibilityTimer = Int32() var invincibilityNSTimer = NSTimer() var boundary = SKSpriteNode() var boundaryColor = UIColor.yellowColor() var backgroundColorCustom = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0) var touchLocation = CGPoint() override func didMoveToView(view: SKView) { view.showsPhysics = false physicsWorld.contactDelegate = self self.backgroundColor = backgroundColorCustom setBoundaries() spawnShip() start() } func setBoundaries() { setBottomBoundary() setLeftSideBoundry() setRightSideBoundry() } func start() { score = 0 Helper.toggleRun(true) showExitButton() showScore() rockTimer() healthTimer() boosterTimer() } func spawnShip(){ ship = SpaceShip.spawn(shipCategory, rockCategory: rockCategory, frame: self.frame) SpaceShip.setShipHealth(Helper.setShipHealth()) showHealth() self.addChild(ship) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches{ touchLocation = touch.locationInNode(self) let pos = touch.locationInNode(self) let node = self.nodeAtPoint(pos) if node == exitLabel { stopRocks() endGame() } else { touchLocation = touch.locationInNode(self) ship.position.x = touchLocation.x print(ship.position.x) } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { for touch in touches{ touchLocation = touch.locationInNode(self) ship.position.x = touchLocation.x } } func didBeginContact(contact: SKPhysicsContact) { if (contact.bodyA.categoryBitMask == boundaryCategory) { contact.bodyB.node?.removeFromParent() print("GAMESCENE: scoreIncresed") increaseScore() refreshScoreView() } if (contact.bodyA.categoryBitMask == shipCategory) { contact.bodyB.node?.physicsBody?.collisionBitMask = 0 if (contact.bodyB.node?.name == "Health") { contact.bodyB.node?.removeFromParent() increaseHealth() } else if (contact.bodyB.node?.name == "ScoreBump") { contact.bodyB.node?.removeFromParent() bumpScore() } else if (contact.bodyB.node?.name == "Invincibility") { contact.bodyB.node?.removeFromParent() makeInvincible() showInvincibleLabel() } else if (contact.bodyB.node?.name == "Rock") { if Helper.isInvincible() == false { SpaceShip.deductHealth(Helper.deductHealth()) if SpaceShip.dead() { stopRocks() endGame() } } } refreshHealthView() } } func increaseHealth() { if Helper.canRun() { SpaceShip.health = SpaceShip.health + 5 } } func bumpScore() { if Helper.canRun() { score = score + 50 } } func increaseScore() { if Helper.canRun() { score = score + 5 } } func spawnRock() { if Helper.canRun() { rock = Rock.spawn() rock.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY) self.addChild(rock) } } func spawnHealth() { if Helper.canRun() { health = Health.spawn() health.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: frame.maxY) self.addChild(health) } } func randomSpawn() { if Helper.canRun() { if Helper.randomSpawn() == 1 { let boost = Boost.spawnInvincibility() boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY) self.addChild(boost) } else { let boost = Boost.spawnScoreBump() boost.position = Helper.randomSpawnPoint(frame.minX, valueHighX: frame.maxX, valueY: self.frame.maxY) self.addChild(boost) } } } func boosterTimer() { boosterRateTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("randomSpawn"), userInfo: nil, repeats: true) } func rockTimer() { rockRateTimer = NSTimer.scheduledTimerWithTimeInterval(Helper.rockSpawnRate(), target: self, selector: ("spawnRock"), userInfo: nil, repeats: true) } func healthTimer() { healthRateTimer = NSTimer.scheduledTimerWithTimeInterval(5.3, target: self, selector: ("spawnHealth"), userInfo: nil, repeats: true) } func stopRocks() { Helper.toggleRun(false) } private func showHighScores() { Helper.setLastScore(score) } private func setBottomBoundary() { let boundary = Boundary.setBottomBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func setRightSideBoundry() { let boundary = Boundary.setRightSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func setLeftSideBoundry() { let boundary = Boundary.setLeftSideBoundary(boundaryCategory, rockCategory: rockCategory, frame: self.frame) self.addChild(boundary) } private func showHealth() { let health = Health.showHealth(label) health.fontSize = 20 health.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 40) self.addChild(health) } func showInvincibleLabel() { if 15 - invincibilityTimer > 0 { invincibleLabel.removeFromParent() let invLabel = invincibleLabel invLabel.text = "Invincible: \(15 - invincibilityTimer)" invLabel.fontColor = UIColor.yellowColor() invLabel.fontSize = 20 invLabel.position = CGPoint(x: self.frame.minX + 55 , y: self.frame.maxY - 65) self.addChild(invLabel) } else { invincibleLabel.removeFromParent() } } private func showScore() { scoreLabel.text = "Score: \(score)" scoreLabel.fontSize = 20 scoreLabel.position = CGPoint(x: self.frame.maxX - 75 , y: self.frame.maxY - 40) self.addChild(scoreLabel) } func showExitButton() { if Helper.canRun() { exitLabel.text = "exit" exitLabel.fontSize = 20 exitLabel.position = CGPoint(x: self.frame.maxX - 55, y: self.frame.maxY - 80) self.addChild(exitLabel) } } private func refreshHealthView() { label.removeFromParent() showHealth() print("GAMESCENE: refreshHealthView") } private func refreshScoreView() { scoreLabel.removeFromParent() showScore() print("GAMESCENE: refreshScoreView") } private func endGame() { showHighScores() ship.removeAllActions() rock.removeAllActions() invincibleLabel.removeAllActions() let skView = self.view as SKView!; let gameScene = EndScene(size: (skView?.bounds.size)!) let transition = SKTransition.fadeWithDuration (2.0) boosterRateTimer.invalidate() rockRateTimer.invalidate() healthRateTimer.invalidate() view!.presentScene(gameScene, transition: transition) } private func makeInvincible() { if Helper.invincible == false { Helper.toggleInvincibility(true) invincibilityTimer = 1 startInvincibilityTimer() print("GAMESCENE: makeInvincible") } } @objc private func incrementInvincibilityTimer() { invincibilityTimer = invincibilityTimer + 1 showInvincibleLabel() if invincibilityTimer >= 15 { invincibilityNSTimer.invalidate() Helper.toggleInvincibility(false) print("GAMESCENE: incrementInvincibilityTimer") } } private func returnInvincibilityTime() -> Int32 { return invincibilityTimer } private func startInvincibilityTimer() { invincibilityNSTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: (#selector(GameScene.incrementInvincibilityTimer)), userInfo: nil, repeats: true) print("GAMESCENE: startInvincibilityTimer") } }
mit
1ee1da34752c2f13dc23fc9a751cdb62
30.790997
179
0.585213
4.926258
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Tests/ScheduleComponentTests/Presenter Tests/Share Command/SchedulePresenterShareCommandTests.swift
1
1207
import EurofurenceModel import ScheduleComponent import XCTest import XCTScheduleComponent class SchedulePresenterShareCommandTests: XCTestCase { func testShareCommand() throws { let eventViewModel = StubScheduleEventViewModel.random let eventGroupViewModel = ScheduleEventGroupViewModel(title: .random, events: [eventViewModel]) let viewModel = CapturingScheduleViewModel(days: .random, events: [eventGroupViewModel], currentDay: 0) let viewModelFactory = FakeScheduleViewModelFactory(viewModel: viewModel) let context = SchedulePresenterTestBuilder().with(viewModelFactory).build() context.simulateSceneDidLoad() let searchResult = StubScheduleEventViewModel.random searchResult.isFavourite = false let indexPath = IndexPath(item: 0, section: 0) let commands = context.scene.binder?.eventActionsForComponent(at: indexPath) let action = try XCTUnwrap(commands?.command(titled: .share)) XCTAssertEqual("square.and.arrow.up", action.sfSymbol) let sender = "Cell" action.run(sender) XCTAssertEqual(sender, eventViewModel.sharedSender as? String) } }
mit
c0edd12233b622635a9b7bc5da39605a
39.233333
111
0.722452
5.587963
false
true
false
false
Yalantis/EatFit
EatFit/Vendors/YALPageController/YALPageController.swift
1
5547
// // YALPageController.swift // EatFit // // Created by Dmitriy Demchenko on 7/12/16. // Copyright © 2016 aleksey chernish. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } typealias YALPageControllerTransitionHook = ((_ pageViewController: UIPageViewController, _ viewController: UIViewController, _ pageIndex: Int) -> Void) class YALPageController: NSObject { // declare a static var to produce a unique address as the assoc object handle static var YALPageControllerAssociatedObjectHandle: UInt8 = 123 var viewControllers = [UIViewController]() var didFinishTransition: YALPageControllerTransitionHook? var pagingEnabled = true weak var pageViewController: UIPageViewController! fileprivate weak var scrollView: UIScrollView! func showPage(_ index: Int, animated: Bool) { showViewController(viewControllers[Int(index)], animated: animated) if let pageViewController = pageViewController, let firstControllers = viewControllers.first { didFinishTransition?( pageViewController, firstControllers, index ) } } func showViewController(_ viewController: UIViewController, animated: Bool) { guard let pageViewController = pageViewController else { return } guard let lastViewController = pageViewController.viewControllers?.last else { return } let currentIndex = viewControllers.firstIndex(of: lastViewController) let index = viewControllers.firstIndex(of: viewController) if currentIndex == index { return } let direction: UIPageViewController.NavigationDirection = index > currentIndex ? .forward : .reverse pageViewController.setViewControllers( [viewController], direction: direction, animated: animated, completion: { _ in if let _ = self.scrollView { self.scrollView.isScrollEnabled = self.pagingEnabled } } ) } func setupViewControllers(_ viewControllers: [UIViewController]) { self.viewControllers = viewControllers guard let pageViewController = pageViewController else { return } guard let firstViewController = viewControllers.first else { return } pageViewController.setViewControllers( [firstViewController], direction: .forward, animated: false, completion: nil ) guard let pageIndex = viewControllers.firstIndex(of: firstViewController) else { return } didFinishTransition?( pageViewController, firstViewController, pageIndex ) } func setupPageViewController(_ pageViewController: UIPageViewController) { self.pageViewController = pageViewController self.pageViewController.view.subviews.forEach { view in if let view = view as? UIScrollView { scrollView = view } } } // MARK: - Paging Enabled fileprivate func setupPagingEnabled(_ pagingEnabled: Bool) { self.pagingEnabled = pagingEnabled if let _ = scrollView { scrollView.isScrollEnabled = pagingEnabled } } } extension YALPageController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.firstIndex(of: viewController) else { return nil } if index >= viewControllers.count - 1 { return nil } return viewControllers[index + 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = viewControllers.firstIndex(of: viewController) else { return nil } if index <= 0 { return nil } return viewControllers[index - 1] } } extension YALPageController: UIPageViewControllerDelegate { func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let _ = scrollView { scrollView.isPagingEnabled = pagingEnabled } if let lastViewController = pageViewController.viewControllers?.last , lastViewController != previousViewControllers.last { if let lastIndex = viewControllers.firstIndex(of: lastViewController) { didFinishTransition?( pageViewController, lastViewController, lastIndex ) } } } }
mit
4c7206dac071d93b369f928a97b5f128
29.472527
190
0.61053
6.231461
false
false
false
false
ted005/Qiu_Suo
Qiu Suo/Qiu Suo/TWNodeSearchTableViewController.swift
2
5132
// // TWNodeSearchTableViewController.swift // V2EX Explorer // // Created by Robbie on 15/8/23. // Copyright (c) 2015年 Ted Wei. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class TWNodeSearchTableViewController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate{ var searchController: UISearchController? var nodes: [TWNode] = [] var filteredNodes: [TWNode] = [] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations self.clearsSelectionOnViewWillAppear = true tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "seachCell") tableView.separatorStyle = UITableViewCellSeparatorStyle.None //search searchController = UISearchController(searchResultsController: nil) self.searchController!.searchResultsUpdater = self self.navigationItem.titleView = searchController?.searchBar self.searchController?.dimsBackgroundDuringPresentation = false self.searchController?.searchBar.barStyle = UIBarStyle.Default self.searchController?.hidesNavigationBarDuringPresentation = false self.searchController?.searchBar.delegate = self //load all nodes Alamofire.request(.GET, "https://www.v2ex.com/api/nodes/all.json") .responseJSON { (req, res, result)in if(result.isFailure) { NSLog("Fail to load data.") } else { let json = JSON(result.value!) for subJson in json { let node: TWNode = TWNode() node.title = subJson.1["title"].stringValue node.name = subJson.1["name"].stringValue node.header = subJson.1["header"].stringValue node.topics = subJson.1["topics"].intValue node.url = subJson.1["url"].stringValue self.nodes.append(node) } self.filteredNodes = self.nodes //dont show all nodes // self.tableView.reloadData() } } } func updateSearchResultsForSearchController(searchController: UISearchController) { filteredNodes.removeAll(keepCapacity: true) let searchText = searchController.searchBar.text for node in nodes { if (node.title?.lowercaseString.rangeOfString(searchText!.lowercaseString) != nil) { filteredNodes.append(node) } } tableView.reloadData() tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredNodes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) cell.textLabel?.text = filteredNodes[indexPath.row].title cell.detailTextLabel?.text = filteredNodes[indexPath.row].header return cell } func searchBarSearchButtonClicked(searchBar: UISearchBar) { //placeholder } func searchBarCancelButtonClicked(searchBar: UISearchBar) { //placeholder } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //wrong, will trigger receiver has no segue with identifier '***' error // let destVC = TWExplorePostsTableViewController() //init vc with storyboard, it has segue configured let destVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("topicsInNodeVC") as! TWExplorePostsTableViewController destVC.nodeName = filteredNodes[indexPath.row].name! destVC.nodeNameForTitle = filteredNodes[indexPath.row].title! self.navigationController?.pushViewController(destVC, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ //fix select back to Explore showing black screen override func viewWillDisappear(animated: Bool) { NSLog("will dispappear......") super.viewWillDisappear(true) self.searchController?.active = false } }
gpl-2.0
a13ae1d1946ca60b77ee6137ad9b24c2
35.642857
156
0.635478
5.883028
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.ChatTests/Models/SubscriptionQueriesSpec.swift
1
2506
// // SubscriptionQueriesSpec.swift // Rocket.ChatTests // // Created by Rafael Kellermann Streit on 23/04/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import XCTest import RealmSwift @testable import Rocket_Chat class SubscriptionManagerQueriesSpec: XCTestCase { override func tearDown() { super.tearDown() Realm.clearDatabase() } func testFindByRoomId() throws { let sub1 = Subscription() sub1.identifier = "sub1-identifier" sub1.rid = "sub1-rid" let sub2 = Subscription() sub2.identifier = "sub2-identifier" sub2.rid = "sub2-rid" Realm.current?.execute({ realm in realm.add(sub1, update: true) realm.add(sub2, update: true) }) XCTAssertEqual(Subscription.find(rid: "sub2-rid"), sub2) XCTAssertEqual(Subscription.find(rid: "sub1-rid"), sub1) } func testFindByNameAndType() throws { let sub1 = Subscription() sub1.identifier = "sub1-identifier" sub1.name = "sub1-name" sub1.type = .directMessage let sub2 = Subscription() sub2.identifier = "sub2-identifier" sub2.name = "sub2-name" sub2.type = .channel Realm.current?.execute({ realm in realm.add(sub1, update: true) realm.add(sub2, update: true) }) XCTAssertEqual(Subscription.find(name: "sub1-name", subscriptionType: [.directMessage]), sub1) XCTAssertEqual(Subscription.find(name: "sub2-name", subscriptionType: [.channel]), sub2) } func testSetTemporaryMessagesFailed() { let user = User.testInstance() let sub = Subscription.testInstance() let msg1 = Message.testInstance("msg1") msg1.rid = sub.rid msg1.failed = false msg1.temporary = true msg1.userIdentifier = user.identifier let msg2 = Message.testInstance("msg2") msg2.rid = sub.rid msg2.failed = false msg2.temporary = true msg2.userIdentifier = user.identifier Realm.current?.execute({ realm in realm.add(user, update: true) realm.add(sub, update: true) realm.add(msg1, update: true) realm.add(msg2, update: true) }) sub.setTemporaryMessagesFailed(user: user) XCTAssertTrue(msg1.failed) XCTAssertFalse(msg1.temporary) XCTAssertTrue(msg2.failed) XCTAssertFalse(msg2.temporary) } }
mit
642fc4c87e7f2c7b2b3bf6b16a607b6d
26.527473
102
0.612375
4.027331
false
true
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Moog Ladder Filter.xcplaygroundpage/Contents.swift
2
2635
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Moog Ladder Filter //: ### One of the coolest filters available in AudioKit is the Moog Ladder. It's based off of Robert Moog's iconic ladder filter, which was the first implementation of a voltage - controlled filter used in an analog synthesizer. As such, it was the first filter that gave the ability to use voltage control to determine the cutoff frequency of the filter. As we're dealing with a software implementation, and not an analog synthesizer, we don't have to worry about dealing with voltage control directly. However, by using this node, you can emulate some of the sounds of classic analog synthesizers in your app. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("mixloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var moogLadder = AKMoogLadder(player) //: Set the parameters of the Moog Ladder Filter here. moogLadder.cutoffFrequency = 300 // Hz moogLadder.resonance = 0.6 AudioKit.output = moogLadder AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { var cutoffFrequencyLabel: Label? var resonanceLabel: Label? override func setup() { addTitle("Moog Ladder Filter") addLabel("Audio Playback") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) cutoffFrequencyLabel = addLabel("Cutoff Frequency: \(moogLadder.cutoffFrequency)") addSlider(#selector(setCutoffFrequency), value: moogLadder.cutoffFrequency, minimum: 0, maximum: 5000) resonanceLabel = addLabel("Resonance: \(moogLadder.resonance)") addSlider(#selector(setResonance), value: moogLadder.resonance, minimum: 0, maximum: 0.99) } func start() { player.play() } func stop() { player.stop() } func setCutoffFrequency(slider: Slider) { moogLadder.cutoffFrequency = Double(slider.value) cutoffFrequencyLabel!.text = "Cutoff Frequency: \(String(format: "%0.0f", moogLadder.cutoffFrequency))" } func setResonance(slider: Slider) { moogLadder.resonance = Double(slider.value) resonanceLabel!.text = "Resonance: \(String(format: "%0.3f", moogLadder.resonance))" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 300)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
4c1b077d2b41455a58f54936a60b2028
37.75
612
0.712334
4.398998
false
false
false
false
hevertonrodrigues/HRSideBar
HRSideBar/HRSideBarView.swift
1
1079
// // HRSideBarView.swift // HRSideBar // // Created by Heverton Rodrigues on 23/09/14. // Copyright (c) 2014 Heverton Rodrigues. All rights reserved. // import Foundation import UIKit class HRSideBarView :UIView { private var width :Double = Double() private var height :Double = Double() override init() { super.init() self.backgroundColor = UIColor( rgba: "#AEAEAE" ) } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSize( width w :Double, height h :Double ) { self.width = w self.height = h self.frame = CGRectMake( CGFloat( -w ), 0, CGFloat( w ) , CGFloat( h ) ) } func open() { self.frame = CGRectMake( 0, 0, CGFloat( self.width ) , self.frame.size.height ) } func close() { self.frame = CGRectMake( CGFloat( -self.width ), 0, CGFloat( self.width ) , self.frame.size.height ) } }
mit
7d54d65ad2346aeb3da7e0145c950b1a
21.5
108
0.584801
3.785965
false
false
false
false
apple/swift
test/refactoring/ConvertAsync/convert_params_single.swift
7
17585
// RUN: %empty-directory(%t) // REQUIRES: concurrency func withError() async throws -> String { "" } func withError(_ completion: @escaping (String?, Error?) -> Void) { } func notOptional() async throws -> String { "" } func notOptional(_ completion: @escaping (String, Error?) -> Void) { } func errorOnly() async throws { } func errorOnly(_ completion: @escaping (Error?) -> Void) { } func test(_ str: String) -> Bool { return false } func testParamsSingle() async throws { // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNRELATED %s withError { res, err in if test("unrelated") { print("unrelated") } else { print("else unrelated") } } // UNRELATED: convert_params_single.swift // UNRELATED-NEXT: let res = try await withError() // UNRELATED-NEXT: if test("unrelated") { // UNRELATED-NEXT: print("unrelated") // UNRELATED-NEXT: } else { // UNRELATED-NEXT: print("else unrelated") // UNRELATED-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } if let str = res { print("got result \(str)") } print("after") } // BOUND: do { // BOUND-NEXT: let str = try await withError() // BOUND-NEXT: print("before") // BOUND-NEXT: print("got result \(str)") // BOUND-NEXT: print("after") // BOUND-NEXT: } catch let bad { // BOUND-NEXT: print("got error \(bad)") // BOUND-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND-COMMENT %s withError { res, err in // a // b print("before") // c if let bad = err { // d // e print("got error \(bad)") // f return // g } // h if let str = res { // i // j print("got result \(str)") // k } // l print("after") // m } // BOUND-COMMENT: do { // BOUND-COMMENT-NEXT: let str = try await withError() // BOUND-COMMENT-NEXT: // a // BOUND-COMMENT-NEXT: // b // BOUND-COMMENT-NEXT: print("before") // BOUND-COMMENT-NEXT: // c // BOUND-COMMENT-NEXT: // h // BOUND-COMMENT-NEXT: // i // BOUND-COMMENT-NEXT: // j // BOUND-COMMENT-NEXT: print("got result \(str)") // BOUND-COMMENT-NEXT: // k // BOUND-COMMENT-NEXT: // l // BOUND-COMMENT-NEXT: print("after") // BOUND-COMMENT-NEXT: // m // BOUND-COMMENT-NEXT: } catch let bad { // BOUND-COMMENT-NEXT: // d // BOUND-COMMENT-NEXT: // e // BOUND-COMMENT-NEXT: print("got error \(bad)") // BOUND-COMMENT-NEXT: // f // BOUND-COMMENT-NEXT: // g // BOUND-COMMENT-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") guard let str = res else { print("got error \(err!)") return } print("got result \(str)") print("after") } // UNBOUND-ERR: do { // UNBOUND-ERR-NEXT: let str = try await withError() // UNBOUND-ERR-NEXT: print("before") // UNBOUND-ERR-NEXT: print("got result \(str)") // UNBOUND-ERR-NEXT: print("after") // UNBOUND-ERR-NEXT: } catch let err { // UNBOUND-ERR-NEXT: print("got error \(err)") // UNBOUND-ERR-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else if let str = res { print("got result \(str)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=BOUND %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } if let str = res { print("got result \(str)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") return } print("got result \(res!)") print("after") } // UNBOUND-RES: do { // UNBOUND-RES-NEXT: let res = try await withError() // UNBOUND-RES-NEXT: print("before") // UNBOUND-RES-NEXT: print("got result \(res)") // UNBOUND-RES-NEXT: print("after") // UNBOUND-RES-NEXT: } catch let bad { // UNBOUND-RES-NEXT: print("got error \(bad)") // UNBOUND-RES-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") print("after") return } print("got error \(err!)") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-RES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else { print("got result \(res!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err != nil { print("got error \(err!)") return } print("got result \(res!)") print("after") } // UNBOUND: do { // UNBOUND-NEXT: let res = try await withError() // UNBOUND-NEXT: print("before") // UNBOUND-NEXT: print("got result \(res)") // UNBOUND-NEXT: print("after") // UNBOUND-NEXT: } catch let err { // UNBOUND-NEXT: print("got error \(err)") // UNBOUND-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res != nil { print("got result \(res!)") print("after") return } print("got error \(err!)") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err != nil { print("got error \(err!)") } else { print("got result \(res!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res != nil { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if err == nil { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if res == nil { print("got error \(err!)") } else { print("got result \(res!)") } print("after") } // Cannot use refactor-check-compiles because of the placeholder, compiler is unable to infer 'str'. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNHANDLEDNESTED %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } else { if let str = res { print("got result \(str)") } } print("after") } // UNHANDLEDNESTED: do { // UNHANDLEDNESTED-NEXT: let res = try await withError() // UNHANDLEDNESTED-NEXT: print("before") // UNHANDLEDNESTED-NEXT: if let str = <#res#> { // UNHANDLEDNESTED-NEXT: print("got result \(str)") // UNHANDLEDNESTED-NEXT: } // UNHANDLEDNESTED-NEXT: print("after") // UNHANDLEDNESTED-NEXT: } catch let bad { // UNHANDLEDNESTED-NEXT: print("got error \(bad)") // UNHANDLEDNESTED-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOERR %s withError { res, err in print("before") if let str = res { print("got result \(str)") } print("after") } // NOERR: convert_params_single.swift // NOERR-NEXT: let str = try await withError() // NOERR-NEXT: print("before") // NOERR-NEXT: print("got result \(str)") // NOERR-NEXT: print("after") // NOERR-NOT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NORES %s withError { res, err in print("before") if let bad = err { print("got error \(bad)") } print("after") } // NORES: do { // NORES-NEXT: let res = try await withError() // NORES-NEXT: print("before") // NORES-NEXT: print("after") // NORES-NEXT: } catch let bad { // NORES-NEXT: print("got error \(bad)") // NORES-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") if ((res != (nil)) && err == nil) { print("got result \(res!)") } else { print("got error \(err!)") } print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-COND %s withError { res, err in print("before") if res != nil && test(res!) { print("got result \(res!)") } print("after") } // UNKNOWN-COND: convert_params_single.swift // UNKNOWN-COND-NEXT: let res = try await withError() // UNKNOWN-COND-NEXT: print("before") // UNKNOWN-COND-NEXT: if <#res#> != nil && test(res) { // UNKNOWN-COND-NEXT: print("got result \(res)") // UNKNOWN-COND-NEXT: } // UNKNOWN-COND-NEXT: print("after") // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNKNOWN-CONDELSE %s withError { res, err in print("before") if res != nil && test(res!) { print("got result \(res!)") } else { print("bad") } print("after") } // UNKNOWN-CONDELSE: var res: String? = nil // UNKNOWN-CONDELSE-NEXT: var err: Error? = nil // UNKNOWN-CONDELSE-NEXT: do { // UNKNOWN-CONDELSE-NEXT: res = try await withError() // UNKNOWN-CONDELSE-NEXT: } catch { // UNKNOWN-CONDELSE-NEXT: err = error // UNKNOWN-CONDELSE-NEXT: } // UNKNOWN-CONDELSE-EMPTY: // UNKNOWN-CONDELSE-NEXT: print("before") // UNKNOWN-CONDELSE-NEXT: if res != nil && test(res!) { // UNKNOWN-CONDELSE-NEXT: print("got result \(res!)") // UNKNOWN-CONDELSE-NEXT: } else { // UNKNOWN-CONDELSE-NEXT: print("bad") // UNKNOWN-CONDELSE-NEXT: } // UNKNOWN-CONDELSE-NEXT: print("after") // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=MULTIBIND %s withError { res, err in print("before") if let str = res { print("got result \(str)") } if let str2 = res { print("got result \(str2)") } if case (let str3?) = (res) { print("got result \(str3)") } print("after") } // MULTIBIND: let str = try await withError() // MULTIBIND-NEXT: print("before") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("got result \(str)") // MULTIBIND-NEXT: print("after") // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NESTEDRET %s withError { res, err in print("before") if let str = res { if test(str) { return } print("got result \(str)") } print("after") } // NESTEDRET: convert_params_single.swift // NESTEDRET-NEXT: let str = try await withError() // NESTEDRET-NEXT: print("before") // NESTEDRET-NEXT: if test(str) { // NESTEDRET-NEXT: <#return#> // NESTEDRET-NEXT: } // NESTEDRET-NEXT: print("got result \(str)") // NESTEDRET-NEXT: print("after") // NESTEDRET-NOT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND-ERR %s withError { res, err in print("before") guard let str = res, err == nil else { print("got error \(err!)") return } print("got result \(str)") print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard res != nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard err == nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNBOUND %s withError { res, err in print("before") guard res != nil && err == nil else { print("got error \(err!)") return } print("got result \(res!)") print("after") } // Cannot use refactor-check-compiles as transform results in invalid code, // see comment below. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=UNWRAPPING %s withError { str, err in print("before") guard err == nil else { return } _ = str!.count _ = /*before*/str!/*after*/.count _ = str?.count _ = str!.count.bitWidth _ = str?.count.bitWidth _ = (str?.count.bitWidth)! _ = str!.first?.isWhitespace _ = str?.first?.isWhitespace _ = (str?.first?.isWhitespace)! print("after") } // UNWRAPPING: let str = try await withError() // UNWRAPPING-NEXT: print("before") // UNWRAPPING-NEXT: _ = str.count // UNWRAPPING-NEXT: _ = /*before*/str/*after*/.count // UNWRAPPING-NEXT: _ = str.count // UNWRAPPING-NEXT: _ = str.count.bitWidth // UNWRAPPING-NEXT: _ = str.count.bitWidth // Note this transform results in invalid code as str.count.bitWidth is no // longer optional, but arguably it's more useful than leaving str as a // placeholder. In general, the transform we perform here is locally valid // within the optional chain, but may change the type of the overall chain. // UNWRAPPING-NEXT: _ = (str.count.bitWidth)! // UNWRAPPING-NEXT: _ = str.first?.isWhitespace // UNWRAPPING-NEXT: _ = str.first?.isWhitespace // UNWRAPPING-NEXT: _ = (str.first?.isWhitespace)! // UNWRAPPING-NEXT: print("after") // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=NOT-OPTIONAL %s notOptional { str, err in print("before") if let err2 = err { print("got error \(err2)") return } print("got result \(str)") print("after") } // NOT-OPTIONAL: do { // NOT-OPTIONAL-NEXT: let str = try await notOptional() // NOT-OPTIONAL-NEXT: print("before") // NOT-OPTIONAL-NEXT: print("got result \(str)") // NOT-OPTIONAL-NEXT: print("after") // NOT-OPTIONAL-NEXT: } catch let err2 { // NOT-OPTIONAL-NEXT: print("got error \(err2)") // NOT-OPTIONAL-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=ERROR-ONLY %s errorOnly { err in print("before") if let err2 = err { print("got error \(err2)") return } print("after") } // ERROR-ONLY: convert_params_single.swift // ERROR-ONLY-NEXT: do { // ERROR-ONLY-NEXT: try await errorOnly() // ERROR-ONLY-NEXT: print("before") // ERROR-ONLY-NEXT: print("after") // ERROR-ONLY-NEXT: } catch let err2 { // ERROR-ONLY-NEXT: print("got error \(err2)") // ERROR-ONLY-NEXT: } // ERROR-ONLY-NOT: } }
apache-2.0
4cd61c095263a35fa49abd9730e1997d
31.869159
164
0.610634
3.466391
false
false
false
false
apple/swift
test/Parse/operator_decl.swift
4
5205
// RUN: %target-typecheck-verify-swift prefix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{20-23=}} postfix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{21-24=}} infix operator +++ {} // expected-error {{operator should no longer be declared with body}} {{19-22=}} infix operator +++* { // expected-error {{operator should no longer be declared with body; use a precedence group instead}} {{none}} associativity right } infix operator +++*+ : A { } // expected-error {{operator should no longer be declared with body}} {{25-29=}} prefix operator +++** : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{23-27=}} // expected-error@-2 {{operator should no longer be declared with body}} {{26-30=}} prefix operator ++*++ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{23-26=}} postfix operator ++*+* : A { } // expected-error@-1 {{only infix operators may declare a precedence}} {{24-28=}} // expected-error@-2 {{operator should no longer be declared with body}} {{27-31=}} postfix operator ++**+ : A // expected-error@-1 {{only infix operators may declare a precedence}} {{24-27=}} operator ++*** : A // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} operator +*+++ { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-error@-2 {{operator should no longer be declared with body}} {{15-19=}} operator +*++* : A { } // expected-error@-1 {{operator must be declared as 'prefix', 'postfix', or 'infix'}} // expected-error@-2 {{operator should no longer be declared with body}} {{19-23=}} prefix operator // expected-error {{expected operator name in operator declaration}} ; prefix operator %%+ prefix operator ?? postfix operator ?? // expected-error {{postfix operator names starting with '?' or '!' are disallowed to avoid collisions with built-in unwrapping operators}} prefix operator !! postfix operator !! // expected-error {{postfix operator names starting with '?' or '!' are disallowed to avoid collisions with built-in unwrapping operators}} postfix operator ?$$ // expected-error@-1 {{postfix operator names starting with '?' or '!' are disallowed}} // expected-error@-2 {{'$$' is considered an identifier}} infix operator --aa // expected-error {{'aa' is considered an identifier and must not appear within an operator name}} infix operator aa--: A // expected-error {{'aa' is considered an identifier and must not appear within an operator name}} infix operator <<$$@< // expected-error {{'$$' is considered an identifier and must not appear within an operator name}} infix operator !!@aa // expected-error {{'@' is not allowed in operator names}} infix operator #++= // expected-error {{'#' is not allowed in operator names}} infix operator ++=# // expected-error {{'#' is not allowed in operator names}} infix operator -># // expected-error {{'#' is not allowed in operator names}} // FIXME: Ideally, we shouldn't emit the «consistent whitespace» diagnostic // where = cannot possibly mean an assignment. infix operator =#= // expected-error@-1 {{'#' is not allowed in operator names}} // expected-error@-2 {{'=' must have consistent whitespace on both sides}} infix operator +++= infix operator *** : A infix operator --- : ; // expected-error {{expected precedence group name after ':' in operator declaration}} precedencegroup { // expected-error {{expected identifier after 'precedencegroup'}} associativity: right } precedencegroup A { associativity right // expected-error {{expected colon after attribute name in precedence group}} } precedencegroup B { precedence 123 // expected-error {{'precedence' is not a valid precedence group attribute}} } precedencegroup C { associativity: sinister // expected-error {{expected 'none', 'left', or 'right' after 'associativity'}} } precedencegroup D { assignment: no // expected-error {{expected 'true' or 'false' after 'assignment'}} } precedencegroup E { higherThan: } // expected-error {{expected name of related precedence group after 'higherThan'}} precedencegroup F { higherThan: A, B, C } precedencegroup BangBangBang { associativity: none associativity: left // expected-error{{'associativity' attribute for precedence group declared multiple times}} } precedencegroup CaretCaretCaret { assignment: true assignment: false // expected-error{{'assignment' attribute for precedence group declared multiple times}} } class Foo { infix operator ||| // expected-error{{'operator' may only be declared at file scope}} } infix operator **<< : UndeclaredPrecedenceGroup // expected-error@-1 {{unknown precedence group 'UndeclaredPrecedenceGroup'}} protocol Proto {} infix operator *<*< : F, Proto // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{expected expression}} // https://github.com/apple/swift/issues/60932 // expected-error@+2 {{expected precedence group name after ':' in operator declaration}} postfix operator ++: // expected-error {{only infix operators may declare a precedence}} {{20-21=}}
apache-2.0
ba79c06fad8cedb3a375535e6bb13665
43.470085
159
0.708437
4.278783
false
false
false
false
anasmeister/nRF-Coventry-University
nRF Toolbox/MainViewController/NORMainViewController.swift
1
3369
// // NORMainViewController.swift // nRF Toolbox // // Created by Mostafa Berg on 27/04/16. // Copyright © 2016 Nordic Semiconductor. All rights reserved. // Edited by Anastasios Panagoulias on 11/01/07 import UIKit class NORMainViewController: UIViewController, UICollectionViewDataSource, UIAlertViewDelegate { // MARK: - Outlets & Actions @IBOutlet weak var collectionView: UICollectionView! @IBAction func aboutButtonTapped(_ sender: AnyObject) { showAboutAlertView() } // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self; } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) } override func viewDidAppear(_ animated: Bool) { let isUserLoggedIn = UserDefaults.standard.bool(forKey: "isUserLoggedIn") if (!isUserLoggedIn){ self.performSegue(withIdentifier: "loginView", sender: self) } } @IBAction func logoutButtonTapped(_ sender: Any) { UserDefaults.standard.set(false, forKey: "isUserLoggedIn") UserDefaults.standard.synchronize() self.performSegue(withIdentifier: "loginView", sender: self) } func showAboutAlertView() { //let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String //Note: The character \u{2022} found here is a unicode bullet, used just for styling purposes let aboutMessage = String("This application is a creation of Anastasios Panagoulias on behalf of Coventry University and the Module M99 EKM of the academic year 2016-2017. This application is part of the Dissertation Module. Several parts of this application are taken from the nRF Toolbox official open source App. This application is designed to work with the most popular Low Energy Bluetooth accessories that use standard BLE profiles. This Application has been tested with the Nordic Semiconductor nRF 52 - DK. It supports Nordic Semiconductor's proprietary profiles:\n\n\u{2022}UART (Universal Asynchronous Receiver/Transmitter),\n\n\u{2022}DFU (Device Firmware Update).\n\nMore information and the source code may be found on GitHub.\n\nVersion 0.2") let alertView = UIAlertView.init(title: "About", message: aboutMessage!, delegate: self, cancelButtonTitle: "Ok", otherButtonTitles:"GitHub") alertView.show() } // MARK: - UIalertViewDelegate func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { if buttonIndex == 1 { UIApplication.shared.openURL(URL(string: "https://github.com/anasmeister/nRF-Coventry-University")!) } } // MARK: - UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cellName = String(format: "profile_%d", (indexPath as NSIndexPath).item) return collectionView.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath) } }
bsd-3-clause
f9659390bb63536dfe4b58e018f1e1ad
43.315789
766
0.703979
5.03438
false
false
false
false
brentdax/swift
test/Driver/multi-threaded.swift
1
4722
// RUN: %empty-directory(%t) // RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-module -o test.swiftmodule | %FileCheck -check-prefix=MODULE %s // RUN: echo "{\"%s\": {\"assembly\": \"/build/multi-threaded.s\"}, \"%S/Inputs/main.swift\": {\"assembly\": \"/build/main.s\"}}" > %t/ofms.json // RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofms.json -S | %FileCheck -check-prefix=ASSEMBLY %s // RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c | %FileCheck -check-prefix=OBJECT %s // RUN: %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -c 2> %t/parseable-output // RUN: cat %t/parseable-output | %FileCheck -check-prefix=PARSEABLE %s // RUN: (cd %t && env TMPDIR=/tmp %swiftc_driver -driver-print-jobs -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -o a.out ) | %FileCheck -check-prefix=EXEC %s // RUN: echo "{\"%s\": {\"llvm-bc\": \"multi-threaded.bc\", \"object\": \"%t/multi-threaded.o\"}, \"%S/Inputs/main.swift\": {\"llvm-bc\": \"main.bc\", \"object\": \"%t/main.o\"}}" > %t/ofmo.json // RUN: %target-swiftc_driver -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -emit-dependencies -output-file-map %t/ofmo.json -c // RUN: cat %t/*.d | %FileCheck -check-prefix=DEPENDENCIES %s // Check if -embed-bitcode works // RUN: %target-swiftc_driver -driver-print-jobs -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -c | %FileCheck -check-prefix=BITCODE %s // Check if -embed-bitcode works with -parseable-output // RUN: %target-swiftc_driver -parseable-output -module-name=ThisModule -embed-bitcode -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -c 2> %t/parseable2 // RUN: cat %t/parseable2 | %FileCheck -check-prefix=PARSEABLE2 %s // Check if linking works with -parseable-output // RUN: (cd %t && %target-swiftc_driver -parseable-output -module-name=ThisModule -wmo -num-threads 4 %S/Inputs/main.swift %s -output-file-map %t/ofmo.json -o a.out) 2> %t/parseable3 // RUN: cat %t/parseable3 | %FileCheck -check-prefix=PARSEABLE3 %s // MODULE: -frontend // MODULE-DAG: -num-threads 4 // MODULE-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift // MODULE-DAG: -o test.swiftmodule // MODULE-NOT: ld // ASSEMBLY: -frontend // ASSEMBLY-DAG: -num-threads 4 // ASSEMBLY-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift // ASSEMBLY-DAG: -o /build/main.s -o /build/multi-threaded.s // ASSEMBLY-NOT: ld // OBJECT: -frontend // OBJECT-DAG: -num-threads 4 // OBJECT-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift // OBJECT-DAG: -o main.o -o multi-threaded.o // OBJECT-NOT: ld // BITCODE: -frontend // BITCODE-DAG: -num-threads 4 // BITCODE-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift // BITCODE-DAG: -o main.bc -o multi-threaded.bc // BITCODE-DAG: -frontend -c -primary-file main.bc {{.*}} -o {{[^ ]*}}main.o // BITCODE-DAG: -frontend -c -primary-file multi-threaded.bc {{.*}} -o {{[^ ]*}}multi-threaded.o // BITCODE-NOT: ld // PARSEABLE: "outputs": [ // PARSEABLE: "path": "main.o" // PARSEABLE: "path": "multi-threaded.o" // EXEC: -frontend // EXEC-DAG: -num-threads 4 // EXEC-DAG: {{[^ ]*}}/Inputs/main.swift {{[^ ]*}}/multi-threaded.swift // EXEC-DAG: -o /tmp/main{{[^ ]*}}.o -o /tmp/multi-threaded{{[^ ]*}}.o // EXEC: ld // EXEC: /tmp/main{{[^ ]*}}.o /tmp/multi-threaded{{[^ ]*}}.o // DEPENDENCIES-DAG: {{.*}}/multi-threaded.o : {{.*}}/multi-threaded.swift {{.*}}/Inputs/main.swift // DEPENDENCIES-DAG: {{.*}}/main.o : {{.*}}/multi-threaded.swift {{.*}}/Inputs/main.swift // PARSEABLE2: "name": "compile" // PARSEABLE2: "outputs": [ // PARSEABLE2: "path": "main.bc" // PARSEABLE2: "path": "multi-threaded.bc" // PARSEABLE2: "name": "backend" // PARSEABLE2: "inputs": [ // PARSEABLE2: "main.bc" // PARSEABLE2: "outputs": [ // PARSEABLE2: "path": "{{.*}}/main.o" // PARSEABLE2: "name": "backend" // PARSEABLE2: "inputs": [ // PARSEABLE2: "multi-threaded.bc" // PARSEABLE2: "outputs": [ // PARSEABLE2: "path": "{{.*}}/multi-threaded.o" // PARSEABLE3: "name": "compile" // PARSEABLE3: "outputs": [ // PARSEABLE3: "path": "{{.*}}/main.o" // PARSEABLE3: "path": "{{.*}}/multi-threaded.o" // PARSEABLE3: "name": "link" // PARSEABLE3: "inputs": [ // PARSEABLE3-NEXT: "{{.*}}/main.o" // PARSEABLE3-NEXT: "{{.*}}/multi-threaded.o" // PARSEABLE3: "outputs": [ // PARSEABLE3: "path": "a.out" func libraryFunction() {}
apache-2.0
718dadc81a2f4dd600d8848ec782b193
50.89011
202
0.645489
3
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
solutions/31_Next_Permutation.playground/Contents.swift
1
1792
// #31 Next Permutation https://leetcode.com/problems/next-permutation/ // 代码写起来很简单,数学推导稍微多一些。方法如下: // 从右往左找第一个比右边小的数字(如果找不到,逆转整个数组即可),其 index 为 leftNumIndex。再找它右边比它大的数字(一定存在)里最小的,由于右边是降序,从右往左找的第一个即是,index 为 rightNumIndex。swap 两个 index 的 num。 // leftNumIndex 左边是不变的,下面看右边。右边本来是降序,能保证 swap 过后也是(不严格的)降序。换成升序,只需逆转这部分。 // 时间复杂度:O(n) 空间复杂度:O(1) class Solution { func nextPermutation(_ nums: inout [Int]) { var leftNumIndex = -1 for (index, num) in nums.enumerated().reversed() { if index != nums.count - 1 && num < nums[index + 1] { leftNumIndex = index break } } if leftNumIndex == -1 { reverse(&nums, fromIndex: 0) return } var rightNumIndex = -1 for (index, num) in nums.enumerated().reversed() { if num > nums[leftNumIndex] { rightNumIndex = index break } } swap(&nums[leftNumIndex], &nums[rightNumIndex]) reverse(&nums, fromIndex: leftNumIndex + 1) } func reverse(_ nums: inout [Int], fromIndex: Int) { var leftIndex = fromIndex, rightIndex = nums.count - 1 while leftIndex < rightIndex { swap(&nums[leftIndex], &nums[rightIndex]) leftIndex += 1 rightIndex -= 1 } } } var nums = [3, 1, 2] Solution().nextPermutation(&nums) nums
mit
d6b00b5ce992a767456af9f8b39306f4
30.630435
142
0.560523
3.590123
false
false
false
false
midoks/Swift-Learning
GitHubStar/GitHubStar/GitHubStar/Vendor/MDDropDownList/MDDropDownList.swift
1
7663
// // // Created by midoks on 15/12/30. // Copyright © 2015年 midoks. All rights reserved. // import UIKit class MDDropDownBackView:UIView { var _backView:UIView? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear //背景色 _backView = UIView(frame: frame) _backView!.backgroundColor = UIColor.black _backView!.layer.opacity = 0.2 addSubview(_backView!) let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap)) self.addGestureRecognizer(tap) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //点击消失 func tap(){ UIView.animate(withDuration: 0.25, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.layer.opacity = 0.0 }) { (status) -> Void in self.hide() self.layer.opacity = 1 } } func hide(){ self.removeFromSuperview() } override func layoutSubviews() { super.layoutSubviews() self._backView?.frame = frame } } class MDDropDownListView:UIView { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //下拉类 class MDDropDownList : UIView { var listClick:(( _ tag:Int) -> ())? var bbView:MDDropDownBackView? var listView:UIView? var listButton: Array<UIButton> = Array<UIButton>() var listTriangleButton:UIButton? var listSize:CGSize = CGSize(width: 150.0, height: 50.0) var listImageSize:CGSize = CGSize(width: 40.0, height: 30.0) var navHeight:CGFloat = 64.0 override init(frame: CGRect) { super.init(frame:frame) self.bbView = MDDropDownBackView(frame: frame) self.listView = MDDropDownListView(frame: CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight, width: self.listSize.width, height: 0)) self.listView!.backgroundColor = UIColor.white self.listView!.layer.cornerRadius = 3 self.bbView?.addSubview(self.listView!) self.listTriangleButton = UIButton(frame: CGRect(x: frame.width - 33, y: self.navHeight - 13, width: 15, height: 15)) self.listTriangleButton?.setTitle("▲", for: .normal) self.listTriangleButton?.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15.0) self.bbView?.addSubview(self.listTriangleButton!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //重新设置位置 func setViewFrame(frame: CGRect){ if UIDevice.current.orientation.isLandscape { self.listView?.frame = CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight+1, width: self.listSize.width, height: self.listView!.frame.height) self.listTriangleButton?.frame = CGRect(x: frame.width - 35, y: self.navHeight - 11, width: 15, height: 15) } else { self.listView?.frame = CGRect(x: frame.width - self.listSize.width - 5, y: self.navHeight, width: self.listSize.width, height: self.listView!.frame.height) self.listTriangleButton?.frame = CGRect(x: frame.width - 33, y: self.navHeight - 12, width: 15, height: 15) } self.bbView?.frame = frame self.frame = frame } //MARK: - Private Methods - //生成纯色背景 func imageWithColor(color:UIColor, size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.height, height: size.height) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } //点击 func listClick(s:UIButton){ //if listClick != nil { //listClick?(tag: s.tag) //} // self.hide() // self.touchDragOutside(s: s) } //鼠标按下操作 func touchDown(s:UIButton){ //s.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1) } //鼠标按下离开操作 func touchDragOutside(s:UIButton){ s.backgroundColor = UIColor.white } //添加按钮 func add(icon:UIImage, title:String){ let c = self.listButton.count let bheight = self.listSize.height * CGFloat(c) let bbViewHeight = self.listSize.height * CGFloat(c+1) self.listView?.frame = CGRect(x: (self.listView?.frame.origin.x)!, y: (self.listView?.frame.origin.y)!, width: (self.listView?.frame.size.width)!, height: bbViewHeight) let u = UIButton(frame: CGRect(x: 0, y: bheight, width: self.listSize.width, height: self.listSize.height)) u.tag = c u.setImage(icon, for: .normal) u.setImage(icon, for: .highlighted) u.setTitle(title, for: .normal) u.setTitleColor(UIColor.black, for: .normal) u.layer.cornerRadius = 3 u.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14.0) u.backgroundColor = UIColor.white u.contentHorizontalAlignment = .left u.imageEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0) u.titleEdgeInsets = UIEdgeInsetsMake(0, 40, 0, 0) u.addTarget(self, action: Selector(("listClick:")), for: UIControlEvents.touchUpInside) // u.addTarget(self, action: "touchDown:", for: UIControlEvents.touchDown) // u.addTarget(self, action: "touchDragOutside:", for: UIControlEvents.touchDragOutside) if ( c>0 ) { let line = UIView(frame: CGRect(x: 0, y: 0, width: u.frame.width, height: 1)) line.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1) u.addSubview(line) } self.listView!.addSubview(u) self.listButton.append(u) } //动画显示特效 func showAnimation(){ UIApplication.shared.windows.first?.addSubview(self.bbView!) let sFrame = self.listView?.frame self.listView?.frame.size = CGSize(width: 0.0, height: 0.0) self.listView?.frame.origin.x = sFrame!.origin.x + (sFrame?.width)! self.listView?.layer.opacity = 0 self.listTriangleButton?.layer.opacity = 0 UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in self.listView?.frame.size.height += sFrame!.size.height self.listView?.frame.origin.x -= (sFrame?.width)! self.listView?.layer.opacity = 1 self.listTriangleButton?.layer.opacity = 0.6 }) { (status) -> Void in self.listView?.layer.opacity = 1 self.listTriangleButton?.layer.opacity = 1 self.listView?.frame = sFrame! } } //隐藏 func hide(){ self.bbView!.removeFromSuperview() } }
apache-2.0
647c7b6177578bcf52d4dfe4b86b7f87
31.299145
176
0.581106
4.306553
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Option/TamalesOaxaquenos/Physic/VOptionTamalesOaxaquenosPhysicFinish.swift
1
1597
import SpriteKit class VOptionTamalesOaxaquenosPhysicFinish:ViewGameNode<MOptionTamalesOaxaquenos> { private let positionX:CGFloat private let height:CGFloat private let width_2:CGFloat private let height_2:CGFloat private let kWidth:CGFloat = 250 override init(controller:ControllerGame<MOptionTamalesOaxaquenos>) { let areaWidth:CGFloat = MOptionTamalesOaxaquenosArea.kWidth height = MGame.sceneSize.height let size:CGSize = CGSize( width:kWidth, height:height) width_2 = kWidth / 2.0 height_2 = height / 2.0 positionX = areaWidth - width_2 super.init( controller:controller, size:size, zPosition:MOptionTamalesOaxaquenosZPosition.Physics.rawValue) startPhysics() } required init?(coder:NSCoder) { return nil } //MARK: private override func positionStart() { position = CGPoint(x:positionX, y:height_2) } private func startPhysics() { let edgeFrame:CGRect = CGRect( x:-width_2, y:-height_2, width:kWidth, height:height) let physicsBody:SKPhysicsBody = SKPhysicsBody(edgeLoopFrom:edgeFrame) physicsBody.categoryBitMask = MOptionTamalesOaxaquenosPhysicsStruct.Finish physicsBody.contactTestBitMask = MOptionTamalesOaxaquenosPhysicsStruct.Player physicsBody.collisionBitMask = MOptionTamalesOaxaquenosPhysicsStruct.None self.physicsBody = physicsBody } }
mit
57a21df79db764d85f11c424d9ac330a
28.574074
85
0.649343
5.151613
false
false
false
false
lieonCX/Live
Live/View/Home/Room/CollectionLiveTagView.swift
1
2317
// // CollectionLiveTagView.swift // Live // // Created by fanfans on 2017/7/4. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit class CollectionLiveTagView: UIView { fileprivate lazy var bgView: UIView = { let bgView = UIView() self.backgroundColor = UIColor.black .withAlphaComponent(0.6) return bgView }() fileprivate lazy var statusLabel: UILabel = { let statusLabel = UILabel() statusLabel.font = UIFont.systemFont(ofSize: 11) statusLabel.textColor = UIColor.white statusLabel.textAlignment = .center return statusLabel }() fileprivate lazy var statusView: UIView = { let statusView = UIView() statusView.layer.cornerRadius = 5 * 0.5 statusView.layer.masksToBounds = true return statusView }() override init(frame: CGRect) { super.init(frame: frame) self.layer.borderWidth = 0.5 self.layer.borderColor = UIColor.white.cgColor self.layer.cornerRadius = 16 * 0.5 self.layer.masksToBounds = true self.addSubview(bgView) self.addSubview(statusView) self.addSubview(statusLabel) bgView.snp.makeConstraints { (maker) in maker.left.equalTo(0) maker.right.equalTo(0) maker.top.equalTo(0) maker.bottom.equalTo(0) } statusView.snp.makeConstraints { (maker) in maker.centerY.equalTo(bgView.snp.centerY) maker.left.equalTo(3) maker.width.equalTo(5) maker.height.equalTo(5) } statusLabel.snp.makeConstraints { (maker) in maker.left.equalTo(5) maker.right.equalTo(0) maker.top.equalTo(0) maker.bottom.equalTo(0) } } func configWithListLiveType(type: ListLiveType) { if type == .living { statusLabel.text = "直播中" statusView.backgroundColor = UIColor(hex: CustomKey.Color.mainColor) } else { statusLabel.text = "回放中" statusView.backgroundColor = UIColor(hex:0x14eff) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b8655e7ba33cd7ea6ea2099cde6dc46e
30.108108
80
0.59861
4.426923
false
false
false
false
ddddxxx/LyricsX
LyricsX/Controller/MenuBarLyricsController.swift
2
5172
// // MenuBarLyrics.swift // LyricsX - https://github.com/ddddxxx/LyricsX // // 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 https://mozilla.org/MPL/2.0/. // import Cocoa import CXExtensions import CXShim import GenericID import LyricsCore import MusicPlayer import OpenCC import SwiftCF import AccessibilityExt class MenuBarLyricsController { static let shared = MenuBarLyricsController() let statusItem: NSStatusItem var lyricsItem: NSStatusItem? var buttonImage = #imageLiteral(resourceName: "status_bar_icon") var buttonlength: CGFloat = 30 private var screenLyrics = "" { didSet { DispatchQueue.main.async { self.updateStatusItem() } } } private var cancelBag = Set<AnyCancellable>() private init() { statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) AppController.shared.$currentLyrics .combineLatest(AppController.shared.$currentLineIndex) .receive(on: DispatchQueue.lyricsDisplay.cx) .invoke(MenuBarLyricsController.handleLyricsDisplay, weaklyOn: self) .store(in: &cancelBag) workspaceNC.cx .publisher(for: NSWorkspace.didActivateApplicationNotification) .signal() .invoke(MenuBarLyricsController.updateStatusItem, weaklyOn: self) .store(in: &cancelBag) defaults.publisher(for: [.menuBarLyricsEnabled, .combinedMenubarLyrics]) .prepend() .invoke(MenuBarLyricsController.updateStatusItem, weaklyOn: self) .store(in: &cancelBag) } private func handleLyricsDisplay(event: (lyrics: Lyrics?, index: Int?)) { guard !defaults[.disableLyricsWhenPaused] || selectedPlayer.playbackState.isPlaying, let lyrics = event.lyrics, let index = event.index else { screenLyrics = "" return } var newScreenLyrics = lyrics.lines[index].content if let converter = ChineseConverter.shared, lyrics.metadata.language?.hasPrefix("zh") == true { newScreenLyrics = converter.convert(newScreenLyrics) } if newScreenLyrics == screenLyrics { return } screenLyrics = newScreenLyrics } @objc private func updateStatusItem() { guard defaults[.menuBarLyricsEnabled], !screenLyrics.isEmpty else { setImageStatusItem() lyricsItem = nil return } if defaults[.combinedMenubarLyrics] { updateCombinedStatusLyrics() } else { updateSeparateStatusLyrics() } } private func updateSeparateStatusLyrics() { setImageStatusItem() if lyricsItem == nil { lyricsItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) lyricsItem?.highlightMode = false } lyricsItem?.title = screenLyrics } private func updateCombinedStatusLyrics() { lyricsItem = nil setTextStatusItem(string: screenLyrics) if statusItem.isVisibe { return } // truncation var components = screenLyrics.components(options: [.byWords]) while !components.isEmpty, !statusItem.isVisibe { components.removeLast() let proposed = components.joined() + "..." setTextStatusItem(string: proposed) } } private func setTextStatusItem(string: String) { statusItem.title = string statusItem.image = nil statusItem.length = NSStatusItem.variableLength } private func setImageStatusItem() { statusItem.title = "" statusItem.image = buttonImage statusItem.length = buttonlength } } // MARK: - Status Item Visibility private extension NSStatusItem { var isVisibe: Bool { guard let buttonFrame = button?.frame, let frame = button?.window?.convertToScreen(buttonFrame) else { return false } let point = CGPoint(x: frame.midX, y: frame.midY) guard let screen = NSScreen.screens.first(where: { $0.frame.contains(point) }) else { return false } let carbonPoint = CGPoint(x: point.x, y: screen.frame.height - point.y - 1) guard let element = try? AXUIElement.systemWide().element(at: carbonPoint), let pid = try? element.pid() else { return false } return getpid() == pid } } private extension String { func components(options: String.EnumerationOptions) -> [String] { var components: [String] = [] let range = Range(uncheckedBounds: (startIndex, endIndex)) enumerateSubstrings(in: range, options: options) { _, _, range, _ in components.append(String(self[range])) } return components } }
mpl-2.0
c55877d95dbe4d93778d2455511ff0b6
30.730061
103
0.615429
4.973077
false
false
false
false
luckymore0520/GreenTea
Loyalty/Cards/Model/Card.swift
1
3017
// // Card.swift // Loyalty // // Created by WangKun on 16/4/29. // Copyright © 2016年 WangKun. All rights reserved. // import UIKit import AVOSCloud class Card: AVObject,AVSubclassing { @NSManaged var activity:Activity @NSManaged var ownerId:String @NSManaged var currentCount:Int func getFullInfo(){ let query = Activity.query() query.getObjectInBackgroundWithId(self.activity.objectId) { (activity, error) in if let activity = activity as? Activity { self.activity = activity } } } var isFull:Bool { return activity.loyaltyCoinMaxCount == self.currentCount } static func parseClassName() -> String! { return "Card" } } extension Card { func collect(code:String, completionHandler:(success:Bool)->Void) { if self.currentCount == self.activity.loyaltyCoinMaxCount { completionHandler(success: false) } else { Coin.checkCode(self.activity, code: code, completionHandler: { (success) in if success { self.currentCount += 1 self.saveInBackgroundWithBlock({ (success, error) in completionHandler(success: success) }) } else { completionHandler(success: false) } }) } } static func queryCardWithId(objectId:String, completionHandler:Card?->Void) { let query = Card.query() query.includeKey("activity") query.getObjectInBackgroundWithId(objectId) { (card, error) in if let card = card as? Card { completionHandler(card) } else { completionHandler(nil) } } } static func queryCardsOfUser(userName:String,completionHandler:[Card]->Void) { let query = Card.query() query.whereKey("ownerId", equalTo: userName) query.includeKey("activity") query.findObjectsInBackgroundWithBlock { (cards, error) in if cards.count > 0 { let cardList = cards as! [Card] completionHandler(cardList) } } } static func obtainNewCard(activity:Activity, completionHandler:(card:Card?,errorMsg:String?) -> Void) { guard let user = UserInfoManager.sharedManager.currentUser else { completionHandler(card: nil, errorMsg: "登录后才能领取集点卡") return } let card = Card() card.activity = activity card.ownerId = user.username card.currentCount = 0 card.saveInBackgroundWithBlock { (success, error) in if success { user.addNewCard(card) completionHandler(card: card,errorMsg: nil) } else { completionHandler(card: nil, errorMsg: NSError.errorMsg(error)) } } } }
mit
d6998b388be2674614525d77b6319126
29.561224
107
0.566132
4.965174
false
false
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO iOS/ListViewController.swift
1
9786
// // ListViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid class ListViewController: UIViewController { var searchedTerm = "" var searchTimer: Timer? @IBOutlet weak var tableView: UITableView! @IBOutlet weak var orderButton: UIBarButtonItem! @IBOutlet weak var filterButton: UIBarButtonItem! fileprivate var tasks: [Task] = [] fileprivate var subscription: RapidSubscription? fileprivate var ordering = RapidOrdering(keyPath: Task.createdAttributeName, ordering: .descending) fileprivate var filter: RapidFilter? override func viewDidLoad() { super.viewDidLoad() setupUI() subscribe() } // MARK: Actions @IBAction func addTask(_ sender: Any) { presentNewTaskController() } @objc func showOrderModal(_ sender: Any) { presentOrderModal() } @objc func showFilterModal(_ sender: Any) { presentFilterModal() } } fileprivate extension ListViewController { func setupUI() { navigationController?.navigationBar.prefersLargeTitles = true let searchController = UISearchController(searchResultsController: nil) searchController.delegate = self searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true navigationItem.searchController = searchController navigationItem.title = "Tasks" navigationItem.largeTitleDisplayMode = .always tableView.dataSource = self tableView.delegate = self tableView.separatorColor = .appSeparator tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension orderButton.target = self orderButton.action = #selector(self.showOrderModal(_:)) filterButton.target = self filterButton.action = #selector(self.showFilterModal(_:)) } /// Subscribe to a collection func subscribe() { // If there is a previous subscription then unsubscribe from it subscription?.unsubscribe() tasks.removeAll() tableView.reloadData() // Get Rapid collection reference with a given name var collection = Rapid.collection(named: Constants.collectionName) // If a filter is set, modify the collection reference with it if let filter = filter { // If the search bar text is not empty, filter also by the text if !searchedTerm.isEmpty { // The search bar text can be in a title or in a description // Combine two "CONTAINS" filters with logical "OR" let combinedFilter = RapidFilter.or([ RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm), RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm) ]) // And then, combine the search bar text filter with a filter from the filter modal collection.filtered(by: RapidFilter.and([filter, combinedFilter])) } else { // Associate the collection reference with the filter collection.filtered(by: filter) } } // If the searchBar text is not empty, filter by the text else if !searchedTerm.isEmpty { let combinedFilter = RapidFilter.or([ RapidFilter.contains(keyPath: Task.titleAttributeName, subString: searchedTerm), RapidFilter.contains(keyPath: Task.descriptionAttributeName, subString: searchedTerm) ]) collection.filtered(by: combinedFilter) } // Order the collection by a given ordering // Subscribe to the collection // Store a subscribtion reference to be able to unsubscribe from it subscription = collection.order(by: ordering).subscribeWithChanges { result in switch result { case .success(let changes): let (documents, insert, update, delete) = changes let previousSet = self.tasks self.tasks = documents.flatMap({ Task(withSnapshot: $0) }) self.tableView.animateChanges(previousData: previousSet, data: self.tasks, new: insert, updated: update, deleted: delete) case .failure: self.tasks = [] self.tableView.reloadData() } } } func presentNewTaskController() { let controller = self.storyboard!.instantiateViewController(withIdentifier: "TaskNavigationViewController") present(controller, animated: true, completion: nil) } func presentOrderModal() { let controller = self.storyboard?.instantiateViewController(withIdentifier: "OrderViewController") as! OrderViewController controller.delegate = self controller.ordering = ordering controller.modalPresentationStyle = .custom controller.modalTransitionStyle = .crossDissolve present(controller, animated: true, completion: nil) } func presentFilterModal() { let controller = self.storyboard?.instantiateViewController(withIdentifier: "FilterViewController") as! FilterViewController controller.delegate = self controller.filter = filter controller.modalPresentationStyle = .custom controller.modalTransitionStyle = .crossDissolve present(controller, animated: true, completion: nil) } func presentEditTask(_ task: Task) { let controller = self.storyboard?.instantiateViewController(withIdentifier: "TaskViewController") as! TaskViewController controller.task = task navigationController?.pushViewController(controller, animated: true) } } // MARK: Table view extension ListViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath) as! TaskCell let task = tasks[indexPath.row] cell.configure(withTask: task, delegate: self) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let task = tasks[indexPath.row] presentEditTask(task) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let action = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completion) in let task = self.tasks[indexPath.row] task.delete() } action.backgroundColor = .appRed return UISwipeActionsConfiguration(actions: [action]) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let task = tasks[indexPath.row] task.delete() } } } extension ListViewController: TaskCellDelegate { func cellCheckmarkChanged(_ cell: TaskCell, value: Bool) { if let indexPath = tableView.indexPath(for: cell) { let task = tasks[indexPath.row] task.updateCompleted(value) } } } // MARK: Search bar delegate extension ListViewController: UISearchControllerDelegate, UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard searchedTerm != (searchController.searchBar.text ?? "") else { return } searchedTerm = searchController.searchBar.text ?? "" searchTimer?.invalidate() searchTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in self?.subscribe() } } } // MARK: Ordering delegate extension ListViewController: OrderViewControllerDelegate { func orderViewControllerDidCancel(_ controller: OrderViewController) { controller.dismiss(animated: true, completion: nil) } func orderViewControllerDidFinish(_ controller: OrderViewController, withOrdering ordering: RapidOrdering) { self.ordering = ordering subscribe() controller.dismiss(animated: true, completion: nil) } } // MARK: Filter delegate extension ListViewController: FilterViewControllerDelegate { func filterViewControllerDidCancel(_ controller: FilterViewController) { controller.dismiss(animated: true, completion: nil) } func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) { self.filter = filter subscribe() controller.dismiss(animated: true, completion: nil) } }
mit
b337f26192b1a8ab960eb130b1e98cef
34.711679
142
0.646602
5.715537
false
false
false
false
alblue/swift
test/SILGen/global_resilience.swift
1
4303
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift // RUN: %target-swift-emit-silgen -I %t -enable-resilience -enable-sil-ownership -parse-as-library %s | %FileCheck %s // RUN: %target-swift-emit-sil -I %t -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s import resilient_global public struct MyEmptyStruct {} // CHECK-LABEL: sil_global @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct public var myEmptyGlobal = MyEmptyStruct() // CHECK-LABEL: sil_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp : $MyEmptyStruct @_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct() // Mutable addressor for resilient global // CHECK-LABEL: sil hidden [global_init] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau : $@convention(thin) () -> Builtin.RawPointer // CHECK: global_addr @$s17global_resilience13myEmptyGlobalAA02MyD6StructVv // CHECK: return // Synthesized accessors for our resilient global variable // CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvg // CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau // CHECK: return // CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvs // CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau // CHECK: return // CHECK-LABEL: sil @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvM // CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau // CHECK: begin_access [modify] [dynamic] // CHECK: yield // CHECK: end_access // Mutable addressor for fixed-layout global // CHECK-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau // CHECK: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv // CHECK: return // CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0 // CHECK-OPT: alloc_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv // CHECK-OPT: return // CHECK-OPT-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau // CHECK-OPT: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp // CHECK-OPT: function_ref @globalinit_{{.*}}_func0 // CHECK-OPT: return // Accessing resilient global from our resilience domain -- // call the addressor directly // CHECK-LABEL: sil @$s17global_resilience16getMyEmptyGlobalAA0dE6StructVyF // CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau // CHECK: return public func getMyEmptyGlobal() -> MyEmptyStruct { return myEmptyGlobal } // Accessing resilient global from a different resilience domain -- // access it with accessors // CHECK-LABEL: sil @$s17global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF // CHECK: function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvg // CHECK: return public func getEmptyGlobal() -> EmptyResilientStruct { return emptyGlobal } // CHECK-LABEL: sil @$s17global_resilience17modifyEmptyGlobalyyF // CHECK: [[MODIFY:%.*]] = function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvM // CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[FN:%.*]] = function_ref @$s16resilient_global20EmptyResilientStructV6mutateyyF // CHECK-NEXT: apply [[FN]]([[ADDR]]) // CHECK-NEXT: end_apply [[TOKEN]] // CHECK-NEXT: tuple // CHECK-NEXT: return public func modifyEmptyGlobal() { emptyGlobal.mutate() } // Accessing fixed-layout global from a different resilience domain -- // call the addressor directly // CHECK-LABEL: sil @$s17global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF // CHECK: function_ref @$s16resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVvau // CHECK: return public func getFixedLayoutGlobal() -> EmptyResilientStruct { return fixedLayoutGlobal }
apache-2.0
295a78d5d0d5175f221686822eae0dec
43.822917
200
0.752033
4.055608
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Login Management/LoginListSelectionHelper.swift
2
1472
// 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 /// Helper that keeps track of selected indexes for LoginListViewController public class LoginListSelectionHelper { private unowned let tableView: UITableView private(set) var selectedIndexPaths = [IndexPath]() var selectedCount: Int { return selectedIndexPaths.count } init(tableView: UITableView) { self.tableView = tableView } func selectIndexPath(_ indexPath: IndexPath) { selectedIndexPaths.append(indexPath) } func indexPathIsSelected(_ indexPath: IndexPath) -> Bool { return selectedIndexPaths.contains(indexPath) { path1, path2 in return path1.row == path2.row && path1.section == path2.section } } func deselectIndexPath(_ indexPath: IndexPath) { guard let foundSelectedPath = (selectedIndexPaths.filter { $0.row == indexPath.row && $0.section == indexPath.section }).first, let indexToRemove = selectedIndexPaths.firstIndex(of: foundSelectedPath) else { return } selectedIndexPaths.remove(at: indexToRemove) } func deselectAll() { selectedIndexPaths.removeAll() } func selectIndexPaths(_ indexPaths: [IndexPath]) { selectedIndexPaths += indexPaths } }
mpl-2.0
615553e470bb5de32519eae2fda07dba
31
135
0.677989
4.939597
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/TabContentsScripts/NightModeHelper.swift
2
2141
// 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 WebKit import Shared struct NightModePrefsKey { static let NightModeButtonIsInMenu = PrefsKeys.KeyNightModeButtonIsInMenu static let NightModeStatus = PrefsKeys.KeyNightModeStatus static let NightModeEnabledDarkTheme = PrefsKeys.KeyNightModeEnabledDarkTheme } class NightModeHelper: TabContentScript { fileprivate weak var tab: Tab? required init(tab: Tab) { self.tab = tab } static func name() -> String { return "NightMode" } func scriptMessageHandlerName() -> String? { return "NightMode" } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { // Do nothing. } static func toggle(_ prefs: Prefs, tabManager: TabManager) { let isActive = prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false setNightMode(prefs, tabManager: tabManager, enabled: !isActive) } static func setNightMode(_ prefs: Prefs, tabManager: TabManager, enabled: Bool) { prefs.setBool(enabled, forKey: NightModePrefsKey.NightModeStatus) for tab in tabManager.tabs { tab.nightMode = enabled tab.webView?.scrollView.indicatorStyle = enabled ? .white : .default } } static func setEnabledDarkTheme(_ prefs: Prefs, darkTheme enabled: Bool) { prefs.setBool(enabled, forKey: NightModePrefsKey.NightModeEnabledDarkTheme) } static func hasEnabledDarkTheme(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NightModePrefsKey.NightModeEnabledDarkTheme) ?? false } static func isActivated(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false } } class NightModeAccessors { static func isNightMode(_ prefs: Prefs) -> Bool { return prefs.boolForKey(NightModePrefsKey.NightModeStatus) ?? false } }
mpl-2.0
0db62944221785dbace48c0b0cdf2e4a
32.453125
132
0.706679
4.888128
false
false
false
false
paymentez/paymentez-ios
PaymentSDK/SkyFloatingLabelTextField.swift
1
19615
// Copyright 2016-2017 Skyscanner Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License // for the specific language governing permissions and limitations under the License. import UIKit /** A beautiful and flexible textfield implementation with support for title label, error message and placeholder. */ @IBDesignable open class SkyFloatingLabelTextField: UITextField { // swiftlint:disable:this type_body_length /** A Boolean value that determines if the language displayed is LTR. Default value set automatically from the application language settings. */ open var isLTRLanguage = UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { didSet { updateTextAligment() } } fileprivate func updateTextAligment() { if isLTRLanguage { textAlignment = .left titleLabel.textAlignment = .left } else { textAlignment = .right titleLabel.textAlignment = .right } } // MARK: Animation timing /// The value of the title appearing duration @objc dynamic open var titleFadeInDuration: TimeInterval = 0.2 /// The value of the title disappearing duration @objc dynamic open var titleFadeOutDuration: TimeInterval = 0.3 // MARK: Colors fileprivate var cachedTextColor: UIColor? /// A UIColor value that determines the text color of the editable text @IBInspectable override dynamic open var textColor: UIColor? { set { cachedTextColor = newValue updateControl(false) } get { return cachedTextColor } } /// A UIColor value that determines text color of the placeholder label @IBInspectable dynamic open var placeholderColor: UIColor = UIColor.lightGray { didSet { updatePlaceholder() } } /// A UIFont value that determines text color of the placeholder label @objc dynamic open var placeholderFont: UIFont? { didSet { updatePlaceholder() } } fileprivate func updatePlaceholder() { if let placeholder = placeholder, let font = placeholderFont ?? font { attributedPlaceholder = NSAttributedString( string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: placeholderColor, NSAttributedString.Key.font: font] ) } } /// A UIFont value that determines the text font of the title label @objc dynamic open var titleFont: UIFont = .systemFont(ofSize: 13) { didSet { updateTitleLabel() } } /// A UIColor value that determines the text color of the title label when in the normal state @IBInspectable dynamic open var titleColor: UIColor = .gray { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the bottom line when in the normal state @IBInspectable dynamic open var lineColor: UIColor = .lightGray { didSet { updateLineView() } } /// A UIColor value that determines the color used for the title label and line when the error message is not `nil` @IBInspectable dynamic open var errorColor: UIColor = .red { didSet { updateColors() } } /// A UIColor value that determines the text color of the title label when editing @IBInspectable dynamic open var selectedTitleColor: UIColor = .blue { didSet { updateTitleColor() } } /// A UIColor value that determines the color of the line in a selected state @IBInspectable dynamic open var selectedLineColor: UIColor = .black { didSet { updateLineView() } } // MARK: Line height /// A CGFloat value that determines the height for the bottom line when the control is in the normal state @IBInspectable dynamic open var lineHeight: CGFloat = 0.5 { didSet { updateLineView() setNeedsDisplay() } } /// A CGFloat value that determines the height for the bottom line when the control is in a selected state @IBInspectable dynamic open var selectedLineHeight: CGFloat = 1.0 { didSet { updateLineView() setNeedsDisplay() } } // MARK: View components /// The internal `UIView` to display the line below the text input. open var lineView: UIView! /// The internal `UILabel` that displays the selected, deselected title or error message based on the current state. open var titleLabel: UILabel! // MARK: Properties /** The formatter used before displaying content in the title label. This can be the `title`, `selectedTitle` or the `errorMessage`. The default implementation converts the text to uppercase. */ open var titleFormatter: ((String) -> String) = { (text: String) -> String in return text } /** Identifies whether the text object should hide the text being entered. */ override open var isSecureTextEntry: Bool { set { super.isSecureTextEntry = newValue fixCaretPosition() } get { return super.isSecureTextEntry } } /// A String value for the error message to display. open var errorMessage: String? { didSet { updateControl(true) } } /// The backing property for the highlighted property fileprivate var _highlighted = false /** A Boolean value that determines whether the receiver is highlighted. When changing this value, highlighting will be done with animation */ override open var isHighlighted: Bool { get { return _highlighted } set { _highlighted = newValue updateTitleColor() updateLineView() } } /// A Boolean value that determines whether the textfield is being edited or is selected. open var editingOrSelected: Bool { return super.isEditing || isSelected } /// A Boolean value that determines whether the receiver has an error message. open var hasErrorMessage: Bool { return errorMessage != nil && errorMessage != "" } fileprivate var _renderingInInterfaceBuilder: Bool = false /// The text content of the textfield @IBInspectable override open var text: String? { didSet { updateControl(false) } } /** The String to display when the input field is empty. The placeholder can also appear in the title label when both `title` `selectedTitle` and are `nil`. */ @IBInspectable override open var placeholder: String? { didSet { setNeedsDisplay() updatePlaceholder() updateTitleLabel() } } /// The String to display when the textfield is editing and the input is not empty. @IBInspectable open var selectedTitle: String? { didSet { updateControl() } } /// The String to display when the textfield is not editing and the input is not empty. @IBInspectable open var title: String? { didSet { updateControl() } } // Determines whether the field is selected. When selected, the title floats above the textbox. open override var isSelected: Bool { didSet { updateControl(true) } } // MARK: - Initializers /** Initializes the control - parameter frame the frame of the control */ override public init(frame: CGRect) { super.init(frame: frame) init_SkyFloatingLabelTextField() } /** Intialzies the control by deserializing it - parameter coder the object to deserialize the control from */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) init_SkyFloatingLabelTextField() } fileprivate final func init_SkyFloatingLabelTextField() { borderStyle = .none createTitleLabel() createLineView() updateColors() addEditingChangedObserver() updateTextAligment() } fileprivate func addEditingChangedObserver() { self.addTarget(self, action: #selector(SkyFloatingLabelTextField.editingChanged), for: .editingChanged) } /** Invoked when the editing state of the textfield changes. Override to respond to this change. */ @objc open func editingChanged() { updateControl(true) updateTitleLabel(true) } // MARK: create components fileprivate func createTitleLabel() { let titleLabel = UILabel() titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleLabel.font = titleFont titleLabel.alpha = 0.0 titleLabel.textColor = titleColor addSubview(titleLabel) self.titleLabel = titleLabel } fileprivate func createLineView() { if lineView == nil { let lineView = UIView() lineView.isUserInteractionEnabled = false self.lineView = lineView configureDefaultLineHeight() } lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin] addSubview(lineView) } fileprivate func configureDefaultLineHeight() { let onePixel: CGFloat = 1.0 / UIScreen.main.scale lineHeight = 2.0 * onePixel selectedLineHeight = 2.0 * self.lineHeight } // MARK: Responder handling /** Attempt the control to become the first responder - returns: True when successfull becoming the first responder */ @discardableResult override open func becomeFirstResponder() -> Bool { let result = super.becomeFirstResponder() updateControl(true) return result } /** Attempt the control to resign being the first responder - returns: True when successfull resigning being the first responder */ @discardableResult override open func resignFirstResponder() -> Bool { let result = super.resignFirstResponder() updateControl(true) return result } // MARK: - View updates fileprivate func updateControl(_ animated: Bool = false) { updateColors() updateLineView() updateTitleLabel(animated) } fileprivate func updateLineView() { if let lineView = lineView { lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected) } updateLineColor() } // MARK: - Color updates /// Update the colors for the control. Override to customize colors. open func updateColors() { updateLineColor() updateTitleColor() updateTextColor() } fileprivate func updateLineColor() { if hasErrorMessage { lineView.backgroundColor = errorColor } else { lineView.backgroundColor = editingOrSelected ? selectedLineColor : lineColor } } fileprivate func updateTitleColor() { if hasErrorMessage { titleLabel.textColor = errorColor } else { if editingOrSelected || isHighlighted { titleLabel.textColor = selectedTitleColor } else { titleLabel.textColor = titleColor } } } fileprivate func updateTextColor() { if hasErrorMessage { super.textColor = errorColor } else { super.textColor = cachedTextColor } } // MARK: - Title handling fileprivate func updateTitleLabel(_ animated: Bool = false) { var titleText: String? = nil if hasErrorMessage { titleText = titleFormatter(errorMessage!) } else { if editingOrSelected { titleText = selectedTitleOrTitlePlaceholder() if titleText == nil { titleText = titleOrPlaceholder() } } else { titleText = titleOrPlaceholder() } } titleLabel.text = titleText titleLabel.font = titleFont updateTitleVisibility(animated) } fileprivate var _titleVisible = false /* * Set this value to make the title visible */ open func setTitleVisible( _ titleVisible: Bool, animated: Bool = false, animationCompletion: ((_ completed: Bool) -> Void)? = nil ) { if _titleVisible == titleVisible { return } _titleVisible = titleVisible updateTitleColor() updateTitleVisibility(animated, completion: animationCompletion) } /** Returns whether the title is being displayed on the control. - returns: True if the title is displayed on the control, false otherwise. */ open func isTitleVisible() -> Bool { return hasText || hasErrorMessage || _titleVisible } fileprivate func updateTitleVisibility(_ animated: Bool = false, completion: ((_ completed: Bool) -> Void)? = nil) { let alpha: CGFloat = isTitleVisible() ? 1.0 : 0.0 let frame: CGRect = titleLabelRectForBounds(bounds, editing: isTitleVisible()) let updateBlock = { () -> Void in self.titleLabel.alpha = alpha self.titleLabel.frame = frame } if animated { let animationOptions: UIView.AnimationOptions = .curveEaseOut let duration = isTitleVisible() ? titleFadeInDuration : titleFadeOutDuration UIView.animate(withDuration: duration, delay: 0, options: animationOptions, animations: { () -> Void in updateBlock() }, completion: completion) } else { updateBlock() completion?(true) } } // MARK: - UITextField text/placeholder positioning overrides /** Calculate the rectangle for the textfield when it is not being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func textRect(forBounds bounds: CGRect) -> CGRect { let superRect = super.textRect(forBounds: bounds) let titleHeight = self.titleHeight() let rect = CGRect( x: superRect.origin.x, y: titleHeight, width: superRect.size.width, height: superRect.size.height - titleHeight - selectedLineHeight ) return rect } /** Calculate the rectangle for the textfield when it is being edited - parameter bounds: The current bounds of the field - returns: The rectangle that the textfield should render in */ override open func editingRect(forBounds bounds: CGRect) -> CGRect { let superRect = super.editingRect(forBounds: bounds) let titleHeight = self.titleHeight() let rect = CGRect( x: superRect.origin.x, y: titleHeight, width: superRect.size.width, height: superRect.size.height - titleHeight - selectedLineHeight ) return rect } /** Calculate the rectangle for the placeholder - parameter bounds: The current bounds of the placeholder - returns: The rectangle that the placeholder should render in */ override open func placeholderRect(forBounds bounds: CGRect) -> CGRect { let rect = CGRect( x: 0, y: titleHeight(), width: bounds.size.width, height: bounds.size.height - titleHeight() - selectedLineHeight ) return rect } // MARK: - Positioning Overrides /** Calculate the bounds for the title label. Override to create a custom size title field. - parameter bounds: The current bounds of the title - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the title label should render in */ open func titleLabelRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { if editing { return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight()) } return CGRect(x: 0, y: titleHeight(), width: bounds.size.width, height: titleHeight()) } /** Calculate the bounds for the bottom line of the control. Override to create a custom size bottom line in the textbox. - parameter bounds: The current bounds of the line - parameter editing: True if the control is selected or highlighted - returns: The rectangle that the line bar should render in */ open func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect { let height = editing ? selectedLineHeight : lineHeight return CGRect(x: 0, y: bounds.size.height - height, width: bounds.size.width, height: height) } /** Calculate the height of the title label. -returns: the calculated height of the title label. Override to size the title with a different height */ open func titleHeight() -> CGFloat { if let titleLabel = titleLabel, let font = titleLabel.font { return font.lineHeight } return 15.0 } /** Calcualte the height of the textfield. -returns: the calculated height of the textfield. Override to size the textfield with a different height */ open func textHeight() -> CGFloat { return self.font!.lineHeight + 7.0 } // MARK: - Layout /// Invoked when the interface builder renders the control override open func prepareForInterfaceBuilder() { if #available(iOS 8.0, *) { super.prepareForInterfaceBuilder() } borderStyle = .none isSelected = true _renderingInInterfaceBuilder = true updateControl(false) invalidateIntrinsicContentSize() } /// Invoked by layoutIfNeeded automatically override open func layoutSubviews() { super.layoutSubviews() titleLabel.frame = titleLabelRectForBounds(bounds, editing: isTitleVisible() || _renderingInInterfaceBuilder) lineView.frame = lineViewRectForBounds(bounds, editing: editingOrSelected || _renderingInInterfaceBuilder) } /** Calculate the content size for auto layout - returns: the content size to be used for auto layout */ override open var intrinsicContentSize: CGSize { return CGSize(width: bounds.size.width, height: titleHeight() + textHeight()) } // MARK: - Helpers fileprivate func titleOrPlaceholder() -> String? { guard let title = title ?? placeholder else { return nil } return titleFormatter(title) } fileprivate func selectedTitleOrTitlePlaceholder() -> String? { guard let title = selectedTitle ?? title ?? placeholder else { return nil } return titleFormatter(title) } } // swiftlint:disable:this file_length
mit
1cc2fb9bf384995dc31a68bf5fd07578
30.586151
125
0.628703
5.408051
false
false
false
false
biohazardlover/NintendoEverything
Pods/SwiftSoup/Sources/Attribute.swift
1
4267
// // Attribute.swift // SwifSoup // // Created by Nabil Chatbi on 29/09/16. // Copyright © 2016 Nabil Chatbi.. All rights reserved. // import Foundation open class Attribute { /// The element type of a dictionary: a tuple containing an individual /// key-value pair. static let booleanAttributes: [String] = [ "allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled", "formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize", "noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected", "sortable", "truespeed", "typemustmatch" ] var key: String var value: String public init(key: String, value: String) throws { try Validate.notEmpty(string: key) self.key = key.trim() self.value = value } /** Get the attribute key. @return the attribute key */ open func getKey() -> String { return key } /** Set the attribute key; case is preserved. @param key the new key; must not be null */ open func setKey(key: String) throws { try Validate.notEmpty(string: key) self.key = key.trim() } /** Get the attribute value. @return the attribute value */ open func getValue() -> String { return value } /** Set the attribute value. @param value the new attribute value; must not be null */ @discardableResult open func setValue(value: String) -> String { let old = self.value self.value = value return old } /** Get the HTML representation of this attribute; e.g. {@code href="index.html"}. @return HTML */ public func html() -> String { let accum = StringBuilder() html(accum: accum, out: (Document("")).outputSettings()) return accum.toString() } public func html(accum: StringBuilder, out: OutputSettings ) { accum.append(key) if (!shouldCollapseAttribute(out: out)) { accum.append("=\"") Entities.escape(accum, value, out, true, false, false) accum.append("\"") } } /** Get the string representation of this attribute, implemented as {@link #html()}. @return string */ open func toString() -> String { return html() } /** * Create a new Attribute from an unencoded key and a HTML attribute encoded value. * @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars. * @param encodedValue HTML attribute encoded value * @return attribute */ open static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute { let value = try Entities.unescape(string: encodedValue, strict: true) return try Attribute(key: unencodedKey, value: value) } public func isDataAttribute() -> Bool { return key.startsWith(Attributes.dataPrefix) && key.count > Attributes.dataPrefix.count } /** * Collapsible if it's a boolean attribute and value is empty or same as name * * @param out Outputsettings * @return Returns whether collapsible or not */ public final func shouldCollapseAttribute(out: OutputSettings) -> Bool { return ("" == value || value.equalsIgnoreCase(string: key)) && out.syntax() == OutputSettings.Syntax.html && isBooleanAttribute() } public func isBooleanAttribute() -> Bool { return Attribute.booleanAttributes.contains(key) } public func hashCode() -> Int { var result = key.hashValue result = 31 * result + value.hashValue return result } public func clone() -> Attribute { do { return try Attribute(key: key, value: value) } catch Exception.Error( _, let msg) { print(msg) } catch { } return try! Attribute(key: "", value: "") } } extension Attribute : Equatable { static public func == (lhs: Attribute, rhs: Attribute) -> Bool { return lhs.value == rhs.value && lhs.key == rhs.key } }
mit
f00026db41789bae02922f73f2126766
27.824324
113
0.600797
4.278837
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/PCAEncoder.swift
1
2929
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import TensorFlow import PenguinStructures /// A class that does PCA decomposition /// Input shape for training: [N, H, W, C] /// W matrix: [H, W, C, latent] /// Output: [H, W, C] public struct PCAEncoder { public typealias Patch = Tensor<Double> /// Basis public let U: Tensor<Double> /// Data mean public let mu: Tensor<Double> /// Size of latent public var d: Int { get { U.shape[1] } } /// Input dimension for one sample public var n: Int { get { U.shape[0] } } /// Train a PCAEncoder model /// images should be a Tensor of shape [N, H, W, C] /// default feature size is 10 /// Input: [N, H, W, C] public typealias HyperParameters = Int public init(from imageBatch: Tensor<Double>, given p: HyperParameters? = nil) { precondition(imageBatch.rank == 4, "Wrong image shape \(imageBatch.shape)") let (N_, H_, W_, C_) = (imageBatch.shape[0], imageBatch.shape[1], imageBatch.shape[2], imageBatch.shape[3]) let n = H_ * W_ * C_ let d = p ?? 10 let images_flattened = imageBatch.reshaped(to: [N_, n]) let mu = images_flattened.mean(squeezingAxes: 0) let images_flattened_without_mean = (images_flattened - mu).transposed() let (_, U, _) = images_flattened_without_mean.svd(computeUV: true, fullMatrices: false) self.init(withBasis: U![TensorRange.ellipsis, 0..<d], andMean: mu) } /// Initialize a PCAEncoder public init(withBasis U: Tensor<Double>, andMean mu: Tensor<Double>) { self.U = U self.mu = mu } /// Generate an image according to a latent /// Input: [H, W, C] /// Output: [d] @differentiable public func encode(_ image: Patch) -> Tensor<Double> { precondition(image.rank == 3 || (image.rank == 4), "wrong latent dimension \(image.shape)") let (N_) = (image.shape[0]) if image.rank == 4 { if N_ == 1 { return matmul(U, transposed: true, image.reshaped(to: [n, 1]) - mu.reshaped(to: [n, 1])).reshaped(to: [1, d]) } else { let v = image.reshaped(to: [N_, n]) - mu.reshaped(to: [1, n]) return matmul(v, U) } } else { let v = image.reshaped(to: [n, 1]) - mu.reshaped(to: [n, 1]) return matmul(U, transposed: true, v).reshaped(to: [d]) } } } extension PCAEncoder: AppearanceModelEncoder {}
apache-2.0
c9316e7ed0cf253dbc1460397c1792b5
31.186813
117
0.638102
3.503589
false
false
false
false
AlexLittlejohn/OMDBMovies
OMDBMovies/Models/MovieResult.swift
1
615
// // MovieResult.swift // OMDBMovies // // Created by Alex Littlejohn on 2016/04/04. // Copyright © 2016 Alex Littlejohn. All rights reserved. // import UIKit struct MovieResult { let title: String let year: String let poster: String let imdbID: String let type: String } extension MovieResult: JSONInitializable { init(JSON: JSONObject) { title = JSON["Title"] as? String ?? "" year = JSON["Year"] as? String ?? "" poster = JSON["Poster"] as? String ?? "" imdbID = JSON["imdbID"] as? String ?? "" type = JSON["Type"] as? String ?? "" } }
mit
a7fa54cb32d9a3a678faea26b3df66ee
21.777778
58
0.596091
3.721212
false
false
false
false
kstaring/swift
test/IRGen/closure.swift
4
3284
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // -- partial_apply context metadata // CHECK: [[METADATA:@.*]] = private constant %swift.full_boxmetadata { void (%swift.refcounted*)* @objectdestroy, i8** null, %swift.type { i64 64 }, i32 16, i8* bitcast (<{ i32, i32, i32, i32 }>* @"\01l__swift3_reflection_descriptor" to i8*) } func a(i i: Int) -> (Int) -> Int { return { x in i } } // -- Closure entry point // CHECK: define linkonce_odr hidden i64 @_TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, i64) protocol Ordinable { func ord() -> Int } func b<T : Ordinable>(seq seq: T) -> (Int) -> Int { return { i in i + seq.ord() } } // -- partial_apply stub // CHECK: define internal i64 @_TPA__TFF7closure1aFT1iSi_FSiSiU_FSiSi(i64, %swift.refcounted*) // CHECK: } // -- Closure entry point // CHECK: define linkonce_odr hidden i64 @[[CLOSURE2:_TFF7closure1buRxS_9OrdinablerFT3seqx_FSiSiU_FSiSi]](i64, %swift.refcounted*, %swift.type* %T, i8** %T.Ordinable) {{.*}} { // -- partial_apply stub // CHECK: define internal i64 @_TPA_[[CLOSURE2]](i64, %swift.refcounted*) {{.*}} { // CHECK: entry: // CHECK: [[CONTEXT:%.*]] = bitcast %swift.refcounted* %1 to <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* // CHECK: [[BINDINGSADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 1 // CHECK: [[TYPEADDR:%.*]] = bitcast [16 x i8]* [[BINDINGSADDR]] // CHECK: [[TYPE:%.*]] = load %swift.type*, %swift.type** [[TYPEADDR]], align 8 // CHECK: [[WITNESSADDR_0:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[TYPEADDR]], i32 1 // CHECK: [[WITNESSADDR:%.*]] = bitcast %swift.type** [[WITNESSADDR_0]] // CHECK: [[WITNESS:%.*]] = load i8**, i8*** [[WITNESSADDR]], align 8 // CHECK: [[BOXADDR:%.*]] = getelementptr inbounds <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>, <{ %swift.refcounted, [16 x i8], %swift.refcounted* }>* [[CONTEXT]], i32 0, i32 2 // CHECK: [[BOX:%.*]] = load %swift.refcounted*, %swift.refcounted** [[BOXADDR]], align 8 // CHECK: call void @swift_rt_swift_retain(%swift.refcounted* [[BOX]]) // CHECK: call void @swift_rt_swift_release(%swift.refcounted* %1) // CHECK: [[RES:%.*]] = tail call i64 @[[CLOSURE2]](i64 %0, %swift.refcounted* [[BOX]], %swift.type* [[TYPE]], i8** [[WITNESS]]) // CHECK: ret i64 [[RES]] // CHECK: } // -- <rdar://problem/14443343> Boxing of tuples with generic elements // CHECK: define hidden { i8*, %swift.refcounted* } @_TF7closure14captures_tupleu0_rFT1xTxq___FT_Txq__(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U) func captures_tuple<T, U>(x x: (T, U)) -> () -> (T, U) { // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_getTupleTypeMetadata2(%swift.type* %T, %swift.type* %U, i8* null, i8** null) // CHECK-NOT: @swift_getTupleTypeMetadata2 // CHECK: [[BOX:%.*]] = call { %swift.refcounted*, %swift.opaque* } @swift_allocBox(%swift.type* [[METADATA]]) // CHECK: [[ADDR:%.*]] = extractvalue { %swift.refcounted*, %swift.opaque* } [[BOX]], 1 // CHECK: bitcast %swift.opaque* [[ADDR]] to <{}>* return {x} }
apache-2.0
3d34eaa1daa406e5cd99f2c869b6e94c
55.62069
244
0.629111
3.121673
false
false
false
false
diegosanchezr/Chatto
ChattoAdditions/Source/Input/ChatInputBarAppearance.swift
1
1481
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public struct ChatInputBarAppearance { public var textFont = UIFont.systemFontOfSize(12) public var textColor = UIColor.blackColor() public var textPlaceholderFont = UIFont.systemFontOfSize(12) public var textPlaceholderColor = UIColor.grayColor() public var textPlaceholder = "" public var sendButtonTitle = "" public init() {} }
mit
101422b08dccf6abbc199d7e57e3038e
42.558824
78
0.774477
4.936667
false
false
false
false
natecook1000/swift
validation-test/Sema/type_checker_perf/slow/rdar22770433.swift
2
333
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts func test(n: Int) -> Int { return n == 0 ? 0 : (0..<n).reduce(0) { // expected-error@-1 {{reasonable time}} ($0 > 0 && $1 % 2 == 0) ? ((($0 + $1) - ($0 + $1)) / ($1 - $0)) + (($0 + $1) / ($1 - $0)) : $0 } }
apache-2.0
b76a708f1e4b005d8c18dc68c82b7574
36
98
0.495495
2.561538
false
true
false
false
ResearchSuite/ResearchSuiteAppFramework-iOS
Source/Core/Classes/RSAFCoreState.swift
1
2949
// // RSAFReduxState.swift // Pods // // Created by James Kizer on 3/22/17. // // import UIKit import ReSwift import ResearchKit import ResearchSuiteTaskBuilder import ResearchSuiteResultsProcessor public final class RSAFCoreState: RSAFBaseState { let loggedIn: Bool public typealias ActivityQueueElement = (UUID, RSAFActivityRun, RSTBTaskBuilder) let activityQueue: [ActivityQueueElement] // let resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)] let extensibleStorage: [String: NSObject] let taskBuilder: RSTBTaskBuilder? let resultsProcessor: RSRPResultsProcessor? let titleLabelText: String? let titleImage: UIImage? public init(loggedIn: Bool = false, activityQueue: [ActivityQueueElement] = [], resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)] = [], extensibleStorage: [String: NSObject] = [:], taskBuilder: RSTBTaskBuilder? = nil, resultsProcessor: RSRPResultsProcessor? = nil, titleLabelText: String? = nil, titleImage: UIImage? = nil ) { self.loggedIn = loggedIn self.activityQueue = activityQueue // self.resultsQueue = resultsQueue self.extensibleStorage = extensibleStorage self.taskBuilder = taskBuilder self.resultsProcessor = resultsProcessor self.titleLabelText = titleLabelText self.titleImage = titleImage super.init() } public required override convenience init() { self.init(loggedIn: false) } static func newState( fromState: RSAFCoreState, loggedIn: Bool? = nil, activityQueue: [ActivityQueueElement]? = nil, resultsQueue: [(UUID, RSAFActivityRun, ORKTaskResult)]? = nil, extensibleStorage: [String: NSObject]? = nil, taskBuilder: (RSTBTaskBuilder?)? = nil, resultsProcessor: (RSRPResultsProcessor?)? = nil, titleLabelText: (String?)? = nil, titleImage: (UIImage?)? = nil ) -> RSAFCoreState { return RSAFCoreState( loggedIn: loggedIn ?? fromState.loggedIn, activityQueue: activityQueue ?? fromState.activityQueue, // resultsQueue: resultsQueue ?? fromState.resultsQueue, extensibleStorage: extensibleStorage ?? fromState.extensibleStorage, taskBuilder: taskBuilder ?? fromState.taskBuilder, resultsProcessor: resultsProcessor ?? fromState.resultsProcessor, titleLabelText: titleLabelText ?? fromState.titleLabelText, titleImage: titleImage ?? fromState.titleImage ) } open override var description: String { return "\n\tloggedIn: \(self.loggedIn)" + "\n\tactivityQueue: \(self.activityQueue)" + // "\n\tresultsQueue: \(self.resultsQueue)"+ "\n\textensibleStorage: \(self.extensibleStorage)" } }
apache-2.0
e7359df0ac8caca458b0005d2c749d23
32.134831
84
0.646999
5.256684
false
false
false
false
wangjianquan/wjKeyBoard
wjKeyBoard/PhotoBrowersViewController.swift
1
2003
// // PhotoBrowersViewController.swift // CustomKeyboard // // Created by landixing on 2017/6/16. // Copyright © 2017年 WJQ. All rights reserved. // import UIKit class PhotoBrowersViewController: UIViewController { var imageView : UIImageView = { let imageview : UIImageView = UIImageView() imageview.contentMode = .scaleAspectFit imageview.clipsToBounds = true return imageview }() var image : UIImage? { didSet{ guard let image = image else { return } self.imageView.image = image } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidLoad() { super.viewDidLoad() setupUI() displayPhoto() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension PhotoBrowersViewController { fileprivate func setupUI() { navigationItem.leftBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(PhotoBrowersViewController.back)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "delete", style: .plain, target: self, action: #selector(PhotoBrowersViewController.deleteImage)) view.addSubview(imageView) imageView.frame = CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.height - 64) } fileprivate func displayPhoto() { } } extension PhotoBrowersViewController { @objc fileprivate func back() { } @objc fileprivate func deleteImage() { navigationController?.popViewController(animated: true) } }
apache-2.0
03b0d2999ff8ac0a5bfa5a7ad7517711
17.348624
164
0.5995
5.319149
false
false
false
false
artkirillov/DesignPatterns
Iterator.playground/Pages/2.xcplaygroundpage/Contents.swift
1
1500
final class Destination { let name: String init(name: String) { self.name = name } } final class DestinationList: Sequence { var destinations: [Destination] init(destinations: [Destination]) { self.destinations = destinations } func makeIterator() -> DestinationIterator { return DestinationIterator(destinationList: self) } } final class DestinationIterator: IteratorProtocol { private var current = 0 private let destinations: [Destination] init(destinationList: DestinationList) { self.destinations = destinationList.destinations } func next() -> Destination? { let next = current < destinations.count ? destinations[current] : nil current += 1 return next } } final class DestinationIterator2: IteratorProtocol { private var current: Int private let destinations: [Destination] init(destinationList: DestinationList) { self.destinations = destinationList.destinations self.current = destinations.count - 1 } func next() -> Destination? { let next = current >= 0 ? destinations[current] : nil current -= 1 return next } } let list = DestinationList(destinations: [ Destination(name: "Destination 1"), Destination(name: "Destination 2"), Destination(name: "Destination 3") ] ) for destination in list { print(destination.name) } list.forEach { print($0.name) }
mit
ad9a612a1b8de7ec4ea4198e23dd2435
22.809524
77
0.647333
4.672897
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/NewActivity/ActivityItemViewModel.swift
1
16355
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import Localization import PlatformKit import RxDataSources import ToolKit public final class ActivityItemViewModel: IdentifiableType, Hashable { typealias AccessibilityId = Accessibility.Identifier.Activity typealias LocalizationStrings = LocalizationConstants.Activity.MainScreen.Item public typealias Descriptors = AssetBalanceViewModel.Value.Presentation.Descriptors public var identity: AnyHashable { event } public var descriptors: Descriptors { let accessibility = AccessibilityId.ActivityCell.self switch event.status { case .pending: return .muted( cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix, fiatAccessiblitySuffix: accessibility.fiatValuePrefix ) case .complete: return .activity( cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix, fiatAccessiblitySuffix: accessibility.fiatValuePrefix ) case .product: return .activity( cryptoAccessiblitySuffix: accessibility.cryptoValuePrefix, fiatAccessiblitySuffix: accessibility.fiatValuePrefix ) } } public var titleLabelContent: LabelContent { var text = "" switch event { case .buySell(let orderDetails): switch (orderDetails.status, orderDetails.isBuy) { case (.pending, true): text = "\(LocalizationStrings.buying) \(orderDetails.outputValue.currency.displayCode)" case (_, true): text = "\(LocalizationStrings.buy) \(orderDetails.outputValue.currency.displayCode)" case (_, false): text = [ LocalizationStrings.sell, orderDetails.inputValue.currency.displayCode, "->", orderDetails.outputValue.currency.displayCode ].joined(separator: " ") } case .interest(let event): switch (event.type, event.state) { case (.withdraw, .complete): text = LocalizationStrings.withdraw + " \(event.cryptoCurrency.code)" case (.withdraw, .pending), (.withdraw, .processing), (.withdraw, .manualReview): text = LocalizationStrings.withdrawing + " \(event.cryptoCurrency.code)" case (.interestEarned, _): text = event.cryptoCurrency.code + " \(LocalizationStrings.rewardsEarned)" case (.transfer, _): text = LocalizationStrings.added + " \(event.cryptoCurrency.code)" default: unimplemented() } case .swap(let event): let pair = event.pair switch (event.status, pair.outputCurrencyType) { case (.complete, .crypto): text = LocalizationStrings.swap case (.complete, .fiat): text = LocalizationStrings.sell case (_, .crypto): text = LocalizationStrings.pendingSwap case (_, .fiat): text = LocalizationStrings.pendingSell } text += " \(pair.inputCurrencyType.displayCode) -> \(pair.outputCurrencyType.displayCode)" case .simpleTransactional(let event): switch (event.status, event.type) { case (.pending, .receive): text = LocalizationStrings.receiving + " \(event.currency.displayCode)" case (.pending, .send): text = LocalizationStrings.sending + " \(event.currency.displayCode)" case (.complete, .receive): text = LocalizationStrings.receive + " \(event.currency.displayCode)" case (.complete, .send): text = LocalizationStrings.send + " \(event.currency.displayCode)" } case .transactional(let event): switch (event.status, event.type) { case (.pending, .receive): text = LocalizationStrings.receiving + " \(event.currency.displayCode)" case (.pending, .send): text = LocalizationStrings.sending + " \(event.currency.displayCode)" case (.complete, .receive): text = LocalizationStrings.receive + " \(event.currency.displayCode)" case (.complete, .send): text = LocalizationStrings.send + " \(event.currency.displayCode)" } case .fiat(let event): switch (event.type, event.state) { case (.deposit, .completed): text = LocalizationStrings.deposit + " \(event.amount.displayCode)" case (.withdrawal, .completed): text = LocalizationStrings.withdraw + " \(event.amount.displayCode)" case (.deposit, _): text = LocalizationStrings.depositing + " \(event.amount.displayCode)" case (.withdrawal, _): text = LocalizationStrings.withdrawing + " \(event.amount.displayCode)" } case .crypto(let event): switch (event.state, event.type) { case (.pending, .deposit): text = LocalizationStrings.receiving + " \(event.amount.displayCode)" case (.pending, .withdrawal): text = LocalizationStrings.sending + " \(event.amount.displayCode)" case (_, .deposit): text = LocalizationStrings.receive + " \(event.amount.displayCode)" case (_, .withdrawal): text = LocalizationStrings.send + " \(event.amount.displayCode)" } } return .init( text: text, font: descriptors.primaryFont, color: descriptors.primaryTextColor, alignment: .left, adjustsFontSizeToFitWidth: .true(factor: 0.75), accessibility: .id(AccessibilityId.ActivityCell.titleLabel) ) } public var descriptionLabelContent: LabelContent { switch event.status { case .pending(confirmations: let confirmations): return .init( text: "\(confirmations.current) \(LocalizationStrings.of) \(confirmations.total)", font: descriptors.secondaryFont, color: descriptors.secondaryTextColor, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) case .complete: return .init( text: DateFormatter.medium.string(from: event.creationDate), font: descriptors.secondaryFont, color: descriptors.secondaryTextColor, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) case .product(let status): let failedLabelContent: LabelContent = .init( text: LocalizationStrings.failed, font: descriptors.secondaryFont, color: .destructive, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) switch status { case .custodial(let status): switch status { case .failed: return failedLabelContent case .completed, .pending: break } case .interest(let state): switch state { case .processing, .pending, .manualReview: return .init( text: LocalizationStrings.pending, font: descriptors.secondaryFont, color: descriptors.secondaryTextColor, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) case .failed, .rejected, .refunded: return failedLabelContent case .cleared, .complete, .unknown: return .init( text: DateFormatter.medium.string(from: event.creationDate), font: descriptors.secondaryFont, color: descriptors.secondaryTextColor, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) } case .buySell(let status): if status == .failed { return failedLabelContent } case .swap(let status): if status == .failed { return failedLabelContent } } return .init( text: DateFormatter.medium.string(from: event.creationDate), font: descriptors.secondaryFont, color: descriptors.secondaryTextColor, alignment: .left, accessibility: .id(AccessibilityId.ActivityCell.descriptionLabel) ) } } /// The color of the `EventType` image. public var eventColor: UIColor { switch event { case .buySell(let orderDetails): switch (orderDetails.status, orderDetails.isBuy) { case (.failed, _): return .destructive case (_, true): return orderDetails.outputValue.currency.brandUIColor case (_, false): return orderDetails.inputValue.currency.brandUIColor } case .swap(let event): if event.status == .failed { return .destructive } return event.pair.inputCurrencyType.brandUIColor case .interest(let interest): switch interest.state { case .pending, .processing, .manualReview: return .mutedText case .failed, .rejected: return .destructive case .refunded, .cleared, .unknown, .complete: return interest.cryptoCurrency.brandUIColor } case .fiat(let event): switch event.state { case .failed: return .destructive case .pending: return .mutedText case .completed: return event.amount.currency.brandColor } case .crypto(let event): switch event.state { case .failed: return .destructive case .pending: return .mutedText case .completed: return event.amount.currencyType.brandUIColor } case .simpleTransactional(let event): switch event.status { case .complete: return event.currency.brandUIColor case .pending: return .mutedText } case .transactional(let event): switch event.status { case .complete: return event.currency.brandUIColor case .pending: return .mutedText } } } /// The fill color of the `BadgeImageView` public var backgroundColor: UIColor { eventColor.withAlphaComponent(0.15) } /// The `imageResource` for the `BadgeImageViewModel` public var imageResource: ImageResource { switch event { case .interest(let interest): switch interest.state { case .pending, .processing, .manualReview: return .local(name: "clock-icon", bundle: .platformUIKit) case .failed, .rejected: return .local(name: "activity-failed-icon", bundle: .platformUIKit) case .complete: switch interest.type { case .transfer: return .local(name: "plus-icon", bundle: .platformUIKit) case .withdraw: return .local(name: "minus-icon", bundle: .platformUIKit) case .interestEarned: return .local(name: Icon.interest.name, bundle: .componentLibrary) case .unknown: // NOTE: `.unknown` is filtered out in // the `ActivityScreenInteractor` assertionFailure("Unexpected case for interest \(interest.state)") return .local(name: Icon.question.name, bundle: .componentLibrary) } case .cleared: return .local(name: "clock-icon", bundle: .platformUIKit) case .refunded, .unknown: assertionFailure("Unexpected case for interest \(interest.state)") return .local(name: Icon.question.name, bundle: .componentLibrary) } case .buySell(let value): if value.status == .failed { return .local(name: "activity-failed-icon", bundle: .platformUIKit) } let imageName = value.isBuy ? "plus-icon" : "minus-icon" return .local(name: imageName, bundle: .platformUIKit) case .fiat(let event): switch event.state { case .failed: return .local(name: "activity-failed-icon", bundle: .platformUIKit) case .pending: return .local(name: "clock-icon", bundle: .platformUIKit) case .completed: switch event.type { case .deposit: return .local(name: "deposit-icon", bundle: .platformUIKit) case .withdrawal: return .local(name: "withdraw-icon", bundle: .platformUIKit) } } case .crypto(let event): switch event.state { case .failed: return .local(name: "activity-failed-icon", bundle: .platformUIKit) case .pending: return .local(name: "clock-icon", bundle: .platformUIKit) case .completed: switch event.type { case .deposit: return .local(name: "receive-icon", bundle: .platformUIKit) case .withdrawal: return .local(name: "send-icon", bundle: .platformUIKit) } } case .swap(let event): if event.status == .failed { return .local(name: "activity-failed-icon", bundle: .platformUIKit) } return .local(name: "swap-icon", bundle: .platformUIKit) case .transactional(let event): switch (event.status, event.type) { case (.pending, _): return .local(name: "clock-icon", bundle: .platformUIKit) case (_, .send): return .local(name: "send-icon", bundle: .platformUIKit) case (_, .receive): return .local(name: "receive-icon", bundle: .platformUIKit) } case .simpleTransactional(let event): switch (event.status, event.type) { case (.pending, _): return .local(name: "clock-icon", bundle: .platformUIKit) case (_, .send): return .local(name: "send-icon", bundle: .platformUIKit) case (_, .receive): return .local(name: "receive-icon", bundle: .platformUIKit) } } } public let event: ActivityItemEvent public init(event: ActivityItemEvent) { self.event = event } public func hash(into hasher: inout Hasher) { hasher.combine(event) } } extension ActivityItemViewModel: Equatable { public static func == (lhs: ActivityItemViewModel, rhs: ActivityItemViewModel) -> Bool { lhs.event == rhs.event } }
lgpl-3.0
db707f4d75b1cdcd2434267cd8dc2e54
39.480198
103
0.533937
5.629604
false
false
false
false