repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
coolster01/PokerTouch
PokerTouch/ScoreViewController.swift
1
2756
// // ScoreViewController.swift // PokerTouch // // Created by Subhi Sbahi on 5/29/17. // Copyright © 2017 Rami Sbahi. All rights reserved. // import UIKit class ScoreViewController: UIViewController { @IBOutlet weak var Label1: UILabel! @IBOutlet weak var Score1: UILabel! @IBOutlet weak var Label2: UILabel! @IBOutlet weak var Score2: UILabel! @IBOutlet weak var Label3: UILabel! @IBOutlet weak var Score3: UILabel! @IBOutlet weak var Label4: UILabel! @IBOutlet weak var Score4: UILabel! @IBOutlet weak var Label5: UILabel! @IBOutlet weak var Score5: UILabel! @IBOutlet weak var Label6: UILabel! @IBOutlet weak var Score6: UILabel! @IBOutlet weak var Label7: UILabel! @IBOutlet weak var Score7: UILabel! @IBOutlet weak var Label8: UILabel! @IBOutlet weak var Score8: UILabel! @IBOutlet weak var Label9: UILabel! @IBOutlet weak var Score9: UILabel! @IBOutlet weak var BottomLabel: UILabel! @IBOutlet weak var YesButton: UIButton! @IBOutlet weak var NoButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(false) let labelArray = [Label1, Label2, Label3, Label4, Label5, Label6, Label7, Label8, Label9] let scoreArray = [Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8, Score9] let playerList = GameViewController.myRunner.sortedPlayers() for i in 0..<playerList.count { labelArray[i]?.text = String(i+1) + ". " + playerList[i].myName scoreArray[i]?.text = String(playerList[i].money) } GameViewController.myRunner.newRound() if(GameViewController.myRunner.myPlayers.count == 1) { BottomLabel.text = "Looks like \(GameViewController.myRunner.myPlayers[0].myName) won!" YesButton.isEnabled = false NoButton.setTitle("End Game", for: .normal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. GameViewController.myRunner.newRound() } }
apache-2.0
29ba9cfc822002fee7f255f8c686b278
28.308511
106
0.639201
4.379968
false
false
false
false
RxLeanCloud/rx-lean-swift
src/RxLeanCloudSwift/Public/RxAVSMS.swift
1
5072
// // AVValidationSMS.swift // RxLeanCloudSwift // // Created by WuJun on 14/12/2017. // Copyright © 2017 LeanCloud. All rights reserved. // import Foundation import RxSwift public class AVSMS { public var app: LeanCloudApp public var mobilePhoneNumber: String = "" public init(mobilePhoneNumber: String) { self.mobilePhoneNumber = mobilePhoneNumber self.app = RxAVClient.sharedInstance.takeApp(app: nil) } } public class AVUserLogInSMS: AVSMS { public func send() -> Observable<Bool> { var payload = [String: Any]() payload["mobilePhoneNumber"] = self.mobilePhoneNumber let cmd = AVCommand(relativeUrl: "/requestLoginSmsCode", method: "POST", data: payload, app: self.app) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in return avResponse.satusCode == 200 }) } public var shortCode: String? = nil public func setShortCode(receivedShortCode: String) { self.shortCode = receivedShortCode } } public class AVUserSignUpSMS: AVSMS { public func send() -> Observable<Bool> { var payload = [String: Any]() payload["mobilePhoneNumber"] = self.mobilePhoneNumber let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in return avResponse.satusCode == 200 }) } public var shortCode: String? = nil public func setShortCode(receivedShortCode: String) { self.shortCode = receivedShortCode } } public class AVValidationSMS: AVSMS { public static func send(mobilePhoneNumber: String, ttl: Int = 10) -> Observable<Bool> { return AVValidationSMS.send(mobilePhoneNumber: mobilePhoneNumber, appName: nil, operationName: nil) } public static func send(mobilePhoneNumber: String, appName: String?, operationName: String?, ttl: Int? = 10) -> Observable<Bool> { let sms = AVValidationSMS(mobilePhoneNumber: mobilePhoneNumber, appName: appName, operationName: operationName, ttl: ttl) return sms.send() } public var operationName: String? = nil public var ttl: Int = 10 public var appName: String? var shortCode: String? = nil public init(mobilePhoneNumber: String, appName: String?, operationName: String?, ttl: Int?) { self.operationName = operationName self.appName = appName if ttl != nil { self.ttl = ttl! } super.init(mobilePhoneNumber: mobilePhoneNumber) } public func send() -> Observable<Bool> { var payload = [String: Any]() payload["mobilePhoneNumber"] = self.mobilePhoneNumber if self.operationName != nil { payload["op"] = self.operationName } if self.appName != nil { payload["name"] = self.appName } if self.ttl != 10 { payload["ttl"] = self.ttl } let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in return avResponse.satusCode == 200 }) } public func setShortCode(receivedShortCode: String) { self.shortCode = receivedShortCode } public func verify() -> Observable<Bool> { if self.shortCode != nil { let cmd = AVCommand(relativeUrl: "/verifySmsCode/\(String(describing: self.shortCode))?mobilePhoneNumber=\(self.mobilePhoneNumber)", method: "POST", data: nil, app: self.app) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in return avResponse.satusCode == 200 }) } return Observable.from([false]) } } public class AVNoticeSMS: AVSMS { public init(mobilePhoneNumber: String, templateId: String, signatureId: String?, contentParameters: [String: Any]?) { self.templateId = templateId self.signatureId = signatureId self.contentParameters = contentParameters super.init(mobilePhoneNumber: mobilePhoneNumber) } public var templateId: String = "" public var signatureId: String? = nil public var contentParameters: [String: Any]? = nil public func send() -> Observable<Bool> { var payload = [String: Any]() payload["mobilePhoneNumber"] = self.mobilePhoneNumber payload["template"] = self.templateId if self.signatureId != nil { payload["sign"] = self.signatureId } if let env = contentParameters { env.forEach({ (key, value) in payload[key] = value }) } let cmd = AVCommand(relativeUrl: "/requestSmsCode", method: "POST", data: payload, app: self.app) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Bool in return avResponse.satusCode == 200 }) } }
mit
80dfa3c141961abe42e65ae49c1108bb
34.215278
186
0.638336
4.290186
false
false
false
false
renxlWin/gege
swiftChuge/Pods/RealmSwift/RealmSwift/Results.swift
33
18569
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: MinMaxType /** Types of properties which can be used with the minimum and maximum value APIs. - see: `min(ofProperty:)`, `max(ofProperty:)` */ public protocol MinMaxType {} extension NSNumber: MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension Date: MinMaxType {} extension NSDate: MinMaxType {} // MARK: AddableType /** Types of properties which can be used with the sum and average value APIs. - see: `sum(ofProperty:)`, `average(ofProperty:)` */ public protocol AddableType {} extension NSNumber: AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} /** `Results` is an auto-updating container type in Realm returned from object queries. `Results` can be queried with the same predicates as `List<T>`, and you can chain queries to further filter query results. `Results` always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. `Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any unnecessary work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results instances cannot be directly instantiated. */ public final class Results<T: Object>: NSObject, NSFastEnumeration { internal let rlmResults: RLMResults<RLMObject> /// A human-readable description of the objects represented by the results. public override var description: String { let type = "Results<\(rlmResults.objectClassName)>" return gsub(pattern: "RLMResults <0x[a-z0-9]+>", template: type, string: rlmResults.description) ?? type } // MARK: Fast Enumeration /// :nodoc: public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>!, count len: Int) -> Int { return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len))) } /// The type of the objects described by the results. public typealias Element = T // MARK: Properties /// The Realm which manages this results. Note that this property will never return `nil`. public var realm: Realm? { return Realm(rlmResults.realm) } /** Indicates if the results are no longer valid. The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be accessed, but will always be empty. */ public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of objects in the results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal init(_ rlmResults: RLMResults<RLMObject>) { self.rlmResults = rlmResults } // MARK: Index Retrieval /** Returns the index of the given object in the results, or `nil` if the object is not present. */ public func index(of object: T) -> Int? { return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> T { throwForNegativeIndex(position) return unsafeBitCast(rlmResults.object(at: UInt(position)), to: T.self) } /// Returns the first object in the results, or `nil` if the results are empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<T>.self) } /// Returns the last object in the results, or `nil` if the results are empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<T>.self) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results. - parameter key: The name of the property whose values are desired. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<T> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(byKeyPath: property, ascending: ascending) } /** Returns a `Results` containing the objects represented by the results, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the results. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the results, or `nil` if the results are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension Results: RealmCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the results. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension Results: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results { return Results(objectiveCValue as! RLMResults) } var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: rlmResults, metadata: nil) } } // MARK: Unavailable extension Results { @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } }
mit
446ca1d019719c7abadd2617841e3d47
39.632385
120
0.684851
4.828133
false
false
false
false
almas-dev/APMWheelControl
Pod/Classes/APMWheelSector.swift
1
2615
// // Created by Xander on 24.02.16. // import UIKit class APMWheelSector: UIView { var color: UIColor? var label: String? { didSet { sectorLabel.text = label } } let numberOfSegments: CGFloat = 5 let lRadius: CGFloat let sRadius: CGFloat = 0 var arc = UIBezierPath() private let sectorLabel = UILabel() required init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } init(radius: CGFloat) { self.lRadius = radius func degreesToRadians(degrees: CGFloat) -> CGFloat { return CGFloat(M_PI * Double(degrees) / 180) } let sAngle = 270 - ((360 / numberOfSegments) / 2) let eAngle = 270 + ((360 / numberOfSegments) / 2) let startAngle = degreesToRadians(sAngle) let endAngle = degreesToRadians(eAngle) let lArc: UIBezierPath = UIBezierPath(arcCenter: CGPointMake(lRadius, lRadius), radius: lRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) let sArc: UIBezierPath = UIBezierPath(arcCenter: CGPointMake(lRadius, lRadius), radius: sRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) var frame = CGRect() if (eAngle - sAngle) <= 180 { frame = CGRectMake(0, 0, lArc.bounds.width, sArc.currentPoint.y) } if (eAngle - sAngle) > 269 { frame = CGRectMake(0, 0, lArc.bounds.width, lArc.bounds.height) } super.init(frame: frame) backgroundColor = UIColor.clearColor() sectorLabel.frame = CGRectMake(0, 0, frame.width, frame.height - 10) sectorLabel.textColor = UIColor.cyanColor() sectorLabel.textAlignment = .Center sectorLabel.transform = CGAffineTransformMakeRotation(degreesToRadians(90)) addSubview(sectorLabel) } override func drawRect(rect: CGRect) { super.drawRect(rect) color?.setStroke() color?.setFill() let startAngle = degreesToRadians((270 - ((360 / numberOfSegments) / 2))) let endAngle = degreesToRadians((270 + ((360 / numberOfSegments) / 2))) let center = CGPointMake(CGRectGetMidX(rect), lRadius) arc = UIBezierPath(arcCenter: center, radius: lRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) arc.addArcWithCenter(center, radius: sRadius, startAngle: endAngle, endAngle: startAngle, clockwise: false) arc.closePath() arc.fill() } func degreesToRadians(degrees: CGFloat) -> CGFloat { return CGFloat(M_PI * Double(degrees) / 180) } }
mit
6eee6744ea86c5ec1ef5518211d1e532
33.407895
165
0.638241
4.308072
false
false
false
false
jindulys/GitPocket
_site/GitPocket/Utilities/PullToRefresh/UIScrollView+PullToRefresh.swift
1
1445
// // UIScrollView+PullToRefresh.swift // GitPocket // // Created by yansong li on 2015-07-30. // Copyright © 2015 yansong li. All rights reserved. // import Foundation import UIKit import ObjectiveC var associatedObjectHandle: UInt8 = 0 extension UIScrollView { var pullToRefresh: PullToRefresh? { get { return objc_getAssociatedObject(self, &associatedObjectHandle) as? PullToRefresh } set { objc_setAssociatedObject(self, &associatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func addPullToRefresh(pullToRefresh: PullToRefresh, action:()->()) { if self.pullToRefresh != nil { self.removePullToRefresh(self.pullToRefresh!) } self.pullToRefresh = pullToRefresh pullToRefresh.scrollView = self pullToRefresh.action = action let view = pullToRefresh.refreshView view.frame = CGRectMake(0, -view.frame.size.height, self.frame.size.width, view.frame.size.height) self.addSubview(view) self.sendSubviewToBack(view) } func removePullToRefresh(pullToRefresh: PullToRefresh) { self.pullToRefresh?.refreshView.removeFromSuperview() self.pullToRefresh = nil } func startRefreshing() { pullToRefresh?.startRefreshing() } func endRefresing() { pullToRefresh?.endRefreshing() } }
mit
ce99ce52d05d2dc489dc5423312ee1a5
27.333333
113
0.65374
5.013889
false
false
false
false
wrg-mujeeb/WRGCodeBase
WRGCodeBase/Classes/Extension/WRGColorExtension.swift
1
988
// // WRGColorExtension.swift // FBSnapshotTestCase // // Created by Mujeeb R. O on 12/10/17. // import UIKit public extension UIColor { /// Initialize using hex code /// /// - Parameters: /// - hex: hex color code /// - alpha: alpha public convenience init(hex: String, alpha: Float = 1.0){ let purifiedHex = hex.replacingOccurrences(of: "#", with: "") let scanner = Scanner(string:purifiedHex) var color:UInt32 = 0; scanner.scanHexInt32(&color) let mask = 0x000000FF let r = CGFloat(Float(Int(color >> 16) & mask)/255.0) let g = CGFloat(Float(Int(color >> 8) & mask)/255.0) let b = CGFloat(Float(Int(color) & mask)/255.0) self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha)) } /// Initialize using hex code /// /// - Parameter hex: hex color code public convenience init(hex: String){ self.init(hex: hex, alpha: 1.0) } }
mit
6d11d54dc06ac57ddc107d4a4521adef
25.702703
69
0.572874
3.553957
false
false
false
false
KieranHarper/KJHUIKit
Sources/LabelButton.swift
1
2516
// // LabelButton.swift // KJHUIKit // // Created by Kieran Harper on 2/7/17. // Copyright © 2017 Kieran Harper. All rights reserved. // import UIKit /// Simple label only button @objc open class LabelButton: Button { // MARK: - Properties /** The label that is centered inside the button. Alignment is centered by default. */ @objc public let label = CrossfadingLabel() /** The horizontal offset of the label from a X-centered position. Positive numbers move it to the right, negative to the left. */ @objc public var offsetFromCenterX: CGFloat = 0.0 { didSet { self.invalidateIntrinsicContentSize() self.setNeedsLayout() } } /** The vertical offset of the label from a Y-centered position. Positive numbers move it down, negative moves up. */ @objc public var offsetFromCenterY: CGFloat = 0.0 { didSet { self.invalidateIntrinsicContentSize() self.setNeedsLayout() } } // MARK: - Lifecycle @objc public override init(frame: CGRect) { super.init(frame: frame) self.setupLabelButton() } @objc public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupLabelButton() } @objc public convenience init() { self.init(frame: CGRect.zero) } private func setupLabelButton() { label.textAlignment = .center addSubview(label) helperSetLabelFrame() } @objc open override func layoutSubviews() { super.layoutSubviews() helperSetLabelFrame() } private func helperSetLabelFrame() { let size = label.intrinsicContentSize let width = min(size.width, self.bounds.width) let height = min(size.height, self.bounds.height) let newFrame = self.bounds.resizedTo(width: width, height: height) label.frame = newFrame.offsetBy(dx: offsetFromCenterX, dy: offsetFromCenterY) } @objc open override var intrinsicContentSize: CGSize { let intrinsicSize = label.intrinsicContentSize let widthAccountingForOffset = intrinsicSize.width + 2.0 * abs(offsetFromCenterX) let heightAccountingForOffset = intrinsicSize.height + 2.0 * abs(offsetFromCenterY) return CGSize(width: widthAccountingForOffset, height: heightAccountingForOffset) } }
mit
a259ff92020061173d75b49242f0d159
26.336957
91
0.623857
4.657407
false
false
false
false
evolutional/flatbuffers
swift/Sources/FlatBuffers/Table.swift
1
8268
/* * Copyright 2021 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation /// `Table` is a Flatbuffers object that can read, /// mutate scalar fields within a valid flatbuffers buffer @frozen public struct Table { /// Hosting Bytebuffer public private(set) var bb: ByteBuffer /// Current position of the table within the buffer public private(set) var postion: Int32 /// Initializer for the table interface to allow generated code to read /// data from memory /// - Parameters: /// - bb: ByteBuffer that stores data /// - position: Current table position /// - Note: This will `CRASH` if read on a big endian machine public init(bb: ByteBuffer, position: Int32 = 0) { guard isLitteEndian else { fatalError("Reading/Writing a buffer in big endian machine is not supported on swift") } self.bb = bb postion = position } /// Gets the offset of the current field within the buffer by reading /// the vtable /// - Parameter o: current offset /// - Returns: offset of field within buffer public func offset(_ o: Int32) -> Int32 { let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( def: Int16.self, position: Int(vtable + o))) : 0 } /// Gets the indirect offset of the current stored object /// (applicable only for object arrays) /// - Parameter o: current offset /// - Returns: offset of field within buffer public func indirect(_ o: Int32) -> Int32 { o + bb.read(def: Int32.self, position: Int(o)) } /// String reads from the buffer with respect to position of the current table. /// - Parameter offset: Offset of the string public func string(at offset: Int32) -> String? { directString(at: offset + postion) } /// Direct string reads from the buffer disregarding the position of the table. /// It would be preferable to use string unless the current position of the table /// is not needed /// - Parameter offset: Offset of the string public func directString(at offset: Int32) -> String? { var offset = offset offset += bb.read(def: Int32.self, position: Int(offset)) let count = bb.read(def: Int32.self, position: Int(offset)) let position = Int(offset) + MemoryLayout<Int32>.size return bb.readString(at: position, count: Int(count)) } /// Reads from the buffer with respect to the position in the table. /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func readBuffer<T>(of type: T.Type, at o: Int32) -> T { directRead(of: T.self, offset: o + postion) } /// Reads from the buffer disregarding the position of the table. /// It would be used when reading from an /// ``` /// let offset = __t.offset(10) /// //Only used when the we already know what is the /// // position in the table since __t.vector(at:) /// // returns the index with respect to the position /// __t.directRead(of: Byte.self, /// offset: __t.vector(at: offset) + index * 1) /// ``` /// - Parameters: /// - type: Type of Element that needs to be read from the buffer /// - o: Offset of the Element public func directRead<T>(of type: T.Type, offset o: Int32) -> T { let r = bb.read(def: T.self, position: Int(o)) return r } /// Returns that current `Union` object at a specific offset /// by adding offset to the current position of table /// - Parameter o: offset /// - Returns: A flatbuffers object public func union<T: FlatbuffersInitializable>(_ o: Int32) -> T { let o = o + postion return directUnion(o) } /// Returns a direct `Union` object at a specific offset /// - Parameter o: offset /// - Returns: A flatbuffers object public func directUnion<T: FlatbuffersInitializable>(_ o: Int32) -> T { T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) } /// Returns a vector of type T at a specific offset /// This should only be used by `Scalars` /// - Parameter off: Readable offset /// - Returns: Returns a vector of type [T] public func getVector<T>(at off: Int32) -> [T]? { let o = offset(off) guard o != 0 else { return nil } return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o))) } /// Vector count gets the count of Elements within the array /// - Parameter o: start offset of the vector /// - returns: Count of elements public func vector(count o: Int32) -> Int32 { var o = o o += postion o += bb.read(def: Int32.self, position: Int(o)) return bb.read(def: Int32.self, position: Int(o)) } /// Vector start index in the buffer /// - Parameter o:start offset of the vector /// - returns: the start index of the vector public func vector(at o: Int32) -> Int32 { var o = o o += postion return o + bb.read(def: Int32.self, position: Int(o)) + 4 } /// Reading an indirect offset of a table. /// - Parameters: /// - o: position within the buffer /// - fbb: ByteBuffer /// - Returns: table offset static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read(def: Int32.self, position: Int(o)) } /// Gets a vtable value according to an table Offset and a field offset /// - Parameters: /// - o: offset relative to entire buffer /// - vOffset: Field offset within a vtable /// - fbb: ByteBuffer /// - Returns: an position of a field static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 { let vTable = Int32(fbb.capacity) - o return vTable + Int32(fbb.read( def: Int16.self, position: Int(vTable + vOffset - fbb.read( def: Int32.self, position: Int(vTable))))) } /// Compares two objects at offset A and offset B within a ByteBuffer /// - Parameters: /// - off1: first offset to compare /// - off2: second offset to compare /// - fbb: Bytebuffer /// - Returns: returns the difference between static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = fbb.read(def: Int32.self, position: Int(_off2)) let startPos1 = _off1 + memorySize let startPos2 = _off2 + memorySize let minValue = min(len1, len2) for i in 0...minValue { let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) if b1 != b2 { return Int32(b2 - b1) } } return len1 - len2 } /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer /// - Parameters: /// - off1: Offset to compare to /// - key: bytes array to compare to /// - fbb: Bytebuffer /// - Returns: returns the difference between static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 { let memorySize = Int32(MemoryLayout<Int32>.size) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len2 = Int32(key.count) let startPos1 = _off1 + memorySize let minValue = min(len1, len2) for i in 0..<minValue { let b = fbb.read(def: Int8.self, position: Int(i + startPos1)) let byte = key[Int(i)] if b != byte { return Int32(b - Int8(byte)) } } return len1 - len2 } }
apache-2.0
1d0f47acceb57d8e3d1c53cabab95770
36.243243
92
0.646347
3.651943
false
false
false
false
mohsinalimat/ExpandingTableView
ExpandingTest/ExpandingExample/MainViewController.swift
4
2896
// // MainViewController.swift // ExpandingExample // // Created by Vesza Jozsef on 03/06/15. // Copyright (c) 2015 József Vesza. All rights reserved. // import UIKit import ExpandingTableView import ViewModelExtensions let detailSegueIdentifier = "showDetailSegue" let statusbarHeight: CGFloat = 20 class MainViewController: ExpandingTableViewController { let toDetailViewController = ToDetailViewPresentationController() let backToMainViewController = BackToMainViewPresentationController() var viewModel: TableViewModel! var buttonRect: CGRect? // MARK: - Lifecycle methods override func viewDidLoad() { super.viewDidLoad() tableView.contentInset.top = statusbarHeight tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 125 tableView.tableFooterView = UIView(frame: CGRectZero) } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) as! ExampleCell cell.mainTitle = viewModel.titleForRow(indexPath.row) cell.indexPath = indexPath cell.detailButtonActionHandler = { [unowned self] button, index in if let destination = DetailViewController.instanceWithViewModel(DetailViewModel(photoStore: self.viewModel.photoStore, selectedIndex: index.row)) { let newRect = cell.convertRect(button.frame, toView: nil) self.buttonRect = newRect destination.transitioningDelegate = self self.presentViewController(destination, animated: true, completion: nil) } } return cell } } extension MainViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return toDetailViewController } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return backToMainViewController } } extension MainViewController: ViewControllerInitializable { static func instanceWithViewModel(viewModel: TableViewModel) -> MainViewController? { if let instance = self.instance() as? MainViewController { instance.viewModel = viewModel return instance } return nil } }
mit
2ac1e923045a88df157285ede0078fa2
33.47619
217
0.697755
6.225806
false
false
false
false
Antidote-for-Tox/Antidote
Antidote/FriendListCell.swift
1
4101
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit class FriendListCell: BaseCell { struct Constants { static let AvatarSize = 30.0 static let AvatarLeftOffset = 10.0 static let AvatarRightOffset = 16.0 static let TopLabelHeight = 22.0 static let MinimumBottomLabelHeight = 15.0 static let VerticalOffset = 3.0 } fileprivate var avatarView: ImageViewWithStatus! fileprivate var topLabel: UILabel! fileprivate var bottomLabel: UILabel! fileprivate var arrowImageView: UIImageView! override func setupWithTheme(_ theme: Theme, model: BaseCellModel) { super.setupWithTheme(theme, model: model) guard let friendModel = model as? FriendListCellModel else { assert(false, "Wrong model \(model) passed to cell \(self)") return } separatorInset.left = CGFloat(Constants.AvatarLeftOffset + Constants.AvatarSize + Constants.AvatarRightOffset) avatarView.imageView.image = friendModel.avatar avatarView.userStatusView.theme = theme avatarView.userStatusView.userStatus = friendModel.status avatarView.userStatusView.isHidden = friendModel.hideStatus topLabel.text = friendModel.topText topLabel.textColor = theme.colorForType(.NormalText) bottomLabel.text = friendModel.bottomText bottomLabel.textColor = theme.colorForType(.FriendCellStatus) bottomLabel.numberOfLines = friendModel.multilineBottomtext ? 0 : 1 accessibilityLabel = friendModel.accessibilityLabel accessibilityValue = friendModel.accessibilityValue } override func createViews() { super.createViews() avatarView = ImageViewWithStatus() contentView.addSubview(avatarView) topLabel = UILabel() topLabel.font = UIFont.systemFont(ofSize: 18.0) contentView.addSubview(topLabel) bottomLabel = UILabel() bottomLabel.font = UIFont.antidoteFontWithSize(12.0, weight: .light) contentView.addSubview(bottomLabel) let image = UIImage(named: "right-arrow")!.flippedToCorrectLayout() arrowImageView = UIImageView(image: image) arrowImageView.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal) contentView.addSubview(arrowImageView) } override func installConstraints() { super.installConstraints() avatarView.snp.makeConstraints { $0.leading.equalTo(contentView).offset(Constants.AvatarLeftOffset) $0.centerY.equalTo(contentView) $0.size.equalTo(Constants.AvatarSize) } topLabel.snp.makeConstraints { $0.leading.equalTo(avatarView.snp.trailing).offset(Constants.AvatarRightOffset) $0.top.equalTo(contentView).offset(Constants.VerticalOffset) $0.height.equalTo(Constants.TopLabelHeight) } bottomLabel.snp.makeConstraints { $0.leading.trailing.equalTo(topLabel) $0.top.equalTo(topLabel.snp.bottom) $0.bottom.equalTo(contentView).offset(-Constants.VerticalOffset) $0.height.greaterThanOrEqualTo(Constants.MinimumBottomLabelHeight) } arrowImageView.snp.makeConstraints { $0.centerY.equalTo(contentView) $0.leading.greaterThanOrEqualTo(topLabel.snp.trailing) $0.trailing.equalTo(contentView) } } } // Accessibility extension FriendListCell { override var isAccessibilityElement: Bool { get { return true } set {} } // Label and value are set in setupWithTheme:model: method // var accessibilityLabel: String? // var accessibilityValue: String? override var accessibilityTraits: UIAccessibilityTraits { get { return UIAccessibilityTraitButton } set {} } }
mpl-2.0
b5afce381b9f1d2c57001940aa287dc0
33.175
118
0.677396
5.113466
false
false
false
false
natmark/ProcessingKit
ProcessingKitTests/ShapeTests.swift
1
14734
// // ShapeTests.swift // ProcessingKitTests // // Created by AtsuyaSato on 2018/01/29. // Copyright © 2018年 Atsuya Sato. All rights reserved. // import XCTest @testable import ProcessingKit struct TestCase { let description: String let shape: Shape let expect: CGPath? } enum Shape { case point(x: CGFloat, y: CGFloat) case line(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) case rect(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) case roundedRect(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, topLeftRadius: CGFloat, topRightRadius: CGFloat, bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat) case ellipse(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) case arc(x: CGFloat, y: CGFloat, radius: CGFloat, start: CGFloat, stop: CGFloat) case triangle(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat, x3: CGFloat, y3: CGFloat) case quad(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat, x3: CGFloat, y3: CGFloat, x4: CGFloat, y4: CGFloat) case curve(cpx1: CGFloat, cpy1: CGFloat, x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat, cpx2: CGFloat, cpy2: CGFloat) case bezier(x1: CGFloat, y1: CGFloat, cpx1: CGFloat, cpy1: CGFloat, cpx2: CGFloat, cpy2: CGFloat, x2: CGFloat, y2: CGFloat) } class ProcessingViewDelegateShapeSpy: ProcessingViewDelegate { private let exception: XCTestExpectation private let view: ProcessingView private let shape: Shape private(set) var context: CGContext? init(exception: XCTestExpectation, view: ProcessingView, shape: Shape) { self.exception = exception self.view = view self.shape = shape } func setup() { switch shape { case .point(let x, let y): self.view.point(x, y) case .line(let x1, let y1, let x2, let y2): self.view.line(x1, y1, x2, y2) case .rect(let x, let y, let width, let height): self.view.rect(x, y, width, height) case .roundedRect(let x, let y, let width, let height, let topLeftRadius, let topRightRadius, let bottomLeftRadius, let bottomRightRadius): self.view.rect(x, y, width, height, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius) case .ellipse(let x, let y, let width, let height): self.view.ellipse(x, y, width, height) case .arc(let x, let y, let radius, let start, let stop): self.view.arc(x, y, radius, start, stop) case .triangle(let x1, let y1, let x2, let y2, let x3, let y3): self.view.triangle(x1, y1, x2, y2, x3, y3) case .quad(let x1, let y1, let x2, let y2, let x3, let y3, let x4, let y4): self.view.quad(x1, y1, x2, y2, x3, y3, x4, y4) case .curve(let cpx1, let cpy1, let x1, let y1, let x2, let y2, let cpx2, let cpy2): self.view.curve(cpx1, cpy1, x1, y1, x2, y2, cpx2, cpy2) case .bezier(let x1, let y1, let cpx1, let cpy1, let cpx2, let cpy2, let x2, let y2): self.view.bezier(x1, y1, cpx1, cpy1, cpx2, cpy2, x2, y2) } self.record(UIGraphicsGetCurrentContext()) exception.fulfill() } private func record(_ arg: CGContext?) { self.context = arg } } class ShapeTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testPoint() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw point(50, 50)", shape: .point(x: 50, y: 50), expect: UIBezierPath(ovalIn: CGRect(x: 49.5, y: 49.5, width: 1, height: 1)).cgPath ), ] check(testCases: testCases) } func testLine() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw line(0, 0, 100, 100)", shape: .line(x1: 0, y1: 0, x2: 100, y2: 100), expect: UIBezierPath() .moveTo(CGPoint(x: 0, y: 0)) .addLineTo(CGPoint(x: 100, y: 100)) .cgPath ), #line: TestCase( description: "draw line(50, 50, -50, -50)", shape: .line(x1: 50, y1: 50, x2: -50, y2: -50), expect: UIBezierPath() .moveTo(CGPoint(x: 50, y: 50)) .addLineTo(CGPoint(x: -50, y: -50)) .cgPath ), ] check(testCases: testCases) } func testRect() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw rect(0, 0, 50, 50)", shape: .rect(x: 0, y: 0, width: 50, height: 50), expect: UIBezierPath(rect: CGRect(x: 0, y: 0, width: 50, height: 50)).cgPath ), #line: TestCase( description: "draw rect(20, 20, 30, 50)", shape: .rect(x: 20, y: 20, width: 30, height: 50), expect: UIBezierPath(rect: CGRect(x: 20, y: 20, width: 30, height: 50)).cgPath ), #line: TestCase( description: "draw rounded rect(10, 10, 50, 50, 10, 0, 0, 0)", shape: .roundedRect(x: 10, y: 10, width: 50, height: 50, topLeftRadius: 5, topRightRadius: 0, bottomLeftRadius: 0, bottomRightRadius: 0), expect: roundedRectPathBuilder(x: 10, y: 10, width: 50, height: 50, topLeftRadius: 5, topRightRadius: 0, bottomLeftRadius: 0, bottomRightRadius: 0) ), #line: TestCase( description: "draw rounded rect(10, 10, 50, 50, 50, 10, 10, 10)", shape: .roundedRect(x: 10, y: 10, width: 50, height: 50, topLeftRadius: 50, topRightRadius: 10, bottomLeftRadius: 10, bottomRightRadius: 10), expect: roundedRectPathBuilder(x: 10, y: 10, width: 50, height: 50, topLeftRadius: 25, topRightRadius: 10, bottomLeftRadius: 10, bottomRightRadius: 10) ), ] check(testCases: testCases) } func testElipse() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw ellipse(100, 100, 100, 100)", shape: .ellipse(x: 100, y: 100, width: 100, height: 100), expect: UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100)).cgPath ), #line: TestCase( description: "draw ellipse(0, 0, 100, 100)", shape: .ellipse(x: 0, y: 0, width: 100, height: 100), expect: UIBezierPath(ovalIn: CGRect(x: -50, y: -50, width: 100, height: 100)).cgPath ), ] check(testCases: testCases) } func testArc() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw arc(50, 50, 50, 0°, 90°)", shape: .arc(x: 50, y: 50, radius: 50, start: radians(0), stop: radians(90.0)), expect: arcPathBuilder(x: 50, y: 50, radius: 50, start: radians(0), stop: radians(90.0), clockwise: false) ), #line: TestCase( description: "draw arc(50, 50, 30, 30°, 120°)", shape: .arc(x: 50, y: 50, radius: 30, start: radians(30.0), stop: radians(120.0)), expect: arcPathBuilder(x: 50, y: 50, radius: 30, start: radians(30.0), stop: radians(120.0), clockwise: false) ), ] check(testCases: testCases) } func testTriangle() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw triangle(50, 0, 0, 100, 100, 100)", shape: .triangle(x1: 50, y1: 0, x2: 0, y2: 100, x3: 100, y3: 100), expect: UIBezierPath() .moveTo(CGPoint(x: 50, y: 0)) .addLineTo(CGPoint(x: 0, y: 100)) .addLineTo(CGPoint(x: 100, y: 100)) .closePath() .cgPath ), ] check(testCases: testCases) } func testQuad() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw triangle(0, 0, 30, 0, 100, 100, 40, 50)", shape: .quad(x1: 0, y1: 0, x2: 30, y2: 0, x3: 100, y3: 100, x4: 40, y4: 50), expect: UIBezierPath() .moveTo(CGPoint(x: 0, y: 0)) .addLineTo(CGPoint(x: 30, y: 0)) .addLineTo(CGPoint(x: 100, y: 100)) .addLineTo(CGPoint(x: 40, y: 50)) .closePath() .cgPath ), ] check(testCases: testCases) } func testCurve() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw curve(40, 40, 80, 60, 100, 100, 60, 120)", shape: .curve(cpx1: 40, cpy1: 40, x1: 80, y1: 60, x2: 100, y2: 100, cpx2: 60, cpy2: 120), expect: curvePathBuilder(cpx1: 40, cpy1: 40, x1: 80, y1: 60, x2: 100, y2: 100, cpx2: 60, cpy2: 120) ), ] check(testCases: testCases) } func testBezier() { let testCases: [UInt: TestCase] = [ #line: TestCase( description: "draw bezier(40, 40, 80, 60, 100, 100, 60, 120)", shape: .bezier(x1: 40, y1: 40, cpx1: 80, cpy1: 60, cpx2: 100, cpy2: 100, x2: 60, y2: 120), expect: bezierPathBuilder(x1: 40, y1: 40, cpx1: 80, cpy1: 60, cpx2: 100, cpy2: 100, x2: 60, y2: 120) ), ] check(testCases: testCases) } func check(testCases: [UInt: TestCase]) { _ = testCases.map { (line, testCase) in let view = ProcessingView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) let transformDelegateSpy = ProcessingViewDelegateShapeSpy( exception: expectation(description: testCase.description), view: view, shape: testCase.shape ) view.delegate = transformDelegateSpy waitForExpectations(timeout: 100) let actual = transformDelegateSpy.context?.path let expected = testCase.expect XCTAssertEqual(actual, expected, String(line)) } } private func radians(_ degrees: CGFloat) -> CGFloat { let radian = (CGFloat.pi * 2) * (degrees / 360.0) return radian } private func roundedRectPathBuilder(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, topLeftRadius: CGFloat, topRightRadius: CGFloat, bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat) -> CGPath? { let context = CGContext(data: nil, width: 100, height: 100, bitsPerComponent: 8, bytesPerRow: 1664, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: 8194)! context.beginPath() context.move(to: CGPoint(x: x + topLeftRadius, y: y)) context.addLine(to: CGPoint(x: x + width - topRightRadius, y: y)) context.addArc(center: CGPoint(x: x + width - topRightRadius, y: y + topRightRadius), radius: topRightRadius, startAngle: radians(-90.0), endAngle: radians(0.0), clockwise: false) context.addLine(to: CGPoint(x: x + width, y: y + height - bottomRightRadius)) context.addArc(center: CGPoint(x: x + width - bottomRightRadius, y: y + height - bottomRightRadius), radius: bottomRightRadius, startAngle: radians(0.0), endAngle: radians(90.0), clockwise: false) context.addLine(to: CGPoint(x: x + bottomLeftRadius, y: y + height)) context.addArc(center: CGPoint(x: x + bottomLeftRadius, y: y + height - bottomLeftRadius), radius: bottomLeftRadius, startAngle: radians(90.0), endAngle: radians(180.0), clockwise: false) context.addLine(to: CGPoint(x: x, y: y + topLeftRadius)) context.addArc(center: CGPoint(x: x + topLeftRadius, y: y + topLeftRadius), radius: topLeftRadius, startAngle: radians(180.0), endAngle: radians(270.0), clockwise: false) context.closePath() return context.path } private func arcPathBuilder(x: CGFloat, y: CGFloat, radius: CGFloat, start: CGFloat, stop: CGFloat, clockwise: Bool) -> CGPath? { let context = CGContext(data: nil, width: 100, height: 100, bitsPerComponent: 8, bytesPerRow: 1664, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: 8194)! context.addArc(center: CGPoint(x: x, y: y), radius: radius, startAngle: start, endAngle: stop, clockwise: clockwise) return context.path } private func curvePathBuilder(cpx1: CGFloat, cpy1: CGFloat, x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat, cpx2: CGFloat, cpy2: CGFloat) -> CGPath? { let context = CGContext(data: nil, width: 100, height: 100, bitsPerComponent: 8, bytesPerRow: 1664, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: 8194)! let (b1, b2) = ShapeModel.convertCurvePoint(cpx1, cpy1, x1, y1, x2, y2, cpx2, cpy2) context.move(to: CGPoint(x: x1, y: y1)) context.addCurve(to: CGPoint(x: x2, y: y2), control1: CGPoint(x: b1.x, y: b1.y), control2: CGPoint(x: b2.x, y: b2.y)) return context.path } private func bezierPathBuilder(x1: CGFloat, y1: CGFloat, cpx1: CGFloat, cpy1: CGFloat, cpx2: CGFloat, cpy2: CGFloat, x2: CGFloat, y2: CGFloat) -> CGPath? { let context = CGContext(data: nil, width: 100, height: 100, bitsPerComponent: 8, bytesPerRow: 1664, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: 8194)! context.move(to: CGPoint(x: x1, y: y1)) context.addCurve(to: CGPoint(x: x2, y: y2), control1: CGPoint(x: cpx1, y: cpy1), control2: CGPoint(x: cpx2, y: cpy2)) return context.path } } extension UIBezierPath { open func moveTo(_ point: CGPoint) -> UIBezierPath { self.move(to: point) return self } open func addLineTo(_ point: CGPoint) -> UIBezierPath { self.addLine(to: point) return self } open func addArcTo(_ center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> UIBezierPath { self.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) return self } open func addCurveTo(_ points: (to: CGPoint, controlPoint1: CGPoint, controlPoint2: CGPoint)) -> UIBezierPath { self.addCurve(to: points.to, controlPoint1: points.controlPoint1, controlPoint2: points.controlPoint2) return self } open func closePath() -> UIBezierPath { self.close() return self } }
mit
00eb2f90d555da7058cb7c06ab927ff6
43.225225
213
0.576967
3.668909
false
true
false
false
bizz84/SwiftyStoreKit
SwiftyStoreKit-iOS-Demo/ViewController.swift
1
15761
// // ViewController.swift // SwiftyStoreKit // // Created by Andrea Bizzotto on 03/09/2015. // // 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 StoreKit import SwiftyStoreKit enum RegisteredPurchase: String { case purchase1 case purchase2 case nonConsumablePurchase case consumablePurchase case nonRenewingPurchase case autoRenewableWeekly case autoRenewableMonthly case autoRenewableYearly } class ViewController: UIViewController { let appBundleId = "com.musevisions.iOS.SwiftyStoreKit" #if os(iOS) // UISwitch is unavailable on tvOS @IBOutlet var nonConsumableAtomicSwitch: UISwitch! @IBOutlet var consumableAtomicSwitch: UISwitch! @IBOutlet var nonRenewingAtomicSwitch: UISwitch! @IBOutlet var autoRenewableAtomicSwitch: UISwitch! var nonConsumableIsAtomic: Bool { return nonConsumableAtomicSwitch.isOn } var consumableIsAtomic: Bool { return consumableAtomicSwitch.isOn } var nonRenewingIsAtomic: Bool { return nonRenewingAtomicSwitch.isOn } var autoRenewableIsAtomic: Bool { return autoRenewableAtomicSwitch.isOn } #else let nonConsumableIsAtomic = true let consumableIsAtomic = true let nonRenewingIsAtomic = true let autoRenewableIsAtomic = true #endif // MARK: non consumable @IBAction func nonConsumableGetInfo() { getInfo(.nonConsumablePurchase) } @IBAction func nonConsumablePurchase() { purchase(.nonConsumablePurchase, atomically: nonConsumableIsAtomic) } @IBAction func nonConsumableVerifyPurchase() { verifyPurchase(.nonConsumablePurchase) } // MARK: consumable @IBAction func consumableGetInfo() { getInfo(.consumablePurchase) } @IBAction func consumablePurchase() { purchase(.consumablePurchase, atomically: consumableIsAtomic) } @IBAction func consumableVerifyPurchase() { verifyPurchase(.consumablePurchase) } // MARK: non renewing @IBAction func nonRenewingGetInfo() { getInfo(.nonRenewingPurchase) } @IBAction func nonRenewingPurchase() { purchase(.nonRenewingPurchase, atomically: nonRenewingIsAtomic) } @IBAction func nonRenewingVerifyPurchase() { verifyPurchase(.nonRenewingPurchase) } // MARK: auto renewable #if os(iOS) @IBOutlet var autoRenewableSubscriptionSegmentedControl: UISegmentedControl! var autoRenewableSubscription: RegisteredPurchase { switch autoRenewableSubscriptionSegmentedControl.selectedSegmentIndex { case 0: return .autoRenewableWeekly case 1: return .autoRenewableMonthly case 2: return .autoRenewableYearly default: return .autoRenewableWeekly } } #else let autoRenewableSubscription = RegisteredPurchase.autoRenewableWeekly #endif @IBAction func autoRenewableGetInfo() { getInfo(autoRenewableSubscription) } @IBAction func autoRenewablePurchase() { purchase(autoRenewableSubscription, atomically: autoRenewableIsAtomic) } @IBAction func autoRenewableVerifyPurchase() { verifySubscriptions([.autoRenewableWeekly, .autoRenewableMonthly, .autoRenewableYearly]) } func getInfo(_ purchase: RegisteredPurchase) { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in NetworkActivityIndicatorManager.networkOperationFinished() self.showAlert(self.alertForProductRetrievalInfo(result)) } } func purchase(_ purchase: RegisteredPurchase, atomically: Bool) { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: atomically) { result in NetworkActivityIndicatorManager.networkOperationFinished() if case .success(let purchase) = result { let downloads = purchase.transaction.downloads if !downloads.isEmpty { SwiftyStoreKit.start(downloads) } // Deliver content from server, then: if purchase.needsFinishTransaction { SwiftyStoreKit.finishTransaction(purchase.transaction) } } if let alert = self.alertForPurchaseResult(result) { self.showAlert(alert) } } } @IBAction func restorePurchases() { NetworkActivityIndicatorManager.networkOperationStarted() SwiftyStoreKit.restorePurchases(atomically: true) { results in NetworkActivityIndicatorManager.networkOperationFinished() for purchase in results.restoredPurchases { let downloads = purchase.transaction.downloads if !downloads.isEmpty { SwiftyStoreKit.start(downloads) } else if purchase.needsFinishTransaction { // Deliver content from server, then: SwiftyStoreKit.finishTransaction(purchase.transaction) } } self.showAlert(self.alertForRestorePurchases(results)) } } @IBAction func verifyReceipt() { NetworkActivityIndicatorManager.networkOperationStarted() verifyReceipt { result in NetworkActivityIndicatorManager.networkOperationFinished() self.showAlert(self.alertForVerifyReceipt(result)) } } func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) { let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret") SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: completion) } func verifyPurchase(_ purchase: RegisteredPurchase) { NetworkActivityIndicatorManager.networkOperationStarted() verifyReceipt { result in NetworkActivityIndicatorManager.networkOperationFinished() switch result { case .success(let receipt): let productId = self.appBundleId + "." + purchase.rawValue switch purchase { case .autoRenewableWeekly, .autoRenewableMonthly, .autoRenewableYearly: let purchaseResult = SwiftyStoreKit.verifySubscription( ofType: .autoRenewable, productId: productId, inReceipt: receipt) self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: [productId])) case .nonRenewingPurchase: let purchaseResult = SwiftyStoreKit.verifySubscription( ofType: .nonRenewing(validDuration: 60), productId: productId, inReceipt: receipt) self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: [productId])) default: let purchaseResult = SwiftyStoreKit.verifyPurchase( productId: productId, inReceipt: receipt) self.showAlert(self.alertForVerifyPurchase(purchaseResult, productId: productId)) } case .error: self.showAlert(self.alertForVerifyReceipt(result)) } } } func verifySubscriptions(_ purchases: Set<RegisteredPurchase>) { NetworkActivityIndicatorManager.networkOperationStarted() verifyReceipt { result in NetworkActivityIndicatorManager.networkOperationFinished() switch result { case .success(let receipt): let productIds = Set(purchases.map { self.appBundleId + "." + $0.rawValue }) let purchaseResult = SwiftyStoreKit.verifySubscriptions(productIds: productIds, inReceipt: receipt) self.showAlert(self.alertForVerifySubscriptions(purchaseResult, productIds: productIds)) case .error: self.showAlert(self.alertForVerifyReceipt(result)) } } } #if os(iOS) override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } #endif } // MARK: User facing alerts extension ViewController { func alertWithTitle(_ title: String, message: String) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) return alert } func showAlert(_ alert: UIAlertController) { guard self.presentedViewController != nil else { self.present(alert, animated: true, completion: nil) return } } func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController { if let product = result.retrievedProducts.first { let priceString = product.localizedPrice! return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)") } else if let invalidProductId = result.invalidProductIDs.first { return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)") } else { let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support" return alertWithTitle("Could not retrieve product info", message: errorString) } } // swiftlint:disable cyclomatic_complexity func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? { switch result { case .success(let purchase): print("Purchase Success: \(purchase.productId)") return nil case .error(let error): print("Purchase Failed: \(error)") switch error.code { case .unknown: return alertWithTitle("Purchase failed", message: error.localizedDescription) case .clientInvalid: // client is not allowed to issue the request, etc. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment") case .paymentCancelled: // user cancelled the request, etc. return nil case .paymentInvalid: // purchase identifier was invalid, etc. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid") case .paymentNotAllowed: // this device is not allowed to make the payment return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment") case .storeProductNotAvailable: // Product is not available in the current storefront return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront") case .cloudServicePermissionDenied: // user has not allowed access to cloud service information return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed") case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework return alertWithTitle("Purchase failed", message: "Could not connect to the network") case .cloudServiceRevoked: // user has revoked permission to use this cloud service return alertWithTitle("Purchase failed", message: "Cloud service was revoked") default: return alertWithTitle("Purchase failed", message: (error as NSError).localizedDescription) } } } func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController { if results.restoreFailedPurchases.count > 0 { print("Restore Failed: \(results.restoreFailedPurchases)") return alertWithTitle("Restore failed", message: "Unknown error. Please contact support") } else if results.restoredPurchases.count > 0 { print("Restore Success: \(results.restoredPurchases)") return alertWithTitle("Purchases Restored", message: "All purchases have been restored") } else { print("Nothing to Restore") return alertWithTitle("Nothing to restore", message: "No previous purchases were found") } } func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController { switch result { case .success(let receipt): print("Verify receipt Success: \(receipt)") return alertWithTitle("Receipt verified", message: "Receipt verified remotely") case .error(let error): print("Verify receipt Failed: \(error)") switch error { case .noReceiptData: return alertWithTitle("Receipt verification", message: "No receipt data. Try again.") case .networkError(let error): return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)") default: return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)") } } } func alertForVerifySubscriptions(_ result: VerifySubscriptionResult, productIds: Set<String>) -> UIAlertController { switch result { case .purchased(let expiryDate, let items): print("\(productIds) is valid until \(expiryDate)\n\(items)\n") return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)") case .expired(let expiryDate, let items): print("\(productIds) is expired since \(expiryDate)\n\(items)\n") return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)") case .notPurchased: print("\(productIds) has never been purchased") return alertWithTitle("Not purchased", message: "This product has never been purchased") } } func alertForVerifyPurchase(_ result: VerifyPurchaseResult, productId: String) -> UIAlertController { switch result { case .purchased: print("\(productId) is purchased") return alertWithTitle("Product is purchased", message: "Product will not expire") case .notPurchased: print("\(productId) has never been purchased") return alertWithTitle("Not purchased", message: "This product has never been purchased") } } }
mit
110ed4f24f75ac880fe1dbdeb37e8c68
41.945504
128
0.664806
5.414291
false
false
false
false
stripysock/SwiftGen
Pods/Stencil/Stencil/Node.swift
1
6818
import Foundation public struct TemplateSyntaxError : ErrorType, Equatable, CustomStringConvertible { public let description:String public init(_ description:String) { self.description = description } } public func ==(lhs:TemplateSyntaxError, rhs:TemplateSyntaxError) -> Bool { return lhs.description == rhs.description } public protocol NodeType { /// Render the node in the given context func render(context:Context) throws -> String } /// Render the collection of nodes in the given context public func renderNodes(nodes:[NodeType], _ context:Context) throws -> String { return try nodes.map { try $0.render(context) }.joinWithSeparator("") } public class SimpleNode : NodeType { let handler:Context throws -> String public init(handler:Context throws -> String) { self.handler = handler } public func render(context: Context) throws -> String { return try handler(context) } } public class TextNode : NodeType { public let text:String public init(text:String) { self.text = text } public func render(context:Context) throws -> String { return self.text } } public protocol Resolvable { func resolve(context: Context) throws -> Any? } public class VariableNode : NodeType { public let variable: Resolvable public init(variable: Resolvable) { self.variable = variable } public init(variable: String) { self.variable = Variable(variable) } public func render(context: Context) throws -> String { let result = try variable.resolve(context) if let result = result as? String { return result } else if let result = result as? CustomStringConvertible { return result.description } else if let result = result as? NSObject { return result.description } return "" } } public class NowNode : NodeType { public let format:Variable public class func parse(parser:TokenParser, token:Token) throws -> NodeType { var format:Variable? let components = token.components() guard components.count <= 2 else { throw TemplateSyntaxError("'now' tags may only have one argument: the format string `\(token.contents)`.") } if components.count == 2 { format = Variable(components[1]) } return NowNode(format:format) } public init(format:Variable?) { self.format = format ?? Variable("\"yyyy-MM-dd 'at' HH:mm\"") } public func render(context: Context) throws -> String { let date = NSDate() let format = try self.format.resolve(context) var formatter:NSDateFormatter? if let format = format as? NSDateFormatter { formatter = format } else if let format = format as? String { formatter = NSDateFormatter() formatter!.dateFormat = format } else { return "" } return formatter!.stringFromDate(date) } } public class ForNode : NodeType { let variable:Variable let loopVariable:String let nodes:[NodeType] let emptyNodes: [NodeType] public class func parse(parser:TokenParser, token:Token) throws -> NodeType { let components = token.components() guard components.count == 4 && components[2] == "in" else { throw TemplateSyntaxError("'for' statements should use the following 'for x in y' `\(token.contents)`.") } let loopVariable = components[1] let variable = components[3] var emptyNodes = [NodeType]() let forNodes = try parser.parse(until(["endfor", "empty"])) guard let token = parser.nextToken() else { throw TemplateSyntaxError("`endfor` was not found.") } if token.contents == "empty" { emptyNodes = try parser.parse(until(["endfor"])) parser.nextToken() } return ForNode(variable: variable, loopVariable: loopVariable, nodes: forNodes, emptyNodes:emptyNodes) } public init(variable:String, loopVariable:String, nodes:[NodeType], emptyNodes:[NodeType]) { self.variable = Variable(variable) self.loopVariable = loopVariable self.nodes = nodes self.emptyNodes = emptyNodes } public func render(context: Context) throws -> String { let values = try variable.resolve(context) if let values = values as? NSArray where values.count > 0 { return try values.map { item in try context.push([loopVariable: item]) { try renderNodes(nodes, context) } }.joinWithSeparator("") } return try context.push { try renderNodes(emptyNodes, context) } } } public class IfNode : NodeType { public let variable:Variable public let trueNodes:[NodeType] public let falseNodes:[NodeType] public class func parse(parser:TokenParser, token:Token) throws -> NodeType { let components = token.components() guard components.count == 2 else { throw TemplateSyntaxError("'if' statements should use the following 'if condition' `\(token.contents)`.") } let variable = components[1] var trueNodes = [NodeType]() var falseNodes = [NodeType]() trueNodes = try parser.parse(until(["endif", "else"])) guard let token = parser.nextToken() else { throw TemplateSyntaxError("`endif` was not found.") } if token.contents == "else" { falseNodes = try parser.parse(until(["endif"])) parser.nextToken() } return IfNode(variable: variable, trueNodes: trueNodes, falseNodes: falseNodes) } public class func parse_ifnot(parser:TokenParser, token:Token) throws -> NodeType { let components = token.components() guard components.count == 2 else { throw TemplateSyntaxError("'ifnot' statements should use the following 'if condition' `\(token.contents)`.") } let variable = components[1] var trueNodes = [NodeType]() var falseNodes = [NodeType]() falseNodes = try parser.parse(until(["endif", "else"])) guard let token = parser.nextToken() else { throw TemplateSyntaxError("`endif` was not found.") } if token.contents == "else" { trueNodes = try parser.parse(until(["endif"])) parser.nextToken() } return IfNode(variable: variable, trueNodes: trueNodes, falseNodes: falseNodes) } public init(variable:String, trueNodes:[NodeType], falseNodes:[NodeType]) { self.variable = Variable(variable) self.trueNodes = trueNodes self.falseNodes = falseNodes } public func render(context: Context) throws -> String { let result = try variable.resolve(context) var truthy = false if let result = result as? NSArray { if result.count > 0 { truthy = true } } else if result != nil { truthy = true } context.push() let output:String if truthy { output = try renderNodes(trueNodes, context) } else { output = try renderNodes(falseNodes, context) } context.pop() return output } }
mit
6e5f694bea10656bb00a7425022f60a5
25.84252
114
0.670871
4.28805
false
false
false
false
davepatterson/SwiftValidator
SwiftValidator/Core/Validator.swift
1
10970
// // Validator.swift // // Created by Jeff Potter on 11/10/14. // Copyright (c) 2015 jpotts18. All rights reserved. // import Foundation import UIKit /** Class that makes `Validator` objects. Should be added as a parameter to ViewController that will display validation fields. */ public class Validator { /// Dictionary to hold all fields (and accompanying rules) that will undergo validation. public var validations = [UITextField:ValidationRule]() /// Dictionary to hold fields (and accompanying errors) that were unsuccessfully validated. public var errors = [UITextField:ValidationError]() /// Variable that holds success closure to display positive status of field. public var delegate: ValidationDelegate? private var successStyleTransform:((validationRule:ValidationRule)->Void)? /// Variable that holds error closure to display negative status of field. private var errorStyleTransform:((validationError:ValidationError)->Void)? /// - returns: An initialized object, or nil if an object could not be created for some reason that would not result in an exception. private var completedValidationsCount: Int = 0 public init(){} // MARK: Private functions /** This method is used to validate all fields registered to Validator. If validation is unsuccessful, field gets added to errors dictionary. - returns: No return value. */ private func validateAllFields() { errors = [:] for (textField, rule) in validations { if let error = rule.validateField() { errors[textField] = error // let the user transform the field if they want if let transform = self.errorStyleTransform { transform(validationError: error) } } else { // No error // let the user transform the field if they want if let transform = self.successStyleTransform { transform(validationRule: rule) } } } } /** This method is used to validate all fields registered to Validator. If validation is unsuccessful, field gets added to errors dictionary. Completion closure is used to validator know when all fields have undergone validation attempt. - parameter completion: Bool that is set to true when all fields have experienced validation attempt. - returns: No return value. */ private func validateAllFields(completion: (finished: Bool) -> Void) { errors = [:] for (textField, rule) in validations { if rule.remoteInfo != nil { validateRemoteField(textField, callback: { error -> Void in self.completedValidationsCount = self.completedValidationsCount + 1 if self.completedValidationsCount == self.validations.count { // Sends validation back to validate() completion(finished: true) } }) } else { validateRegularField(textField) self.completedValidationsCount = self.completedValidationsCount + 1 if completedValidationsCount == validations.count { // Sends validation back to validate() completion(finished: true) } } } } /** This method is used to validate a field that will need to also be validated via remote request. - parameter textField: TextField of field that is being validated. - parameter completion: Closure that holds the status of textField's validation. Is set to true after remote validation has ended, regardless of whether the validation was a success or failure. - returns: No return value. */ public func validateRemoteField(textField: UITextField, callback: (error: ValidationError?) -> Void) { if let fieldRule = validations[textField] { // Carry on with validation only if regular validation passed if self.validateRegularField(fieldRule.textField) { delegate!.remoteValidationRequest?(textField.text!, urlString: fieldRule.remoteInfo!.urlString, completion: { result -> Void in if result { if let transform = self.successStyleTransform { transform(validationRule: fieldRule) } callback(error: nil) } else { // Stop validation because remote validation failed // Validation Failed on remote call let error = ValidationError(textField: fieldRule.textField, errorLabel: fieldRule.errorLabel, error: fieldRule.remoteInfo!.error) self.errors[fieldRule.textField] = error if let transform = self.errorStyleTransform { transform(validationError: error) } callback(error: error) } }) } } } /** Method used to validate a regular field (non-remote). - parameter: TextField of field that is undergoing validation - returns: A Bool that represents whether the validation was a success or failure, returns true for the former and false for the latter. */ private func validateRegularField(textField: UITextField) -> Bool { if let fieldRule = validations[textField] { if let error = fieldRule.validateField() { errors[textField] = error if let transform = self.errorStyleTransform { transform(validationError: error) } return false } else { if let transform = self.successStyleTransform { if fieldRule.remoteInfo == nil { transform(validationRule: fieldRule) } } return true } } return false } // MARK: Public functions /** This method is used to validate a single field registered to Validator. If validation is unsuccessful, field gets added to errors dictionary. - parameter textField: Holds validator field data. - returns: No return value. */ public func validateField(textField: UITextField, callback: (error:ValidationError?) -> Void){ if let fieldRule = validations[textField] { if let error = fieldRule.validateField() { errors[textField] = error if let transform = self.errorStyleTransform { transform(validationError: error) } callback(error: error) } else { if let transform = self.successStyleTransform { transform(validationRule: fieldRule) } callback(error: nil) } } else { callback(error: nil) } } // MARK: Using Keys /** This method is used to style fields that have undergone validation checks. Success callback should be used to show common success styling and error callback should be used to show common error styling. - parameter success: A closure which is called with validationRule, an object that holds validation data - parameter error: A closure which is called with validationError, an object that holds validation error data - returns: No return value */ public func styleTransformers(success success:((validationRule:ValidationRule)->Void)?, error:((validationError:ValidationError)->Void)?) { self.successStyleTransform = success self.errorStyleTransform = error } /** This method is used to add a field to validator. - parameter textField: field that is to be validated. - parameter Rule: An array which holds different rules to validate against textField. - returns: No return value */ public func registerField(textField:UITextField, rules:[Rule], remoteInfo: (String, String)? = nil) { validations[textField] = ValidationRule(textField: textField, rules: rules, errorLabel: nil, remoteInfo: remoteInfo) } /** This method is used to add a field to validator. - parameter textfield: field that is to be validated. - parameter errorLabel: A UILabel that holds error label data - parameter rules: A Rule array that holds different rules that apply to said textField. - returns: No return value */ public func registerField(textField:UITextField, errorLabel:UILabel, rules:[Rule], remoteInfo: (String, String)? = nil) { validations[textField] = ValidationRule(textField: textField, rules:rules, errorLabel:errorLabel, remoteInfo: remoteInfo) } /** This method is for removing a field validator. - parameter textField: field used to locate and remove textField from validator. - returns: No return value */ public func unregisterField(textField:UITextField) { validations.removeValueForKey(textField) errors.removeValueForKey(textField) } /** This method checks to see if all fields in validator are valid. - returns: No return value. */ public func validate(delegate:ValidationDelegate) { self.validateAllFields() if errors.isEmpty { delegate.validationSuccessful() } else { delegate.validationFailed(errors) } } /** This method attempts to validate all fields registered to Validator(). - returns: No return value. */ public func validate() { self.validateAllFields { finished -> Void in if self.errors.isEmpty { // call success method if it's implemented self.delegate!.validationSuccessful() } else { // call failure method if it's implemented self.delegate!.validationFailed(self.errors) } // set number of completed validations back to 0 self.completedValidationsCount = 0 } } /** This method validates all fields in validator and sets any errors to errors parameter of closure. - parameter callback: A closure which is called with errors, a dictionary of type UITextField:ValidationError. - returns: No return value. */ public func validate(callback:(errors:[UITextField:ValidationError])->Void) -> Void { self.validateAllFields() callback(errors: errors) } }
mit
02c4dcfd3e9f574e4ee31fe060e71793
39.780669
205
0.610392
5.501505
false
false
false
false
oscarafuentes/Ana
Ana/Extensions/UIViewController+Ana.swift
1
2713
// // UIViewController+Ana.swift // Ana // // Created by Oscar Fuentes on 6/8/17. // Copyright © 2017 Oscar Fuentes. All rights reserved. // import Foundation import UIKit public struct AViewControllerTransitionStyle { public static let navigation = 1 public static let presentation = 2 } extension UIViewController { open override func enter(_ parent: UIResponder? = nil, animated: Bool = true, completion: @escaping () -> Void) { if let parent = parent as? UIViewController { if self.transitionStyle() == AViewControllerTransitionStyle.navigation { // TODO: Handle case where tempalte is a UINavigationController if let navController = parent.navigationController { navController.pushViewController(self, animated: animated) completion() } else { parent.present(UINavigationController(rootViewController: self), animated: animated, completion: completion) } } else { parent.present(self, animated: animated, completion: completion) } } else { guard let window = UIApplication.shared.delegate?.window else { return } window?.rootViewController = self.transitionStyle() == AViewControllerTransitionStyle.navigation ? UINavigationController(rootViewController: self) : self window?.makeKeyAndVisible() completion() } } open override func leave(_ animated: Bool = true, completion: @escaping () -> Void) { guard self.transitionStyle() == AViewControllerTransitionStyle.navigation else { self.dismiss(animated: animated, completion: completion) return } guard let navController = self.navigationController else { debugPrint("Attempting to leave from `navigation` transition style but no descendant navigation controller found.") return } guard let index = navController.viewControllers.index(of: self) else { debugPrint("Attempting to leave from `navigation` transition style but could not location self in navigation stack (hierarchy).") return } if index == 0 { navController.dismiss(animated: animated, completion: completion) } else { navController.popToViewController(navController.viewControllers[index - 1], animated: animated) completion() } } open func transitionStyle() -> Int { return AViewControllerTransitionStyle.navigation } }
mit
ac8e8705563610a81626d3d027594cdf
36.150685
166
0.621313
5.685535
false
false
false
false
qiuncheng/posted-articles-in-blog
Demos/QRCodeDemo/QRCodeDemo/ViewController.swift
1
3370
// // ViewController.swift // YLQRCode // // Created by yolo on 2017/1/1. // Copyright © 2017年 Qiuncheng. All rights reserved. // import UIKit import SafariServices class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textField.text = "http://weixin.qq.com/r/QkB8ZE7EuxPErQoH9xVQ" imageView.isUserInteractionEnabled = true let long = UILongPressGestureRecognizer(target: self, action: #selector(detecteQRCode(gesture:))) imageView.addGestureRecognizer(long) generateQRCodeButtonClicked(nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func detecteQRCode(gesture: UILongPressGestureRecognizer) { guard gesture.state == .began else { return } let detect: ((UIAlertAction) -> Void)? = { [weak self] _ in guard let image = self?.imageView.image else { return } YLDetectQRCode.scanQRCodeFromPhotoLibrary(image: image) { (result) in guard let _result = result else { return } QRScanCommon.playSound() if _result.hasPrefix("http") { if let url = URL.init(string: _result) { let sfVC = SFSafariViewController(url: url) self?.present(sfVC, animated: true, completion: nil) } } else { showAlertView(title: "二维码结果", message: _result, cancelButtonTitle: "确定") } } } let saveQRCode: ((UIAlertAction) -> Void)? = { [weak self] _ in guard let image = self?.imageView.image else { return } UIImageWriteToSavedPhotosAlbum(image, self, #selector(ViewController.image(image:error:contextInfo:)), nil) } let alertController = UIAlertController(title: "请选择", message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "识别二维码", style: .default, handler: detect)) alertController.addAction(UIAlertAction.init(title: "保存二维码", style: .default, handler: saveQRCode)) alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) present(alertController, animated: true, completion: nil) } // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; func image(image: UIImage, error: Error, contextInfo: Any) { showAlertView(title: "提醒", message: "保存图片成功", cancelButtonTitle: "确定") } @IBAction func generateQRCodeButtonClicked(_ sender: Any?) { view.endEditing(true) guard let text = textField.text else { return } GenerateQRCode.beginGenerate(text: text) { guard let image = $0 else { return } DispatchQueue.main.async { [weak self] in self?.imageView.image = image } } } }
apache-2.0
8077956704c52b8e17c99206dc01a583
36.965517
119
0.608235
4.828947
false
false
false
false
Jnosh/swift
stdlib/public/core/StringInterpolation.swift
6
3042
//===--- StringInterpolation.swift - String Interpolation -----------------===// // // 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 String : _ExpressibleByStringInterpolation { /// Creates a new string by concatenating the given interpolations. /// /// Do not call this initializer directly. It is used by the compiler when /// you create a string using string interpolation. Instead, use string /// interpolation to create a new string by including values, literals, /// variables, or expressions enclosed in parentheses, prefixed by a /// backslash (`\(`...`)`). /// /// let price = 2 /// let number = 3 /// let message = "If one cookie costs \(price) dollars, " + /// "\(number) cookies cost \(price * number) dollars." /// print(message) /// // Prints "If one cookie costs 2 dollars, 3 cookies cost 6 dollars." @_inlineable @effects(readonly) public init(stringInterpolation strings: String...) { self.init() for str in strings { self += str } } /// Creates a string containing the given expression's textual /// representation. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. /// /// - SeeAlso: `ExpressibleByStringInterpolation` @_inlineable public init<T>(stringInterpolationSegment expr: T) { self = String(describing: expr) } /// Creates a string containing the given value's textual representation. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. /// /// - SeeAlso: `ExpressibleByStringInterpolation` @_inlineable public init<T: TextOutputStreamable> (stringInterpolationSegment expr: T) { self = _toStringReadOnlyStreamable(expr) } /// Creates a string containing the given value's textual representation. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. /// /// - SeeAlso: `ExpressibleByStringInterpolation` @_inlineable public init<T: CustomStringConvertible> (stringInterpolationSegment expr: T) { self = _toStringReadOnlyPrintable(expr) } /// Creates a string containing the given value's textual representation. /// /// Do not call this initializer directly. It is used by the compiler when /// interpreting string interpolations. /// /// - SeeAlso: `ExpressibleByStringInterpolation` public init<T: TextOutputStreamable & CustomStringConvertible> (stringInterpolationSegment expr: T) { self = _toStringReadOnlyStreamable(expr) } }
apache-2.0
e1140c1f802256e64c61159fbd53df93
37.025
103
0.675542
5.053156
false
false
false
false
ricardorauber/iOS-Swift
iOS-Swift.playground/Pages/Timers.xcplaygroundpage/Contents.swift
1
1835
//: ## Timers //: ---- //: [Previous](@previous) import Foundation class CustomClass { var count = 0 func handleTimer() { print("timer ticked!") } func handleTimerWithRepetition(timer: NSTimer) { print("timer ticked!") if timer.valid { if ++count >= 3 { timer.invalidate() // Stops the Timer } } } } let customClass = CustomClass() //: Scheduled Timer on the current NSRunLoop let scheduledTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: customClass, selector: "handleTimer", userInfo: "any data", repeats: false ) //: Scheduled Timer With Repetition let scheduledTimerWithRepetition = NSTimer.scheduledTimerWithTimeInterval(1.0, target: customClass, selector: "handleTimerWithRepetition:", userInfo: nil, repeats: true ) //: Scheduling Timers Manually let selfScheduledTimer = NSTimer(timeInterval: 1.0, target: customClass, selector: "handleTimer", userInfo: nil, repeats: false ) NSRunLoop.currentRunLoop().addTimer(selfScheduledTimer, forMode: NSDefaultRunLoopMode) //: Scheduling Timers Manually With Fire Date let fireDate = NSDate(timeIntervalSinceNow: 3.0) let selfScheduledTimerWithFireDate = NSTimer(fireDate: fireDate, interval: 1.0, target: customClass, selector: "handleTimer", userInfo: nil, repeats: false ) NSRunLoop.currentRunLoop().addTimer(selfScheduledTimerWithFireDate, forMode: NSDefaultRunLoopMode) //: Firing Timers Manually let timerToFire = NSTimer(timeInterval: 3.0, target: customClass, selector: "handleTimer", userInfo: nil, repeats: true) func fireTimer() { timerToFire.fire() // auto invalidate timer if it is a non-repeating timer timerToFire.fire() timerToFire.fire() } //: [Next](@next)
mit
1de602468af4f7957a6eee1190eeb8c8
23.144737
120
0.686104
4.348341
false
false
false
false
quire-io/SwiftyChrono
Sources/Parsers/EN/ENSlashDateFormatStartWithYearParser.swift
1
1643
// // ENSlashDateFormatStartWithYearParser.swift // SwiftyChrono // // Created by Jerry Chen on 1/23/17. // Copyright © 2017 Potix. All rights reserved. // import Foundation /* Date format with slash "/" between numbers like ENSlashDateFormatParser, but this parser expect year before month and date. - YYYY/MM/DD - YYYY-MM-DD - YYYY.MM.DD */ private let PATTERN = "(\\W|^)" + "([0-9]{4})[\\-\\.\\/]([0-9]{1,2})[\\-\\.\\/]([0-9]{1,2})" + "(?=\\W|$)" private let yearNumberGroup = 2 private let monthNumberGroup = 3 private let dateNumberGroup = 4 public class ENSlashDateFormatStartWithYearParser: Parser { override var pattern: String { return PATTERN } override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? { let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match) var result = ParsedResult(ref: ref, index: index, text: matchText) result.start.assign(.year, value: Int(match.string(from: text, atRangeIndex: yearNumberGroup))) result.start.assign(.month, value: Int(match.string(from: text, atRangeIndex: monthNumberGroup))) result.start.assign(.day, value: Int(match.string(from: text, atRangeIndex: dateNumberGroup))) guard let month = result.start[.month], let day = result.start[.day] else { return nil } if month > 12 || month < 1 || day > 31 || day < 1 { return nil } result.tags[.enSlashDateFormatStartWithYearParser] = true return result } }
mit
770d9f94344d02f5d6d5430352a077d2
31.84
129
0.634592
3.881797
false
false
false
false
cpuu/OTT
OTT/Peripheral/PeripheralManagerAddAdvertisedServiceViewController.swift
1
3216
// // PeripheralManagerAddAdvertisedServiceViewController.swift // BlueCap // // Created by Troy Stribling on 10/2/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class PeripheralManagerAddAdvertisedServiceViewController: UITableViewController { struct MainStoryboard { static let peripheralManagerAddAdverstisedServiceCell = "PeripheralManagerAddAdverstisedServiceCell" } var peripheral: String? var peripheralManagerViewController : PeripheralManagerViewController? var services: [BCMutableService] { if let peripheral = self.peripheral { let serviceUUIDs = PeripheralStore.getAdvertisedPeripheralServicesForPeripheral(peripheral) return Singletons.peripheralManager.services.filter{!serviceUUIDs.contains($0.UUID)} } else { return [] } } required init?(coder aDecoder:NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PeripheralManagerAddAdvertisedServiceViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } func didEnterBackground() { BCLogger.debug() if let peripheralManagerViewController = self.peripheralManagerViewController { self.navigationController?.popToViewController(peripheralManagerViewController, animated: false) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(_:UITableView, numberOfRowsInSection section: Int) -> Int { return self.services.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralManagerAddAdverstisedServiceCell, forIndexPath: indexPath) as! NameUUIDCell if let _ = self.peripheral { let service = self.services[indexPath.row] cell.nameLabel.text = service.name cell.uuidLabel.text = service.UUID.UUIDString } else { cell.nameLabel.text = "Unknown" cell.uuidLabel.text = "Unknown" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let peripheral = self.peripheral { let service = self.services[indexPath.row] PeripheralStore.addAdvertisedPeripheralService(peripheral, service:service.UUID) } self.navigationController?.popViewControllerAnimated(true) } }
mit
8900573ae755d97f5dd527d0128dd5c3
35.134831
219
0.701493
5.612565
false
false
false
false
pkadams67/PKA-Project---Puff-Dragon
Puff Magic/GameViewController.swift
1
3794
// // GameViewController.swift // Puff Dragon // // Created by Paul Kirk Adams on 4/21/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import UIKit import Crashlytics import FBSDKCoreKit import FBSDKLoginKit import FBAudienceNetwork import LaunchKit import SpriteKit import GameKit import AVFoundation class GameViewController: UIViewController, FBAdViewDelegate { var backgroundMusic: AVAudioPlayer! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) LaunchKit.sharedInstance().presentAppReleaseNotesIfNeededFromViewController(self) { (didPresent: Bool) -> Void in if didPresent { print("Release Notes card presented") } } // Uncomment for debugging (always show Release Notes) // LaunchKit.sharedInstance().debugAlwaysPresentAppReleaseNotes = true } override func viewDidLoad() { super.viewDidLoad() // Use to test Facebook integration // let facebookLoginButton: FBSDKLoginButton = FBSDKLoginButton() // facebookLoginButton.center = self.view.center // self.view!.addSubview(facebookLoginButton) FBAdSettings.addTestDevice("b981ff62ed0cc52075e3061484e089601b66e1cc") let adView: FBAdView = FBAdView(placementID: "175149402879956_175211062873790", adSize: kFBAdSizeHeight50Banner, rootViewController: self) adView.delegate = self adView.hidden = true self.view!.addSubview(adView) adView.loadAd() playBackgroundMusic("surrealChase.mp3") authenticateLocalPlayer() // Checks whether user logged into Apple's Game Center if let scene = GameScene(fileNamed:"GameScene") { let skView = self.view as! SKView skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill skView.presentScene(scene) } } func adView(adView: FBAdView, didFailWithError error: NSError) { NSLog("Facebook Ad failed to load") adView.hidden = true } func adViewDidLoad(adView: FBAdView) { NSLog("Facebook Ad was loaded and ready to be displayed") adView.hidden = false } func authenticateLocalPlayer() { let localPlayer = GKLocalPlayer.localPlayer() localPlayer.authenticateHandler = {(viewController, error) -> Void in if (viewController != nil) { self.presentViewController(viewController!, animated: true, completion: nil) } else { print("Is local player authenticated? \(GKLocalPlayer.localPlayer().authenticated)") } } } func playBackgroundMusic(filename: String) { let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil) guard let backgroundMusicURL = url else { print("Could not find file: \(filename)") return } do { backgroundMusic = try AVAudioPlayer(contentsOfURL: backgroundMusicURL) backgroundMusic.numberOfLoops = -1 backgroundMusic.prepareToPlay() backgroundMusic.play() backgroundMusic.volume = 0.1 } catch let error as NSError { print(error.description) } } override func shouldAutorotate() -> Bool { return false } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return .Portrait } else { return .All } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
0e18eb475ee66cf1bdc03b0636f27f54
30.355372
146
0.648827
5.14654
false
false
false
false
argent-os/argent-ios
app-ios/Plan.swift
1
14968
// // Plan.swift // app-ios // // Created by Sinan Ulkuatam on 5/3/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import SwiftyJSON import Alamofire import Crashlytics class Plan { static let sharedInstance = Plan(id: "", name: "", interval: "", interval_count: 1, currency: "", amount: "", statement_desc: "") let id: Optional<String> let name: Optional<String> let interval: Optional<String> let interval_count: Optional<Int> let currency: Optional<String> let amount: Optional<String> let statement_desc: Optional<String> required init(id: String, name: String, interval: String, interval_count: Int, currency: String, amount: String, statement_desc: String) { self.id = id self.name = name self.interval = interval self.interval_count = interval_count self.currency = currency self.amount = amount self.statement_desc = statement_desc } class func createPlan(dic: Dictionary<String, AnyObject>, completionHandler: (Bool, String) -> Void) { if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/json" ] let parameters : [String : AnyObject] = dic let endpoint = API_URL + "/stripe/" + (user?.id)! + "/plans" Alamofire.request(.POST, endpoint, parameters: parameters, encoding:.JSON, headers: headers) .responseJSON { response in switch response.result { case .Success: if let value = response.result.value { // let data = JSON(value) // TODO: Update plan handling, response with success and error status codes let data = JSON(value) if data["error"]["message"].stringValue != "" { completionHandler(false, data["error"]["message"].stringValue) Answers.logCustomEventWithName("Recurring Billing Creation failure", customAttributes: dic) } else { completionHandler(true, String(response.result.error)) Answers.logCustomEventWithName("Recurring Billing Creation Plan Success", customAttributes: dic) } } case .Failure(let error): print(error) completionHandler(false, error.localizedDescription) Answers.logCustomEventWithName("Recurring Billing Plan Error", customAttributes: [ "error": error.localizedDescription ]) } } }) } } class func getPlanList(limit: String, starting_after: String, completionHandler: ([Plan]?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/x-www-form-urlencoded" ] let limit = limit let starting_after = starting_after let user_id = (user?.id) var endpoint = API_URL + "/stripe/" + user_id! + "/plans" if starting_after != "" { endpoint = API_URL + "/stripe/" + user_id! + "/plans?limit=" + limit + "&starting_after=" + starting_after } else { endpoint = API_URL + "/stripe/" + user_id! + "/plans?limit=" + limit } Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers) .validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) var plansArray = [Plan]() let plans = data["plans"]["data"].arrayValue for plan in plans { let id = plan["id"].stringValue let amount = plan["amount"].stringValue let name = plan["name"].stringValue let interval = plan["interval"].stringValue let interval_count = plan["interval_count"].intValue let statement_desc = plan["statement_descriptor"].stringValue let item = Plan(id: id, name: name, interval: interval, interval_count: interval_count, currency: "", amount: amount, statement_desc: statement_desc) plansArray.append(item) } completionHandler(plansArray, response.result.error) } case .Failure(let error): print(error) } } }) } } class func getPlan(id: String, completionHandler: (JSON?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/x-www-form-urlencoded" ] let user_id = (user?.id) var endpoint = API_URL + "/stripe/" + user_id! + "/plans/" + id Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers) .validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) let plan = data["plan"] let id = plan["id"].stringValue let amount = plan["amount"].stringValue let name = plan["name"].stringValue let interval = plan["interval"].stringValue let interval_count = plan["interval_count"].intValue let statement_desc = plan["statement_descriptor"].stringValue let item = Plan(id: id, name: name, interval: interval, interval_count: interval_count, currency: "", amount: amount, statement_desc: statement_desc) completionHandler(plan, response.result.error) } case .Failure(let error): print(error) } } }) } } class func updatePlan(id: String, dic: Dictionary<String, AnyObject>, completionHandler: (Bool?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let parameters : [String : AnyObject] = dic let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/json" ] let user_id = (user?.id) let endpoint = API_URL + "/stripe/" + user_id! + "/plans/" + id Alamofire.request(.PUT, endpoint, parameters: parameters, encoding: .JSON, headers: headers) .validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) if data["error"]["message"].stringValue != "" { let err: NSError = NSError(domain: data["error"]["message"].stringValue, code: 13, userInfo: nil) completionHandler(false, err) Answers.logCustomEventWithName("Recurring Billing update failure", customAttributes: [:]) } else { Answers.logCustomEventWithName("Recurring Billing update success", customAttributes: [:]) completionHandler(true, response.result.error) } } case .Failure(let error): print(error) } } }) } } class func getDelegatedPlanList(delegatedUsername: String, limit: String, starting_after: String, completionHandler: ([Plan]?, NSError?) -> Void) { // request to api to get data as json, put in list and table // check for token, get profile id based on token and make the request let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/x-www-form-urlencoded" ] let limit = limit let delegated_username = delegatedUsername let starting_after = starting_after var endpoint = API_URL + "/stripe/plans/" + delegated_username if starting_after != "" { endpoint = API_URL + "/stripe/plans/" + delegated_username + "?limit=" + limit + "&starting_after=" + starting_after } else { endpoint = API_URL + "/stripe/plans/" + delegated_username + "?limit=" + limit } Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers) .validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value) var plansArray = [Plan]() let plans = data["plans"]["data"].arrayValue for plan in plans { let id = plan["id"].stringValue let amount = plan["amount"].stringValue let name = plan["name"].stringValue let interval = plan["interval"].stringValue let interval_count = plan["interval_count"].intValue let statement_desc = plan["statement_descriptor"].stringValue let item = Plan(id: id, name: name, interval: interval, interval_count: interval_count, currency: "", amount: amount, statement_desc: statement_desc) Answers.logCustomEventWithName("Viewing Merchant Recurring Billing Plans", customAttributes: [:]) plansArray.append(item) } completionHandler(plansArray, response.result.error) } case .Failure(let error): print(error) } } } class func deletePlan(id: String, completionHandler: (Bool?, NSError?) -> Void) { // check for token, get profile id based on token and make the request if(userAccessToken != nil) { User.getProfile({ (user, error) in if error != nil { print(error) } let user_id = (user?.id) let parameters : [String : AnyObject] = [:] let headers = [ "Authorization": "Bearer " + (userAccessToken as! String), "Content-Type": "application/json" ] let endpoint = API_URL + "/stripe/" + user_id! + "/plans/" + id Alamofire.request(.DELETE, endpoint, parameters: parameters, encoding: .URL, headers: headers) .responseJSON { response in switch response.result { case .Success: if let value = response.result.value { //let data = JSON(value) completionHandler(true, response.result.error) } case .Failure(let error): print(error) } } }) } } }
mit
8d5563451b385a8cad61fdf9defee27f
45.484472
185
0.447384
5.934576
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/Observables/ToArray.swift
4
1968
// // ToArray.swift // RxSwift // // Created by Junior B. on 20/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Converts an Observable into another Observable that emits the whole sequence as a single array and then terminates. For aggregation behavior see `reduce`. - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) - returns: An observable sequence containing all the emitted elements as array. */ public func toArray() -> Observable<[E]> { return ToArray(source: self.asObservable()) } } final private class ToArraySink<SourceType, O: ObserverType>: Sink<O>, ObserverType where O.E == [SourceType] { typealias Parent = ToArray<SourceType> let _parent: Parent var _list = [SourceType]() init(parent: Parent, observer: O, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let value): self._list.append(value) case .error(let e): self.forwardOn(.error(e)) self.dispose() case .completed: self.forwardOn(.next(self._list)) self.forwardOn(.completed) self.dispose() } } } final private class ToArray<SourceType>: Producer<[SourceType]> { let _source: Observable<SourceType> init(source: Observable<SourceType>) { self._source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] { let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
apache-2.0
aa02e39166ab00bcd8fcc1a2fb9c66e2
28.80303
149
0.629385
4.35177
false
false
false
false
liulichao123/fangkuaishou
快手/快手/classes/Main/common/common.swift
1
2309
// // common.swift // 快手 // // Created by liulichao on 16/5/4. // Copyright © 2016年 刘立超. All rights reserved. // import Foundation //MARK:屏幕大小 /**屏幕大小**/ let ScreenSize = UIScreen.mainScreen().bounds.size //MARK:状态栏大小 /**状态栏大小**/ let statusBarSize: CGSize = UIApplication.sharedApplication().statusBarFrame.size //MARK:定义日志输出函数 func printLog<T>(message: T, file: String = #file, method: String = #function, line: Int = #line) { //release时将会成为空方法,新版LLVM编译器将会略掉该方法 // #if DEBUG print("\((file as NSString).lastPathComponent)[\(line)], \(method): \(message)") // #endif } //MARK:用户键 /**用户名key**/ let UserPhoneKey = "UserPhoneKey" /**用户密码key**/ let UserPwdKey = "UserPwdKey" /**用户idkey**/ let UserIdKey = "UserIdKey" //MARK:按钮通知 /**左上角按钮点击事件通知**/ let leftBtnClickNotificatioin = "leftBtnClickNotificatioin" /**左侧按钮点击事件通知**/ let leftViewBtnClickNotificatioin = "leftViewBtnClickNotificatioin" /*左侧视图上部按钮点击通知**/ let leftViewTopBtnclickNotification = "leftViewTopBtnclickNotification" //MARK:网络接口 //let ServerIP = "http://localhost:8080" let ServerIP = "http://115.159.37.41:8080" //服务器项目名称 let ServerName = "sshkuaishou" //视频,图片 路径前缀 let VideoPrePath = ServerIP + "/" + ServerName + "/" /***注册接口*/ let RegistIP = ServerIP + "/sshkuaishou/regist" /***登录接口*/ let LoginIP = ServerIP + "/sshkuaishou/login" /**上传视频*/ let UploadVideoIP = ServerIP + "/sshkuaishou/video_upload" //MARK:首页接口 /**每页条数*/ let PageSize: Int = 20 /**获取关注视频接口**/ let HomeGuanZhuIP = ServerIP + "/sshkuaishou/video_getVideosOfUserGuanZhu" /**获取发现视频接口**/ let HomeFaXianIP = ServerIP + "/sshkuaishou/video_pubVideo" /**获取同城视频接口**/ let HomeTongChengIP = ServerIP + "/sshkuaishou/video_pubVideo" /**添加关注接口**/ let AddGuanZhuIP = ServerIP + "/sshkuaishou/user_addGuanZhuUser" /**添加双击接口**/ let AddLikeIP = ServerIP + "/sshkuaishou/video_addLike" //MARK:我接口 /**添加双击接口**/ let PersonVideosIP = ServerIP + "/sshkuaishou/video_getVideosOfUser"
apache-2.0
a23243ddd04e67a1ac8cae0992de589b
22.047619
99
0.706612
2.868148
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Settings/VSettingsCellShare.swift
1
1184
import UIKit class VSettingsCellShare:VSettingsCell { override init(frame:CGRect) { super.init(frame:frame) let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.clipsToBounds = true button.setTitle( String.localized(key:"VSettingsCellShare_button"), for:UIControlState.normal) button.setTitleColor( UIColor.white, for:UIControlState.normal) button.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) button.titleLabel!.font = UIFont.bold(size:15) addSubview(button) NSLayoutConstraint.equals( view:button, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: actions func actionButton(sender button:UIButton) { controller?.share() } }
mit
38eb006f306c6b18fe9ac64a112fbd7b
24.73913
64
0.586993
5.170306
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/KillmailsViewController.swift
2
2201
// // KillmailsViewController.swift // Neocom // // Created by Artem Shimanski on 11/13/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import TreeController import Futures class KillmailsViewController: PageViewController, ContentProviderView { typealias Presenter = KillmailsPresenter lazy var presenter: Presenter! = Presenter(view: self) var unwinder: Unwinder? var killsViewController: KillmailsPageViewController? var lossesViewController: KillmailsPageViewController? override func viewDidLoad() { super.viewDidLoad() killsViewController = try! KillmailsPage.default.instantiate().get() lossesViewController = try! KillmailsPage.default.instantiate().get() killsViewController?.title = NSLocalizedString("Kills", comment: "") lossesViewController?.title = NSLocalizedString("Losses", comment: "") viewControllers = [killsViewController!, lossesViewController!] presenter.configure() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) presenter.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presenter.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) presenter.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) presenter.viewDidDisappear(animated) } func present(_ content: Presenter.Presentation, animated: Bool) -> Future<Void> { killsViewController?.input = content.kills lossesViewController?.input = content.losses killsViewController?.presenter.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak killsViewController] presentation in killsViewController?.present(presentation, animated: false) } lossesViewController?.presenter.reload(cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak lossesViewController] presentation in lossesViewController?.present(presentation, animated: false) } return .init(()) } func fail(_ error: Error) { killsViewController?.fail(error) lossesViewController?.fail(error) } }
lgpl-2.1
7dfa94ac3abf48094e6d875cb6698c62
29.555556
140
0.772727
4.263566
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Option/WhistlesVsZombies/Scene/VOptionWhistlesVsZombiesScene.swift
1
4330
import SpriteKit class VOptionWhistlesVsZombiesScene:ViewGameScene<MOptionWhistlesVsZombies> { required init(controller:ControllerGame<MOptionWhistlesVsZombies>) { super.init(controller:controller) physicsWorld.gravity = CGVector.zero factoryNodes() } required init?(coder:NSCoder) { return nil } //MARK: private private func factoryNodes() { let model:MOptionWhistlesVsZombies = controller.model let background:VOptionWhistlesVsZombiesBackground = VOptionWhistlesVsZombiesBackground( controller:controller) let hud:VOptionWhistlesVsZombiesHud = VOptionWhistlesVsZombiesHud( controller:controller) model.hud.view = hud let fire:VOptionWhistlesVsZombiesFire = VOptionWhistlesVsZombiesFire( controller:controller) model.horde.viewFire = fire let player:VOptionWhistlesVsZombiesPlayer = VOptionWhistlesVsZombiesPlayer( controller:controller) model.player.view = player let physicHome:VOptionWhistlesVsZombiesPhysicHome = VOptionWhistlesVsZombiesPhysicHome( controller:controller) let physicSonicLimit:VOptionWhistlesVsZombiesPhysicSonicLimit = VOptionWhistlesVsZombiesPhysicSonicLimit( controller:controller) let menu:ViewGameNodeMenu<MOptionWhistlesVsZombies> = ViewGameNodeMenu<MOptionWhistlesVsZombies>( controller:controller, texture:model.textures.menu, orientation:UIInterfaceOrientation.landscapeLeft) model.viewMenu = menu let hordeTitle:VOptionWhistlesVsZombiesHordeTitle = VOptionWhistlesVsZombiesHordeTitle() model.horde.viewTitle = hordeTitle let title:VOptionWhistlesVsZombiesTitle = VOptionWhistlesVsZombiesTitle() model.viewTitle = title addChild(background) addChild(hud) addChild(fire) addChild(player) factoryBases() addChild(physicHome) addChild(physicSonicLimit) addChild(menu) addChild(hordeTitle) addChild(title) } private func factoryBases() { let bases:[MOptionWhistlesVsZombiesWhistleBase] = controller.model.whistle.bases for base:MOptionWhistlesVsZombiesWhistleBase in bases { let view:VOptionWhistlesVsZombiesBase = VOptionWhistlesVsZombiesBase( controller:controller, model:base) base.viewBase = view addChild(view) } } //MARK: public func addWhistle(base:MOptionWhistlesVsZombiesWhistleBase) { guard let view:VOptionWhistlesVsZombiesWhistle = VOptionWhistlesVsZombiesWhistle( controller:controller, model:base) else { return } base.viewWhistle = view addChild(view) } func addSonicBoomRelease(model:MOptionWhistlesVsZombiesSonicBoomItem) { let view:VOptionWhistlesVsZombiesSonicRelease = VOptionWhistlesVsZombiesSonicRelease( controller:controller, model:model) model.viewRelease = view addChild(view) } func addSonicBoom(model:MOptionWhistlesVsZombiesSonicBoomItem) { let view:VOptionWhistlesVsZombiesSonicBoom = VOptionWhistlesVsZombiesSonicBoom( controller:controller, model:model) model.viewBoom = view addChild(view) } func addZombie(model:MOptionWhistlesVsZombiesZombieItem) { let view:VOptionWhistlesVsZombiesZombie = VOptionWhistlesVsZombiesZombie( controller:controller, model:model) model.view = view addChild(view) } func addPoints( model:MOptionWhistlesVsZombiesPointsItem, modelZombie:MOptionWhistlesVsZombiesZombieItem) { let view:VOptionWhistlesVsZombiesPoints = VOptionWhistlesVsZombiesPoints( controller:controller, modelZombie:modelZombie) model.view = view addChild(view) } }
mit
a96d7d1bf8b075a0cf3bd5879fe32bb6
29.069444
113
0.640647
5.608808
false
false
false
false
SirWellington/sir-wellington-mall
Pods/SwiftExceptionCatcher/SwiftExceptionCatcher/SwiftExceptionCatcher/SwiftExceptionCatcher.swift
1
1355
// // TryOperation.swift // SwiftExceptionCatcher // // Created by Juan Wellington Moreno on 4/4/16. // Copyright © 2016 RedRoma, Inc. All rights reserved. // import Foundation /** * This Extension adds the ability to catch NSException Types in Swift. */ extension NSException : ErrorType { public var _domain: String { return "tech.redroma.SwiftExceptionCatcher" } public var _code: Int { return 0 } } /** This class wraps Operations that may throw NSException types and catches them in a safe way Primarily designed to overcome Swift's exception-handling limitations. - parameter operation: This operation may throw an Objective-C NSException type and must be safely wrapped. */ public func tryOp<T>(operation: (() throws -> T)) throws -> T { var result: T? var error: NSException? let theTry: () -> () = { do { result = try operation() } catch let ex { error = ex as? NSException } return } let theCatch: (NSException!) -> () = { ex in error = ex } tryOperation(theTry, theCatch) if let result = result { return result } else if let ex = error { throw ex } else { throw NSException(name: "Unknown", reason: "Error Occured performing Operation", userInfo: nil) } }
mit
2afd66b6691827210d83216a67573128
24.54717
111
0.624077
4.23125
false
false
false
false
Ataluer/ASRoam
ASRoam/ASRoam/Class/Home/Controller/HomeController.swift
1
3094
// // HomeController.swift // ASRoam // // Created by Yanfei Yu on 2017/5/18. // Copyright © 2017年 Ataluer. All rights reserved. // import UIKit class HomeController: UIViewController, PageContentViewDelegate { //MARK: -懒加载PageTitleView fileprivate lazy var pageTitleView: PageTitleView = {[weak self] in let titleView = PageTitleView(frame: CGRect(x: 0, y: 64, width: kScreenW, height: 40), titles: ["推荐", "体育", "娱乐", "趣玩"], clickBlock: { (NSInteger) -> (Void) in self?.pageContentView.setCurrentIndex(currentIndex: NSInteger) }) return titleView }() //MARK: - 懒加载PageContentView fileprivate lazy var pageContentView: PageContentView = { var childVcs = [UIViewController]() for _ in 0..<4 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) vc.view.backgroundColor = UIColor.white childVcs.append(vc) } let pageContentView = PageContentView(frame: CGRect(x: 0, y: 104, width: kScreenW, height: kScreenH-104-49), childVcs: childVcs, parentViewController: self) return pageContentView }() // MARK: -系统回掉函数 override func viewDidLoad() { super.viewDidLoad() //1.设置UI界面 setupUI() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HomeController { fileprivate func setupUI() { //1.设置导航栏 setupNavigationBar() //2.添加titleview view.addSubview(pageTitleView) //3.添加contentCollection view.addSubview(pageContentView) pageContentView.delegate = self } private func setupNavigationBar() { self.automaticallyAdjustsScrollViewInsets = false //1.设置左边的图片按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //2.设置右边的按钮 let btnSize = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: btnSize) let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: btnSize) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: btnSize) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } } // MARK: -PageContentViewDelegate extension HomeController { func pageContentView(progress: CGFloat, currentIndex: Int, targetIndex: Int) { self.pageTitleView.setTitleWithProgress(progress: progress, currentIndex: currentIndex, targetIndex: targetIndex) } }
mit
d902639c0e577ceea066abab41f796bf
31.182796
167
0.649181
4.78115
false
false
false
false
exchangegroup/MprHttp
MprHttp/TegQ/TegString.swift
2
1155
// // Helper functions to work with strings. // import Foundation public struct TegString { public static func blank(text: String) -> Bool { let trimmed = text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) return trimmed.isEmpty } public static func trim(text: String) -> String { return text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } public static func contains(text: String, substring: String, ignoreCase: Bool = false, ignoreDiacritic: Bool = false) -> Bool { var options: UInt = 0 if ignoreCase { options |= NSStringCompareOptions.CaseInsensitiveSearch.rawValue } if ignoreDiacritic { options |= NSStringCompareOptions.DiacriticInsensitiveSearch.rawValue } return text.rangeOfString(substring, options: NSStringCompareOptions(rawValue: options)) != nil } // // Returns a single space if string is empty. // It is used to set UITableView cells labels as a workaround. // public static func singleSpaceIfEmpty(text: String) -> String { if text == "" { return " " } return text } }
mit
e09d93bcecf0901eda8b5732fca16555
27.875
105
0.720346
4.957082
false
false
false
false
wireapp/wire-ios-data-model
Source/Utilis/FileManager+FileLocations.swift
1
2833
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireSystem private let zmLog = ZMSLog(tag: "FileLocation") public extension FileManager { /// Returns the URL for the sharedContainerDirectory of the app @objc(sharedContainerDirectoryForAppGroupIdentifier:) static func sharedContainerDirectory(for appGroupIdentifier: String) -> URL { let fm = FileManager.default let sharedContainerURL = fm.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) // Seems like the shared container is not available. This could happen for series of reasons: // 1. The app is compiled with with incorrect provisioning profile (for example with 3rd parties) // 2. App is running on simulator and there is no correct provisioning profile on the system // 3. Bug with signing // // The app should not allow to run in all those cases. require(nil != sharedContainerURL, "Unable to create shared container url using app group identifier: \(appGroupIdentifier)") return sharedContainerURL! } @objc static let cachesFolderPrefix: String = "wire-account" /// Returns the URL for caches appending the accountIdentifier if specified @objc func cachesURL(forAppGroupIdentifier appGroupIdentifier: String, accountIdentifier: UUID?) -> URL? { guard let sharedContainerURL = containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else { return nil } return cachesURLForAccount(with: accountIdentifier, in: sharedContainerURL) } /// Returns the URL for caches appending the accountIdentifier if specified @objc func cachesURLForAccount(with accountIdentifier: UUID?, in sharedContainerURL: URL) -> URL { let url = sharedContainerURL.appendingPathComponent("Library", isDirectory: true) .appendingPathComponent("Caches", isDirectory: true) if let accountIdentifier = accountIdentifier { return url.appendingPathComponent("\(type(of: self).cachesFolderPrefix)-\(accountIdentifier.uuidString)", isDirectory: true) } return url } }
gpl-3.0
fc017ad8324a444fe9b96562ba92664b
44.693548
136
0.727144
5.095324
false
false
false
false
benlangmuir/swift
test/SILOptimizer/di_property_wrappers.swift
11
12684
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test @propertyWrapper struct Wrapper<T> { var wrappedValue: T { didSet { print(" .. set \(wrappedValue)") } } init(wrappedValue initialValue: T) { print(" .. init \(initialValue)") self.wrappedValue = initialValue } } protocol IntInitializable { init(_: Int) } final class Payload : CustomStringConvertible, IntInitializable { let payload: Int init(_ p: Int) { self.payload = p print(" + payload alloc \(payload)") } deinit { print(" - payload free \(payload)") } var description: String { return "value = \(payload)" } } struct IntStruct { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } // Check that we don't crash if the function has unrelated generic parameters. // SR-11484 mutating func setit<V>(_ v: V) { wrapped = 5 } } final class IntClass { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } convenience init(withConvenienceInit x: Int) { self.init() self.wrapped = x } } struct RefStruct { @Wrapper var wrapped: Payload init() { wrapped = Payload(42) wrapped = Payload(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: Payload(32)) } else { wrapped = Payload(42) } } init(dynamic b: Bool) { if b { wrapped = Payload(42) } wrapped = Payload(27) } } final class GenericClass<T : IntInitializable> { @Wrapper var wrapped: T init() { wrapped = T(42) wrapped = T(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: T(32)) } else { wrapped = T(42) } } init(dynamic b: Bool) { if b { wrapped = T(42) } wrapped = T(27) } } func testIntStruct() { // CHECK: ## IntStruct print("\n## IntStruct") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 var t1 = IntStruct() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. set 5 t1.setit(false) // CHECK-NEXT: 5 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntStruct(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntStruct(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntStruct(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntStruct(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) } func testIntClass() { // CHECK: ## IntClass print("\n## IntClass") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 let t1 = IntClass() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntClass(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntClass(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntClass(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntClass(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 // CHECK-NEXT: .. set 123 let t6 = IntClass(withConvenienceInit: 123) // CHECK-NEXT: 123 print(t6.wrapped) } func testRefStruct() { // CHECK: ## RefStruct print("\n## RefStruct") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. set value = 27 let t1 = RefStruct() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = RefStruct(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = RefStruct(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = RefStruct(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = RefStruct(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } func testGenericClass() { // CHECK: ## GenericClass print("\n## GenericClass") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. set value = 27 let t1 = GenericClass<Payload>() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = GenericClass<Payload>(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = GenericClass<Payload>(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = GenericClass<Payload>(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = GenericClass<Payload>(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } @propertyWrapper struct WrapperWithDefaultInit<Value> { private var _value: Value? = nil init() { print("default init called on \(Value.self)") } var wrappedValue: Value { get { return _value! } set { print("set value \(newValue)") _value = newValue } } } struct UseWrapperWithDefaultInit { @WrapperWithDefaultInit<Int> var x: Int @WrapperWithDefaultInit<String> var y: String init(y: String) { self.y = y } } func testDefaultInit() { // CHECK: ## DefaultInit print("\n## DefaultInit") let use = UseWrapperWithDefaultInit(y: "hello") // CHECK: default init called on Int // FIXME: DI should eliminate the following call // CHECK: default init called on String // CHECK: set value hello } // rdar://problem/51581937: DI crash with a property wrapper of an optional struct OptIntStruct { @Wrapper var wrapped: Int? init() { wrapped = 42 } } func testOptIntStruct() { // CHECK: ## OptIntStruct print("\n## OptIntStruct") let use = OptIntStruct() // CHECK-NEXT: .. init nil // CHECK-NEXT: .. set Optional(42) } // rdar://problem/53504653 struct DefaultNilOptIntStruct { @Wrapper var wrapped: Int? init() { } } func testDefaultNilOptIntStruct() { // CHECK: ## DefaultNilOptIntStruct print("\n## DefaultNilOptIntStruct") let use = DefaultNilOptIntStruct() // CHECK-NEXT: .. init nil } @propertyWrapper struct Wrapper2<T> { var wrappedValue: T { didSet { print(" .. secondSet \(wrappedValue)") } } init(before: Int = -10, wrappedValue initialValue: T, after: String = "end") { print(" .. secondInit \(before), \(initialValue), \(after)") self.wrappedValue = initialValue } } struct HasComposed { @Wrapper @Wrapper2 var x: Int init() { self.x = 17 } } func testComposed() { // CHECK: ## Composed print("\n## Composed") _ = HasComposed() // CHECK-NEXT: .. secondInit -10, 17, end // CHECK-NEXT: .. init Wrapper2<Int>(wrappedValue: 17) } // SR-11477 @propertyWrapper struct SR_11477_W { let name: String init(name: String = "DefaultParamInit") { self.name = name } var wrappedValue: Int { get { return 0 } } } @propertyWrapper struct SR_11477_W1 { let name: String init() { self.name = "Init" } init(name: String = "DefaultParamInit") { self.name = name } var wrappedValue: Int { get { return 0 } } } struct SR_11477_C { @SR_11477_W var property: Int @SR_11477_W1 var property1: Int init() {} func foo() { print(_property.name) } func foo1() { print(_property1.name) } } func testWrapperInitWithDefaultArg() { // CHECK: ## InitWithDefaultArg print("\n## InitWithDefaultArg") let use = SR_11477_C() use.foo() use.foo1() // CHECK-NEXT: DefaultParamInit // CHECK-NEXT: Init } // rdar://problem/57350503 - DI failure due to an unnecessary cycle breaker public class Test57350503 { @Synchronized public private(set) var anchor: Int public init(anchor: Int) { self.anchor = anchor printMe() } private func printMe() { } } @propertyWrapper public final class Synchronized<Value> { private var value: Value public var wrappedValue: Value { get { value } set { value = newValue } } public init(wrappedValue: Value) { value = wrappedValue } } struct SR_12341 { @Wrapper var wrapped: Int = 10 var str: String init() { wrapped = 42 str = "" wrapped = 27 } init(condition: Bool) { wrapped = 42 wrapped = 27 str = "" } } func testSR_12341() { // CHECK: ## SR_12341 print("\n## SR_12341") // CHECK-NEXT: .. init 10 // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 _ = SR_12341() // CHECK-NEXT: .. init 10 // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 _ = SR_12341(condition: true) } @propertyWrapper struct NonMutatingSetterWrapper<Value> { var value: Value init(wrappedValue: Value) { print(" .. init \(wrappedValue)") value = wrappedValue } var wrappedValue: Value { get { value } nonmutating set { print(" .. nonmutatingSet \(newValue)") } } } struct NonMutatingWrapperTestStruct { @NonMutatingSetterWrapper var SomeProp: Int init(val: Int) { SomeProp = val SomeProp = val + 1 } } // Check if a non-trivial value passes the memory lifetime verifier. struct NonMutatingWrapperTestStructString { @NonMutatingSetterWrapper var SomeProp: String init(val: String) { SomeProp = val } } func testNonMutatingSetterStruct() { // CHECK: ## NonMutatingSetterWrapper print("\n## NonMutatingSetterWrapper") let A = NonMutatingWrapperTestStruct(val: 11) // CHECK-NEXT: .. init 11 // CHECK-NEXT: .. nonmutatingSet 12 } @propertyWrapper final class ClassWrapper<T> { private var _wrappedValue: T var wrappedValue: T { get { _wrappedValue } set { print(" .. set \(newValue)") _wrappedValue = newValue } } init(wrappedValue: T) { print(" .. init \(wrappedValue)") self._wrappedValue = wrappedValue } } struct StructWithClassWrapper<T> { @ClassWrapper private var _storage: T? init(value: T?) { _storage = value } } func testStructWithClassWrapper() { // CHECK: ## StructWithClassWrapper print("\n## StructWithClassWrapper") let _ = StructWithClassWrapper<Int>(value: 10) // CHECK-NEXT: .. init nil // CHECK-NEXT: .. set Optional(10) } testIntStruct() testIntClass() testRefStruct() testGenericClass() testDefaultInit() testOptIntStruct() testDefaultNilOptIntStruct() testComposed() testWrapperInitWithDefaultArg() testSR_12341() testNonMutatingSetterStruct() testStructWithClassWrapper()
apache-2.0
52d3cba21cc660b1841fdfb6c9c4c1ea
19.037915
80
0.602412
3.482702
false
false
false
false
onmyway133/Github.swift
GithubSwiftTests/Classes/EventSpec.swift
1
5393
// // EventSpec.swift // GithubSwift // // Created by Khoa Pham on 24/04/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation import GithubSwift import Quick import Nimble import Mockingjay import RxSwift import Sugar class EventSpec: QuickSpec { override func spec() { describe("event") { var events: [String: GithubSwift.Event] = [:] beforeEach { (Helper.readJSON("events") as JSONArray).flatMap({ GithubSwift.Event.cluster($0) as? GithubSwift.Event }).forEach { events[$0.objectID] = $0 } print(events) } it("OCTCommitCommentEvent should have deserialized") { let event = events["1605861091"] as! CommitCommentEvent expect(event.repositoryName).to(equal("github/twui")) expect(event.actorLogin).to(equal("galaxas0")) expect(event.organizationLogin).to(equal("github")) expect(event.date).to(equal(Formatter.date(string: "2012-10-02 22:03:12 +0000"))) } it("OCTPullRequestCommentEvent should have deserialized") { let event = events["1605868324"] as! PullRequestCommentEvent expect(event.repositoryName).to(equal("github/ReactiveCocoa")) expect(event.actorLogin).to(equal("jspahrsummers")) expect(event.organizationLogin).to(equal("github")) expect(event.comment!.reviewComment!.position).to(equal(14)) expect(event.comment!.originalPosition).to(equal(14)) expect(event.comment!.reviewComment!.commitSHA).to(equal("7e731834f7fa981166cbb509a353dbe02eb5d1ea")) expect(event.comment!.originalCommitSHA).to(equal("7e731834f7fa981166cbb509a353dbe02eb5d1ea")) expect(event.pullRequest).to(beNil()) } it("OCTIssueCommentEvent should have deserialized") { let event = events["1605861266"] as! IssueCommentEvent expect(event.repositoryName).to(equal("github/twui")) expect(event.actorLogin).to(equal("galaxas0")) expect(event.organizationLogin).to(equal("github")) } it("OCTPushEvent should have deserialized") { let event = events["1605847260"] as! PushEvent expect(event.repositoryName).to(equal("github/ReactiveCocoa")) expect(event.actorLogin).to(equal("joshaber")) expect(event.organizationLogin).to(equal("github")) expect((event.commitCount)).to(equal(36)) expect((event.distinctCommitCount)).to(equal(5)) expect(event.previousHeadSHA).to(equal("623934b71f128f9bcc44482d6dc76b7fd4848d4d")) expect(event.currentHeadSHA).to(equal("da01b97c85d2a2d2b8e4021c2e3dff693a8f2c6b")) expect(event.branchName).to(equal("new-demo")) } it("OCTPullRequestEvent should have deserialized") { let event = events["1605849683"] as! PullRequestEvent expect(event.repositoryName).to(equal("github/ReactiveCocoa")) expect(event.actorLogin).to(equal("joshaber")) expect(event.organizationLogin).to(equal("github")) expect((event.action)).to(equal(IssueAction.Opened)) } it("OCTPullRequestEventAssignee should have deserialized") { let event = events["1605825804"] as! PullRequestEvent expect(event.pullRequest!.assignee!.objectID).to(equal("432536")) expect(event.pullRequest!.assignee!.login).to(equal("jspahrsummers")) } it("OCTIssueEvent should have deserialized") { let event = events["1605857918"] as! IssueEvent expect(event.repositoryName).to(equal("github/twui")) expect(event.actorLogin).to(equal("jwilling")) expect(event.organizationLogin).to(equal("github")) expect((event.action)).to(equal(IssueAction.Opened)) } it("OCTRefEvent should have deserialized") { let event = events["1605847125"] as! RefEvent expect(event.repositoryName).to(equal("github/ReactiveCocoa")) expect(event.actorLogin).to(equal("joshaber")) expect(event.organizationLogin).to(equal("github")) expect((event.refKind)).to(equal((RefKind.Branch))) expect((event.eventKind)).to(equal(RefEventKind.Created)) expect(event.refName).to(equal("perform-selector")) } it("OCTForkEvent should have deserialized") { let event = events["2483893273"] as! ForkEvent expect(event.repositoryName).to(equal("thoughtbot/Argo")) expect(event.actorLogin).to(equal("jspahrsummers")) expect(event.forkedRepositoryName).to(equal("jspahrsummers/Argo")) } it("OCTMemberEvent should have deserialized") { let event = events["2472813496"] as! MemberEvent expect(event.repositoryName).to(equal("niftyn8/degenerate")) expect(event.actorLogin).to(equal("niftyn8")) expect(event.memberLogin).to(equal("houndci")) expect((event.action)).to(equal((MemberAction.Added))) } it("OCTPublicEvent should have deserialized") { let event = events["2485152382"] as! PublicEvent expect(event.repositoryName).to(equal("ethanjdiamond/AmIIn")) expect(event.actorLogin).to(equal("ethanjdiamond")) } it("OCTWatchEvent should have deserialized") { let event = events["2484426974"] as! WatchEvent expect(event.repositoryName).to(equal("squiidz/bone")) expect(event.actorLogin).to(equal("mattmassicotte")) } } } }
mit
9fc723031d61b1eaffb6da41dd5aae32
34.946667
123
0.670252
3.824113
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/PostListEditorPresenter.swift
1
7989
import Foundation import UIKit typealias EditorPresenterViewController = UIViewController & EditorAnalyticsProperties /// Provide properties for when showing the editor (like type of post, filter, etc) protocol EditorAnalyticsProperties: AnyObject { func propertiesForAnalytics() -> [String: AnyObject] } /// Handle a user tapping a post in the post list. If an autosave revision is available, give the /// user the option through a dialog alert to load the autosave (or just load the regular post) into /// the editor. /// Analytics are also tracked. struct PostListEditorPresenter { static func handle(post: Post, in postListViewController: EditorPresenterViewController, entryPoint: PostEditorEntryPoint = .unknown) { // Autosaves are ignored for posts with local changes. if !post.hasLocalChanges(), post.hasAutosaveRevision, let saveDate = post.dateModified, let autosaveDate = post.autosaveModifiedDate { let autosaveViewController = autosaveOptionsViewController(forSaveDate: saveDate, autosaveDate: autosaveDate, didTapOption: { loadAutosaveRevision in openEditor(with: post, loadAutosaveRevision: loadAutosaveRevision, in: postListViewController, entryPoint: entryPoint) }) postListViewController.present(autosaveViewController, animated: true) } else { openEditor(with: post, loadAutosaveRevision: false, in: postListViewController, entryPoint: entryPoint) } } static func handleCopy(post: Post, in postListViewController: EditorPresenterViewController) { // Autosaves are ignored for posts with local changes. if !post.hasLocalChanges(), post.hasAutosaveRevision { let conflictsResolutionViewController = copyConflictsResolutionViewController(didTapOption: { copyLocal, cancel in if cancel { return } if copyLocal { openEditorWithCopy(with: post, in: postListViewController) } else { handle(post: post, in: postListViewController) } }) postListViewController.present(conflictsResolutionViewController, animated: true) } else { openEditorWithCopy(with: post, in: postListViewController) } } private static func openEditor(with post: Post, loadAutosaveRevision: Bool, in postListViewController: EditorPresenterViewController, entryPoint: PostEditorEntryPoint = .unknown) { let editor = EditPostViewController(post: post, loadAutosaveRevision: loadAutosaveRevision) editor.modalPresentationStyle = .fullScreen editor.entryPoint = entryPoint postListViewController.present(editor, animated: false) } private static func openEditorWithCopy(with post: Post, in postListViewController: EditorPresenterViewController) { // Copy Post let newPost = post.blog.createDraftPost() newPost.postTitle = post.postTitle newPost.content = post.content newPost.categories = post.categories newPost.postFormat = post.postFormat // Open Editor let editor = EditPostViewController(post: newPost, loadAutosaveRevision: false) editor.modalPresentationStyle = .fullScreen editor.entryPoint = .postsList postListViewController.present(editor, animated: false) // Track Analytics event WPAppAnalytics.track(.postListDuplicateAction, withProperties: postListViewController.propertiesForAnalytics(), with: post) } private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .none return formatter }() private static let timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() private static func dateAndTime(for date: Date) -> String { return dateFormatter.string(from: date) + " @ " + timeFormatter.string(from: date) } /// A dialog giving the user the choice between loading the current version a post or its autosaved version. private static func autosaveOptionsViewController(forSaveDate saveDate: Date, autosaveDate: Date, didTapOption: @escaping (_ loadAutosaveRevision: Bool) -> Void) -> UIAlertController { let title = NSLocalizedString("Which version would you like to edit?", comment: "Title displayed in popup when user has the option to load unsaved changes") let saveDateFormatted = dateAndTime(for: saveDate) let autosaveDateFormatted = dateAndTime(for: autosaveDate) let message = String(format: NSLocalizedString("You recently made changes to this post but didn't save them. Choose a version to load:\n\nFrom this device\nSaved on %@\n\nFrom another device\nSaved on %@\n", comment: "Message displayed in popup when user has the option to load unsaved changes. \n is a placeholder for a new line, and the two %@ are placeholders for the date of last save on this device, and date of last autosave on another device, respectively."), saveDateFormatted, autosaveDateFormatted) let loadSaveButtonTitle = NSLocalizedString("From this device", comment: "Button title displayed in popup indicating date of change on device") let fromAutosaveButtonTitle = NSLocalizedString("From another device", comment: "Button title displayed in popup indicating date of change on another device") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: loadSaveButtonTitle, style: .default) { _ in didTapOption(false) }) alertController.addAction(UIAlertAction(title: fromAutosaveButtonTitle, style: .default) { _ in didTapOption(true) }) alertController.view.accessibilityIdentifier = "autosave-options-alert" return alertController } /// A dialog giving the user the choice between copying the current version of the post or resolving conflicts with edit. private static func copyConflictsResolutionViewController(didTapOption: @escaping (_ copyLocal: Bool, _ cancel: Bool) -> Void) -> UIAlertController { let title = NSLocalizedString("Post sync conflict", comment: "Title displayed in popup when user tries to copy a post with unsaved changes") let message = NSLocalizedString("The post you are trying to copy has two versions that are in conflict or you recently made changes but didn\'t save them.\nEdit the post first to resolve any conflict or proceed with copying the version from this app.", comment: "Message displayed in popup when user tries to copy a post with conflicts") let editFirstButtonTitle = NSLocalizedString("Edit the post first", comment: "Button title displayed in popup indicating that the user edits the post first") let copyLocalButtonTitle = NSLocalizedString("Copy the version from this app", comment: "Button title displayed in popup indicating the user copied the local copy") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel button.") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: editFirstButtonTitle, style: .default) { _ in didTapOption(false, false) }) alertController.addAction(UIAlertAction(title: copyLocalButtonTitle, style: .default) { _ in didTapOption(true, false) }) alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel) { _ in didTapOption(false, true) }) alertController.view.accessibilityIdentifier = "copy-version-conflict-alert" return alertController } }
gpl-2.0
a1e9acfce142ac754d3b452e31e27ac4
55.659574
516
0.716485
5.197788
false
false
false
false
harlanhaskins/swift
test/Driver/PrivateDependencies/private-after-fine.swift
1
3168
/// a --> b ==> c | a ==> d | e ==> b | f ==> g /// a --> b ==> c | a ==> d +==> e +==> b, e --> f ==> g // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/private-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./g.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/private-after-fine/*.swiftdeps %t // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./g.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-INITIAL %s // CHECK-INITIAL-NOT: warning // CHECK-INITIAL-NOT: Handled // RUN: touch -t 201401240006 %t/a.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./g.swift -module-name main -j1 -v > %t/a.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=CHECK-A-NEG %s < %t/a.txt // CHECK-A: Handled a.swift // CHECK-A-DAG: Handled b.swift // CHECK-A-DAG: Handled d.swift // CHECK-A: Handled e.swift // CHECK-A-DAG: Handled c.swift // CHECK-A-DAG: Handled f.swift // CHECK-A-NEG-NOT: Handled g.swift // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/private-after-fine/* %t // RUN: touch -t 201401240005 %t/*.swift // Generate the build record... // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./g.swift -module-name main -j1 -v // ...then reset the .swiftdeps files. // RUN: cp -r %S/Inputs/private-after-fine/*.swiftdeps %t // RUN: touch -t 201401240006 %t/f.swift // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./b.swift ./c.swift ./d.swift ./e.swift ./f.swift ./g.swift -module-name main -j1 -v > %t/f.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-F %s < %t/f.txt // RUN: %FileCheck -check-prefix=CHECK-F-NEG %s < %t/f.txt // CHECK-F: Handled f.swift // CHECK-F: Handled g.swift // CHECK-F-NEG-NOT: Handled a.swift // CHECK-F-NEG-NOT: Handled b.swift // CHECK-F-NEG-NOT: Handled c.swift // CHECK-F-NEG-NOT: Handled d.swift // CHECK-F-NEG-NOT: Handled e.swift
apache-2.0
d86eed3f9b5bc1a263a2e46af4760d47
57.666667
376
0.677715
2.919816
false
false
true
false
society2012/PGDBK
PGDBK/PGDBK/Code/Member/Controller/LoginViewController.swift
1
3685
// // LoginViewController.swift // PGDBK // // Created by hupeng on 2017/7/5. // Copyright © 2017年 m.zintao. All rights reserved. // import UIKit import SVProgressHUD class LoginViewController: BaseViewController { @IBOutlet var passwordFild: UITextField! @IBOutlet var userNameFild: UITextField! override func viewDidLoad() { super.viewDidLoad() self.title = "注册" let name = UserDefaults.standard.object(forKey: "userName") as?String let pwd = UserDefaults.standard.object(forKey: "passWord") as?String self.userNameFild.text = name self.passwordFild.text = pwd } @IBAction func registerBtnAction(_ sender: UIButton) { let registerVC = RegisterViewController(nibName: "RegisterViewController", bundle: nil) self.navigationController?.pushViewController(registerVC, animated: true) } @IBAction func loginBtnAction(_ sender: UIButton) { if(self.userNameFild.text == nil || self.userNameFild.text == ""){ SVProgressHUD.showError(withStatus: "用户名不能为空") return } if(self.passwordFild.text == nil || self.passwordFild.text == ""){ SVProgressHUD.showError(withStatus: "密码不能为空") return } goLogin() } func goLogin() -> Void { SVProgressHUD.show(withStatus: "登录中") SVProgressHUD.setDefaultStyle(.dark) let url = SERVER_IP + "/index.php/api/AppInterface/loginApp" let parmertas = ["username":self.userNameFild.text!,"password":self.passwordFild.text!] NetWorkTools.requestData(URLString: url, type: .post, parmertas: parmertas) { (response) in SVProgressHUD.dismiss() guard let dic = response as? [String:Any] else{return} let data = dic["data"] as?[String:Any] let code = dic["code"] as?Int let message = dic["message"] as?String if(code == 200){ let id = data?["id"] as?String UserDefaults.standard.set(id, forKey: "userId") UserDefaults.standard.set(self.userNameFild.text, forKey: "userName") UserDefaults.standard.set(self.passwordFild.text, forKey: "passWord") NotificationCenter.default.post(name: NSNotification.Name("loginSuccess"), object: id) self.navigationController?.popViewController(animated: true) }else{ SVProgressHUD.showError(withStatus: message) } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let first = (touches as NSSet).allObjects.first as!UITouch if(first.tapCount == 1){ self.view.endEditing(true) } // for touch: AnyObject in touches{ // let tap:UITouch = touch as! UITouch // if(tap.tapCount == 1){ // self.view.endEditing(true) // } // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
a7b71e151eb3b3577faa679bd424af57
30.431034
106
0.593527
4.644586
false
false
false
false
devxoul/Bagel
Bagel/Converter.swift
1
2932
// // Copyright (c) 2015 Suyeol Jeon (http://xoul.kr) // // 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 2 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, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // import Cocoa public func convert(path: String, completion: (String? -> Void)? = nil) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let giffile = _convert(path) dispatch_async(dispatch_get_main_queue()) { completion?(giffile) } } } private func _convert(path: String) -> String? { guard let ffmpeg = NSBundle.mainBundle().pathForResource("ffmpeg", ofType: nil) else { return nil } guard let convert = NSBundle.mainBundle().pathForResource("convert", ofType: nil) else { return nil } guard let gifsicle = NSBundle.mainBundle().pathForResource("gifsicle", ofType: nil) else { return nil } let filename = path.lastPathComponent.stringByDeletingPathExtension let tempDir = NSTemporaryDirectory().stringByAppendingPathComponent(filename) let target = path.stringByDeletingPathExtension + ".gif" NSLog("filename: \(filename)") NSLog("tempDir: \(tempDir)") NSLog("target: \(target)") let fileManager = NSFileManager.defaultManager() defer { NSLog("Removing '\(tempDir)'...") do { try fileManager.removeItemAtPath(tempDir) } catch _ {} } NSLog("Removing '\(tempDir)'...") do { try fileManager.removeItemAtPath(tempDir) } catch _ {} NSLog("Creating '\(tempDir)'...") do { try fileManager.createDirectoryAtPath(tempDir, withIntermediateDirectories: true, attributes: nil) } catch _ { return nil } NSLog("Mapping...") if sh("\(ffmpeg) -i \(path) -r 30 -vcodec png \(tempDir)/out-static-%05d.png") != 0 { return nil } NSLog("Reducing...") if sh("time \(convert) -verbose +dither -layers Optimize -resize 600x600\\> \(tempDir)/out-static*.png GIF:-" + " | \(gifsicle) --colors 256 --loop --optimize=3 --delay 3 --multifile - > \(target)") != 0 { return nil } return target } private func sh(command: String) -> Int32 { NSLog(command) let task = NSTask.launchedTaskWithLaunchPath("/bin/sh", arguments: ["-c", command]) task.waitUntilExit() return task.terminationStatus }
gpl-2.0
eaccaf35f40a63f4e4e68c5c0a97ccd1
34.756098
115
0.664052
4.200573
false
false
false
false
korgx9/QRCodeReader.swift
Sources/QRCodeReaderViewControllerBuilder.swift
1
3312
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation /** The QRCodeViewControllerBuilder aims to create a simple configuration object for the QRCode view controller. */ public final class QRCodeReaderViewControllerBuilder { // MARK: - Configuring the QRCodeViewController Objects /** The builder block. The block gives a reference of builder you can configure. */ public typealias QRCodeReaderViewControllerBuilderBlock = (QRCodeReaderViewControllerBuilder) -> Void /** The title to use for the cancel button. */ public var cancelButtonTitle = "Cancel" /** The code reader object used to scan the bar code. */ public var reader = QRCodeReader() /** The reader container view used to display the video capture and the UI components. */ public var readerView = QRCodeReaderContainer(displayable: QRCodeReaderView()) /** Flag to know whether the view controller start scanning the codes when the view will appear. */ public var startScanningAtLoad = true /** Flag to display the cancel button. */ public var showCancelButton = true /** Flag to display the switch camera button. */ public var showSwitchCameraButton = true /** Flag to display the toggle torch button. If the value is true and there is no torch the button will not be displayed. */ public var showTorchButton = false /** Flag to display the guide view. */ public var showOverlayView = true /** Flag to display the guide view. */ public var showInformationLabel = true /** Flag to display the guide view. */ public var handleOrientationChange = true /** The title to use for the cancel button. */ public var informationLabelText: String? = nil // MARK: - Initializing a Flap View /** Initialize a QRCodeViewController builder with default values. */ public init() {} /** Initialize a QRCodeReaderViewController builder with default values. - parameter buildBlock: A QRCodeReaderViewController builder block to configure itself. */ public init(buildBlock: QRCodeReaderViewControllerBuilderBlock) { buildBlock(self) } }
mit
56b0820e73023a1fc2bc0f3acd7d80e0
28.571429
120
0.727959
4.965517
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/CanonicalDealerCategory.swift
1
1317
/// Describes a well-defined Dealer category within the model. public enum CanonicalDealerCategory: CaseIterable, Equatable, Hashable, Identifiable { public var id: some Hashable { self } /// The category has no local canonical meaning. This is a signal the remote has added a new category /// the current model cannot process. case unknown /// The dealer offers printed material. case prints /// The dealer offers fursuit wares, e.g. accessories, parts or commissions. case fursuits /// The dealer is taking commissions. case commissions /// The dealer offers artwork. case artwork /// The dealer offers miscellaneous, uncategorised wares. case miscellaneous init(categoryName: String) { let lowercasedCategoryName = categoryName.lowercased() switch lowercasedCategoryName { case "prints": self = .prints case "fursuits": self = .fursuits case "commissions": self = .commissions case "artwork": self = .artwork case "miscellaneous": self = .miscellaneous default: self = .unknown } } }
mit
38a075ce75da64a8f0a6c89e9a1de172
25.34
105
0.578588
5.51046
false
false
false
false
robhortn/iOS-study
iOS10Swift3Book/chp10/classes.playground/Contents.swift
1
758
//: Playground - noun: a place where people can play import UIKit class Vehicle { var tires = 4 var headlights = 2 var horsepower = 468 var model = "" func drive() { // Accelerate! } func brake() { // Stop this crazy thing! } func passByReference(vehicle: Vehicle) { vehicle.model = "Cheese" } } let delorean = Vehicle() delorean.model = "DMC-12" let bmw = Vehicle() bmw.model = "328i" let ford = Vehicle() ford.model = "F-150" print(ford.model) ford.passByReference(vehicle: ford) print(ford.model) var someonesAge = 20 func passByVal(age: Int) { //age = 10 // This is NOT allowed because age is defined as a 'let constant' and cannot be changed. }
gpl-3.0
f2e8fa9c8727ec69c4251b479b1b1ece
14.469388
104
0.604222
3.324561
false
false
false
false
mrdepth/EVEOnlineAPI
EVEAPI/EVEAPI/EVEConquerableStationList.swift
1
1965
// // EVEConquerableStationList.swift // EVEAPI // // Created by Artem Shimanski on 30.11.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit public class EVEConquerableStationListItem: EVEObject { public var stationID: Int = 0 public var stationName: String = "" public var stationTypeID: Int = 0 public var solarSystemID: Int = 0 public var corporationID: Int = 0 public var corporationName: String = "" public var x: Double = 0 public var y: Double = 0 public var z: Double = 0 public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "stationID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "stationName":EVESchemeElementType.String(elementName:nil, transformer:nil), "stationTypeID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "solarSystemID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "corporationID":EVESchemeElementType.Int(elementName:nil, transformer:nil), "corporationName":EVESchemeElementType.String(elementName:nil, transformer:nil), "x":EVESchemeElementType.Double(elementName:nil, transformer:nil), "y":EVESchemeElementType.Double(elementName:nil, transformer:nil), "z":EVESchemeElementType.Double(elementName:nil, transformer:nil), ] } } public class EVEConquerableStationList: EVEResult { public var outposts: [EVEConquerableStationListItem] = [] public required init?(dictionary:[String:Any]) { super.init(dictionary: dictionary) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func scheme() -> [String:EVESchemeElementType] { return [ "outposts":EVESchemeElementType.Rowset(elementName: nil, type: EVEConquerableStationListItem.self, transformer: nil) ] } }
mit
a6e3fdbc1eee57061bb1e90a6a9ce849
30.174603
119
0.755092
3.740952
false
false
false
false
SuPair/firefox-ios
Shared/KeyboardHelper.swift
4
4964
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit /** * The keyboard state at the time of notification. */ public struct KeyboardState { public let animationDuration: Double public let animationCurve: UIViewAnimationCurve private let userInfo: [AnyHashable: Any] fileprivate init(_ userInfo: [AnyHashable: Any]) { self.userInfo = userInfo animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! Double // HACK: UIViewAnimationCurve doesn't expose the keyboard animation used (curveValue = 7), // so UIViewAnimationCurve(rawValue: curveValue) returns nil. As a workaround, get a // reference to an EaseIn curve, then change the underlying pointer data with that ref. var curve = UIViewAnimationCurve.easeIn if let curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? Int { NSNumber(value: curveValue as Int).getValue(&curve) } self.animationCurve = curve } /// Return the height of the keyboard that overlaps with the specified view. This is more /// accurate than simply using the height of UIKeyboardFrameBeginUserInfoKey since for example /// on iPad the overlap may be partial or if an external keyboard is attached, the intersection /// height will be zero. (Even if the height of the *invisible* keyboard will look normal!) public func intersectionHeightForView(_ view: UIView) -> CGFloat { if let keyboardFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let keyboardFrame = keyboardFrameValue.cgRectValue let convertedKeyboardFrame = view.convert(keyboardFrame, from: nil) let intersection = convertedKeyboardFrame.intersection(view.bounds) return intersection.size.height } return 0 } } public protocol KeyboardHelperDelegate: AnyObject { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) } /** * Convenience class for observing keyboard state. */ open class KeyboardHelper: NSObject { open var currentState: KeyboardState? fileprivate var delegates = [WeakKeyboardDelegate]() open class var defaultHelper: KeyboardHelper { struct Singleton { static let instance = KeyboardHelper() } return Singleton.instance } /** * Starts monitoring the keyboard state. */ open func startObserving() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** * Adds a delegate to the helper. * Delegates are weakly held. */ open func addDelegate(_ delegate: KeyboardHelperDelegate) { // Reuse any existing slots that have been deallocated. for weakDelegate in delegates where weakDelegate.delegate == nil { weakDelegate.delegate = delegate return } delegates.append(WeakKeyboardDelegate(delegate)) } @objc func keyboardWillShow(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardWillShowWithState: currentState!) } } } @objc func keyboardDidShow(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardDidShowWithState: currentState!) } } } @objc func keyboardWillHide(_ notification: Notification) { if let userInfo = notification.userInfo { currentState = KeyboardState(userInfo) for weakDelegate in delegates { weakDelegate.delegate?.keyboardHelper(self, keyboardWillHideWithState: currentState!) } } } } private class WeakKeyboardDelegate { weak var delegate: KeyboardHelperDelegate? init(_ delegate: KeyboardHelperDelegate) { self.delegate = delegate } }
mpl-2.0
3014fe6b89e9c5ab96bbe00a27f025c8
38.712
131
0.693594
5.602709
false
false
false
false
ricardopereira/Playgrounds
Random.playground/Contents.swift
1
4201
//: Playground - noun: a place where people can play import UIKit import XCPlayground let array = [12,3,1,4,1,2,3,5] let zipped = zip(array, 0..<array.count) let smallerNumber = zipped.sort { $0.0 < $1.0}.first.map { $0.0 } smallerNumber let minIndex = zip(array, array.indices).minElement{ $0.0 < $1.0 }.map { $0.1 } array[minIndex!] // Dictionaries union let moreAttributes: [String:AnyObject] = ["Function":"authenticate"] let attributes: [String:AnyObject] = ["File":"Auth.swift"] func + <K,V> (left: Dictionary<K,V>, right: Dictionary<K,V>?) -> Dictionary<K,V> { guard let right = right else { return left } return left.reduce(right) { var new = $0 as [K:V] new.updateValue($1.1, forKey: $1.0) return new } } attributes + moreAttributes + nil attributes + moreAttributes attributes + nil func += <K,V> (inout left: Dictionary<K,V>, right: Dictionary<K,V>?) { guard let right = right else { return } right.forEach { key, value in left.updateValue(value, forKey: key) } } let b: [String:AnyObject] = ["Function":"authenticate"] var a: [String:AnyObject] = ["File":"Auth.swift"] a += nil a += b enum DialogFilterOptions { case Today case Yesterday case LastWeek case LastMonth case Custom var toString: String { switch self { case .Today: return "Hoje" case .Yesterday: return "Yesterday" case .LastWeek: return "Week" case .LastMonth: return "Month" case .Custom: return "Custom" } } } extension DialogFilterOptions: CustomStringConvertible { var description: String { switch self { case .Today: return "Today" case .Yesterday: return "Yesterday" case .LastWeek: return "LastWeek" case .LastMonth: return "LastMonth" case .Custom: return "Custom" } } } extension DialogFilterOptions: RawRepresentable { init?(rawValue: Int) { switch rawValue { case 1: self = .Today case 2: self = .Yesterday case 3: self = .LastWeek case 4: self = .LastMonth case 0: self = .Custom default: return nil } } var rawValue: Int { switch self { case .Today: return 1 case .Yesterday: return 2 case .LastWeek: return 3 case .LastMonth: return 4 case .Custom: return 0 } } } DialogFilterOptions(rawValue: 1)?.rawValue DialogFilterOptions(rawValue: 0) DialogFilterOptions(rawValue: 123) String(DialogFilterOptions.Today) let oldSchemaVersion = 1 switch oldSchemaVersion { case 1 ..< 2: print("Do 1") fallthrough case 2 ..< 3: print("Do 2") fallthrough default: break } func pow2(radix: Int, _ power: Int) -> Double { return pow(Double(radix), Double(power)) } var decimals = 2 var fraction = true let digits: [Int] = [6,7,9] let d = digits.map { Double($0) } var number = 0.0 for var i = d.count-1, x = 0; i>=0; i-- { if fraction { number += d[i] * 1.0 / pow2(10, decimals - x++) } else { number += d[i] * 1.0 * pow2(10, decimals - x--) } if decimals - x == 0 { fraction = false } } number fraction = false number = 0.0 for (index, value) in (digits.map{ Double($0) }).enumerate() { let reversedIndex = digits.count - index if fraction { number += value * 1.0 / pow2(10, reversedIndex - 1 + decimals) } else { number += value * 1.0 * pow2(10, reversedIndex - 1 - decimals) } if reversedIndex - decimals == 0 { fraction = true } } number class Item { var name: String = "" init(name: String) { self.name = name } } class Collection { var dictionary = NSMutableDictionary() func add(name: String) -> Item { dictionary[name] = Item(name: name) return dictionary[name] as! Item } func release(item: Item) { dictionary.removeObjectForKey(item.name) } } let items = Collection() weak var item1: Item! = items.add("asjflkajsdf") print(item1.name) items.release(item1) print(item1.name)
mit
c022ef201930ab3f1e2401979d554bbb
19.900498
82
0.593192
3.545148
false
false
false
false
bfortunato/aj-framework
platforms/ios/Libs/ApplicaFramework/ApplicaFramework/AFEvent.swift
1
749
// // AFEvent.swift // ApplicaFramework // // Created by Bruno Fortunato on 08/03/16. // Copyright © 2016 Bruno Fortunato. All rights reserved. // import UIKit open class AFEvent { public typealias Callback = ((_ sender: AnyObject, _ params:[String: Any]?) -> Void) public init() { } var callbacks:[Callback] = [] open func add(callback:@escaping Callback) { callbacks.append(callback) } open func invoke(sender: AnyObject, params:[String: Any]? = nil) { for c in callbacks { c(sender, params) } } open func clear() { callbacks = [] } } public func += (left: inout AFEvent, right: @escaping AFEvent.Callback) { left.add(callback: right) }
apache-2.0
ddb95eda1fd0cc955e40f756e7122be8
19.216216
88
0.596257
3.796954
false
false
false
false
knomi/Allsorts
Allsorts/Ended.swift
1
2021
// // Ended.swift // Allsorts // // Copyright (c) 2015 Pyry Jahkola. All rights reserved. // /// Orderable value `T` augmented with an upper bound `.end`. An `Ended<T>` is /// structurally equivalent to `Optional<T>` but flips the ordering of the /// `Optional.Some(T)` (~ `Ended.value(T)`) and the `Optional.None` (~ /// `Ended.end`) cases such that `.value(x)` compares less than `.end`. public enum Ended<T : Orderable> : Orderable, Comparable { case value(T) case end public init() { self = .end } public init(_ value: T?) { self = value.map {x in .value(x)} ?? .end } public var value: T? { switch self { case let .value(x): return .some(x) case .end: return .none } } public func map<U>(_ f: (T) -> U) -> Ended<U> { switch self { case let .value(x): return .value(f(x)) case .end: return .end } } public func flatMap<U>(_ f: (T) -> Ended<U>) -> Ended<U> { switch self { case let .value(x): return f(x) case .end: return .end } } } extension Ended : CustomStringConvertible { public var description: String { switch self { case let .value(x): return "value(\(String(reflecting: x)))" case .end: return "end" } } } extension Ended : CustomDebugStringConvertible { public var debugDescription: String { switch self { case let .value(x): return "Ended.value(\(String(reflecting: x)))" case .end: return "Ended.end" } } } /// Ordering based on `a <=> b == .value(a) <=> .value(b)` and /// `.value(_) < .end`. public func <=> <T>(a: Ended<T>, b: Ended<T>) -> Ordering { switch (a, b) { case let (.value(a), .value(b)): return a <=> b case (.value, .end ): return .less case (.end, .end ): return .equal case (.end, .value ): return .greater } }
mit
68f9ab3669fe8448e623350e6376f560
26.684932
78
0.520534
3.520906
false
false
false
false
apple/swift
test/StringProcessing/Runtime/regex_basic.swift
8
1789
// RUN: %target-run-simple-swift(-Xfrontend -enable-bare-slash-regex) // REQUIRES: swift_in_compiler,string_processing,executable_test import StdlibUnittest var RegexBasicTests = TestSuite("RegexBasic") extension String { @available(SwiftStdlib 5.7, *) func expectMatch<T>( _ regex: Regex<T>, file: String = #file, line: UInt = #line ) -> Regex<T>.Match { guard let result = wholeMatch(of: regex) else { expectUnreachable("Failed match", file: file, line: line) fatalError() } return result } } RegexBasicTests.test("Basic") { guard #available(SwiftStdlib 5.7, *) else { return } let input = "aabccd" let match1 = input.expectMatch(#/aabcc./#) expectEqual("aabccd", match1.0) expectTrue("aabccd" == match1.output) let match2 = input.expectMatch(#/a*b.+./#) expectEqual("aabccd", match2.0) expectTrue("aabccd" == match2.output) } RegexBasicTests.test("Modern") { guard #available(SwiftStdlib 5.7, *) else { return } let input = "aabccd" let match1 = input.expectMatch(#/ a a bc c (?#hello) . # comment /#) expectEqual("aabccd", match1.0) expectTrue("aabccd" == match1.output) } RegexBasicTests.test("Captures") { guard #available(SwiftStdlib 5.7, *) else { return } let input = """ A6F0..A6F1 ; Extend # Mn [2] BAMUM COMBINING MARK KOQNDON..BAMUM \ COMBINING MARK TUKWENTIS """ let regex = #/([0-9A-F]+)(?:\.\.([0-9A-F]+))?\s+;\s+(\w+).*/# // Test inferred type. let _: Regex<(Substring, Substring, Substring?, Substring)>.Type = type(of: regex) let match1 = input.expectMatch(regex) expectEqual(input[...], match1.0) expectTrue(input == match1.0) expectTrue("A6F0" == match1.1) expectTrue("A6F1" == match1.2) expectTrue("Extend" == match1.3) } runAllTests()
apache-2.0
138753c03076a1eae278c1856e11e880
26.106061
75
0.646171
3.155203
false
true
false
false
luckymore0520/GreenTea
Loyalty/LoginAndRegister/Model/UserInfoManager.swift
1
3155
// // UserInfoManager.swift // Loyalty // // Created by WangKun on 16/1/28. // Copyright © 2016年 WangKun. All rights reserved. // import Foundation import AVOSCloud let kLimitVerifySeconds = 60 class UserInfoManager { private static let sharedInstance = UserInfoManager() var savedPhoneNumber:String? var verifyRemainTime:Int = kLimitVerifySeconds var user:User? class var sharedManager : UserInfoManager { return sharedInstance } var currentUser:User? { if self.isLogin { if self.user == nil { user = User.currentMyUser() } return user } return nil } var isLogin:Bool { if let user = User.currentUser() { return user.isAuthenticated() } else { return false } } func login(phone:String,password:String,completionHandler: (result:Bool, errorMsg:String?) -> Void ) { User.logInWithUsernameInBackground(phone, password: password) { (user, error) -> Void in completionHandler(result: user != nil , errorMsg: NSError.errorMsg(error)) if user != nil { User.changeCurrentUser(user, save: true) } } } func logout(){ User.logOut() } func register(phone:String,password:String,code:String,completionHandler: (result:Bool, errorMsg:String?) -> Void ) { self.verifySMSCode(phone, code: code) { (result, errorMsg) -> Void in if result { let user = User.init() user.username = phone user.password = password user.userTypeString = "Custume" user.signUpInBackgroundWithBlock({ (success, error) -> Void in completionHandler(result: success, errorMsg: error == nil ? "" : error.localizedDescription) }) } else { completionHandler(result: result, errorMsg:errorMsg) } } } func requestSMSCode(phone:String, completionHandler: (result:Bool, errorMsg:String?) -> Void) { AVOSCloud.requestSmsCodeWithPhoneNumber(phone, appName: "绿茶", operation: "注册", timeToLive: 10) { (success, error) -> Void in completionHandler(result: success, errorMsg: error == nil ? "" : error.localizedDescription) } } func verifySMSCode(phone:String, code:String, completionHandler: (result:Bool, errorMsg:String?) -> Void) { AVOSCloud.verifySmsCode(code, mobilePhoneNumber: phone) { (success, error) -> Void in completionHandler(result: success, errorMsg: error == nil ? "" : error.localizedDescription) } } } // MARK: - Code Timer extension UserInfoManager { func countDown()->Int { self.verifyRemainTime -= 1 if (self.verifyRemainTime <= 0) { self.verifyRemainTime = kLimitVerifySeconds return 0 } return self.verifyRemainTime } func shouldContinueCountDown()->Bool { return self.verifyRemainTime != kLimitVerifySeconds } }
mit
baee06a13592c0ecc7039b0493cec264
31.42268
132
0.594784
4.603221
false
false
false
false
zixun/GodEye
GodEye/Classes/Main/View/Monitor/MonitorBaseView.swift
1
4021
// // MonitorPercentView.swift // Pods // // Created by zixun on 17/1/5. // // import Foundation enum MonitorBaseViewPosition { case left case right } class MonitorBaseView: UIButton { var position:MonitorBaseViewPosition = .left var firstRow:Bool = true private(set) var type: MonitorSystemType! init(type:MonitorSystemType) { super.init(frame: CGRect.zero) self.type = type self.infoLabel.text = type.info self.contentLabel.text = type.initialValue self.backgroundColor = UIColor.clear self.addSubview(self.rightLine) self.addSubview(self.topLine) self.addSubview(self.infoLabel) self.addSubview(self.contentLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() var rect = self.bounds rect.origin.x = rect.size.width - 0.5 rect.size.width = 0.5 rect.origin.y = 20 rect.size.height -= rect.origin.y * 2 self.rightLine.frame = self.position == .left ? rect : CGRect.zero rect.origin.x = self.position == .left ? 20 : (self.firstRow ? 0 : 20) rect.origin.y = 0 rect.size.width = self.frame.size.width - (self.firstRow ? 20 : 40) rect.size.height = 0.5 self.topLine.frame = rect rect.size.height = 50 rect.origin.x = 20 rect.size.width = self.frame.size.width - rect.origin.x - 20 rect.origin.y = (self.frame.size.height - rect.size.height) / 2 self.contentLabel.frame = rect rect.origin.x = 20 rect.origin.y = 10 rect.size.width = self.frame.size.width - 20 rect.size.height = 12 self.infoLabel.frame = rect } fileprivate lazy var contentLabel: UILabel = { let new = UILabel() new.text = "Unknow" new.textColor = UIColor.white new.textAlignment = .right new.numberOfLines = 0 new.font = UIFont(name: "HelveticaNeue-UltraLight", size: 32) return new }() private(set) lazy var infoLabel: UILabel = { let new = UILabel() new.font = UIFont.systemFont(ofSize: 12) new.textColor = UIColor.white return new }() private lazy var rightLine: UIView = { let new = UIView() new.backgroundColor = UIColor.white return new }() private lazy var topLine: UIView = { let new = UIView() new.backgroundColor = UIColor.white return new }() } // MARK: - Tool extension MonitorBaseView { fileprivate func attributes(size:CGFloat) -> [NSAttributedString.Key : Any] { return [NSAttributedString.Key.font:UIFont(name: "HelveticaNeue-UltraLight", size: size), NSAttributedString.Key.foregroundColor:UIColor.white] } fileprivate func contentString(_ string:String,unit:String) -> NSAttributedString { let result = NSMutableAttributedString() result.append(NSAttributedString(string: string, attributes: self.attributes(size: 32))) result.append(NSAttributedString(string: unit, attributes: self.attributes(size: 16))) return result } } // MARK: - Byte extension MonitorBaseView { func configure(byte:Double) { let str = byte.storageCapacity() self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", str.capacity), unit: str.unit) } } // MARK: - Percent extension MonitorBaseView { func configure(percent:Double) { self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", percent), unit: "%") } } extension MonitorBaseView { func configure(fps: Double) { self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", fps), unit: "FPS") } }
mit
e417deaf1fb5db59e982fcb0ec112969
27.721429
120
0.614275
4.197286
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Input/Photos/Photo/PhotosInputCellProvider.swift
1
5691
/* 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. */ import UIKit protocol PhotosInputCellProviderProtocol: AnyObject { func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell func configureFullImageLoadingIndicator(at indexPath: IndexPath, request: PhotosInputDataProviderImageRequestProtocol) } final class PhotosInputCellProvider: PhotosInputCellProviderProtocol { private let reuseIdentifier = "PhotosCellProvider" private let collectionView: UICollectionView private let dataProvider: PhotosInputDataProviderProtocol init(collectionView: UICollectionView, dataProvider: PhotosInputDataProviderProtocol) { self.dataProvider = dataProvider self.collectionView = collectionView self.collectionView.register(PhotosInputCell.self, forCellWithReuseIdentifier: self.reuseIdentifier) } func cellForItem(at indexPath: IndexPath) -> UICollectionViewCell { let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) as! PhotosInputCell self.configureCell(cell, at: indexPath) return cell } func configureFullImageLoadingIndicator(at indexPath: IndexPath, request: PhotosInputDataProviderImageRequestProtocol) { guard let cell = self.collectionView.cellForItem(at: indexPath) as? PhotosInputCell else { return } self.configureCellForFullImageLoadingIfNeeded(cell, request: request) } private var previewRequests = [Int: PhotosInputDataProviderImageRequestProtocol]() private var fullImageRequests = [Int: PhotosInputDataProviderImageRequestProtocol]() private func configureCell(_ cell: PhotosInputCell, at indexPath: IndexPath) { if let request = self.previewRequests[cell.hash] { self.previewRequests[cell.hash] = nil request.cancel() } self.fullImageRequests[cell.hash] = nil let index = indexPath.item - 1 let targetSize: CGSize = { let maxScale: CGFloat = 2 // This constant is a heuristically chosen compromise between photo quality and memory consumption. let side = max(cell.bounds.size.width, cell.bounds.size.height) * min(UIScreen.main.scale, maxScale) return CGSize(width: side, height: side) }() var imageProvidedSynchronously = true var requestId: Int32 = -1 let request = self.dataProvider.requestPreviewImage(at: index, targetSize: targetSize) { [weak self, weak cell] result in guard let sSelf = self, let sCell = cell else { return } // We can get here even after calling cancelPreviewImageRequest (looks like a race condition in PHImageManager) // Also, according to PHImageManager's documentation, this block can be called several times: we may receive an image with a low quality and then receive an update with a better one // This can also be called before returning from requestPreviewImage (synchronously) if the image is cached by PHImageManager let imageIsForThisCell = imageProvidedSynchronously || sSelf.previewRequests[sCell.hash]?.requestId == requestId if imageIsForThisCell { sCell.image = result.image sSelf.previewRequests[sCell.hash] = nil } } requestId = request.requestId imageProvidedSynchronously = false self.previewRequests[cell.hash] = request if let fullImageRequest = self.dataProvider.fullImageRequest(at: index) { self.configureCellForFullImageLoadingIfNeeded(cell, request: fullImageRequest) } } private func configureCellForFullImageLoadingIfNeeded(_ cell: PhotosInputCell, request: PhotosInputDataProviderImageRequestProtocol) { guard request.progress < 1 else { return } cell.showProgressView() cell.updateProgress(CGFloat(request.progress)) request.observeProgress(with: { [weak self, weak cell, weak request] progress in guard let sSelf = self, let sCell = cell, sSelf.fullImageRequests[sCell.hash] === request else { return } cell?.updateProgress(CGFloat(progress)) }, completion: { [weak self, weak cell, weak request] _ in guard let sSelf = self, let sCell = cell, sSelf.fullImageRequests[sCell.hash] === request else { return } sCell.hideProgressView() sSelf.fullImageRequests[sCell.hash] = nil }) self.fullImageRequests[cell.hash] = request } }
mit
bad928e6e322e9d543f7ac4cee80fbe5
53.721154
193
0.714461
5.140921
false
true
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/View/CategoryTableViewCell.swift
1
1234
// // CategoryTableViewCell.swift // MT_iOS // // Created by CHEEBOW on 2015/06/08. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class CategoryTableViewCell: UITableViewCell { private var _object: Category? var object: Category? { set { self._object = newValue if newValue != nil { self.textLabel?.text = self._object!.label } else { self.textLabel?.text = "" } } get { return self._object } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func layoutSubviews() { super.layoutSubviews() let indentPoints = CGFloat(object!.level) * 20.0; self.contentView.frame = CGRectMake(indentPoints, self.contentView.frame.origin.y, self.contentView.frame.size.width - indentPoints, self.contentView.frame.size.height); } }
mit
c0df0bddadf841721a2595ea15c98e25
23.156863
63
0.568994
4.684411
false
false
false
false
Takanu/Pelican
Sources/Pelican/Session/Modules/API Request/Async/Async+Basic.swift
1
5319
// // MethodRequestAsync+Send.swift // Pelican // // Created by Ido Constantine on 18/03/2018. // import Foundation extension MethodRequestAsync { /** A basic function for testing authorisation tokens, that returns your bot as a user if successful. */ func getMe(callback: ((User?) -> ())? = nil) { let request = TelegramRequest.getMe() tag.sendAsyncRequest(request) { response in if callback != nil { callback!(MethodRequest.decodeResponse(response)) } } } /** Sends a text-based message to the chat linked to this session. */ public func sendMessage(_ message: String, markup: MarkupType?, chatID: String, parseMode: MessageParseMode = .markdown, replyID: Int = 0, disableWebPreview: Bool = false, disableNotification: Bool = false, callback: ((Message?) -> ())? = nil) { let request = TelegramRequest.sendMessage(chatID: chatID, text: message, markup: markup, parseMode: parseMode, disableWebPreview: disableWebPreview, disableNotification: disableNotification, replyMessageID: replyID) tag.sendAsyncRequest(request) { response in // Define the type we wish to decode and see if we can make it happen. let message: Message? if response != nil { message = MethodRequest.decodeResponse(response!) } else { message = nil } // If we have a callback, return whatever the result was. if callback != nil { callback!(message) } } } /** Forward a message of any kind. */ public func forwardMessage(toChatID: String, fromChatID: String, fromMessageID: Int, disableNotification: Bool = false, callback: ((Message?) -> ())? = nil) { let request = TelegramRequest.forwardMessage(toChatID: toChatID, fromChatID: fromChatID, fromMessageID: fromMessageID, disableNotification: disableNotification) tag.sendAsyncRequest(request) { response in if callback != nil { callback!(MethodRequest.decodeResponse(response)) } } } /** Sends and uploads a file as a message to the chat linked to this session, using a `MessageFile` type. */ public func sendFile(_ file: MessageFile, caption: String, markup: MarkupType?, chatID: String, replyID: Int = 0, disableNotification: Bool = false, callback: ((Message?) -> ())? = nil) { let request = TelegramRequest.sendFile(file: file, chatID: chatID, markup: markup, caption: caption, disableNotification: disableNotification, replyMessageID: replyID) // If we immediately fail to make the request, call the callback early. if request == nil { if callback != nil { callback!(nil) return } } tag.sendAsyncRequest(request!) { response in // If we have a callback, return whatever the result was. if callback != nil { callback!(MethodRequest.decodeResponse(response!)) } } } /** Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). - returns: True on success. */ public func sendChatAction(_ actionType: ChatAction, chatID: String, callback: ((Bool) -> ())? = nil) { let request = TelegramRequest.sendChatAction(action: actionType, chatID: chatID) tag.sendAsyncRequest(request) { response in // Define the type we wish to decode and see if we can make it happen. let returnValue: Bool returnValue = MethodRequest.decodeResponse(response!) ?? false // If we have a callback, return whatever the result was. if callback != nil { callback!(returnValue) } } } /** Returns a list of profile pictures for the specified user. */ public func getUserProfilePhotos(userID: String, offset: Int = 0, limit: Int = 100, callback: ((UserProfilePhotos?) -> ())? = nil) { let request = TelegramRequest.getUserProfilePhotos(userID: userID, offset: offset, limit: limit) tag.sendAsyncRequest(request) { response in if callback != nil { callback!(MethodRequest.decodeResponse(response)) } } } /** Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. */ public func getFile(fileID: String, callback: ((FileDownload?) -> ())? = nil) { let request = TelegramRequest.getFile(fileID: fileID) tag.sendAsyncRequest(request) { response in if callback != nil { callback!(MethodRequest.decodeResponse(response)) } } } }
mit
b8d5d8bc2f4975641973d535699a32b6
29.924419
227
0.632074
4.126455
false
false
false
false
cliqz-oss/jsengine
jsengine-ios/jsengine/ContentPolicyDetector.swift
1
4044
// // ContentPolicyDetector.swift // jsengine // // Created by Mahmoud Adam on 9/29/16. // Copyright © 2016 Cliqz GmbH. All rights reserved. // import Foundation import JavaScriptCore class ContentPolicyDetector { enum ContentType: Int { case Other = 1 case Script case Image case Stylesheet case Document = 6 case Subdocument case XMLHTTPRequest = 11 case Font = 14 } // MARK: reqular expressions private var RE_JS : NSRegularExpression? private var RE_CSS : NSRegularExpression? private var RE_IMAGE : NSRegularExpression? private var RE_FONT : NSRegularExpression? private var RE_HTML : NSRegularExpression? private var RE_JSON : NSRegularExpression? static let sharedInstance = ContentPolicyDetector() init () { do { try RE_JS = NSRegularExpression(pattern: "\\.js($|\\|?)", options: .CaseInsensitive) try RE_CSS = NSRegularExpression(pattern: "\\.css($|\\|?)", options: .CaseInsensitive) try RE_IMAGE = NSRegularExpression(pattern: "\\.(?:gif|png|jpe?g|bmp|ico)($|\\|?)", options: .CaseInsensitive) try RE_FONT = NSRegularExpression(pattern: "\\.(?:ttf|woff)($|\\|?)", options: .CaseInsensitive) try RE_HTML = NSRegularExpression(pattern: "\\.html?", options: .CaseInsensitive) try RE_JSON = NSRegularExpression(pattern: "\\.json($|\\|?)", options: .CaseInsensitive) } catch let error as NSError { print("Couldn't initialize regular expressions for detecting Content Policy because of the following error: \(error.description)") } } // MARK: - Public APIs func getContentPolicy(request: NSURLRequest, isMainDocument: Bool) -> Int { // set default value var contentPolicy : ContentType? // Check if the request is the Main Document if (isMainDocument) { contentPolicy = .Document } else if let acceptHeader = request.valueForHTTPHeaderField("Accept") { if acceptHeader.rangeOfString("text/css") != nil { contentPolicy = .Stylesheet } else if acceptHeader.rangeOfString("image/*") != nil || acceptHeader.rangeOfString("image/webp") != nil { contentPolicy = .Image } else if acceptHeader.rangeOfString("text/html") != nil { contentPolicy = .Subdocument } else { // decide based on the URL pattern contentPolicy = getContentPolicy(request.URL) } } else { // decide based on the URL pattern contentPolicy = getContentPolicy(request.URL) } return contentPolicy!.rawValue } // MARK: - Private helper methods private func getContentPolicy(url: NSURL?) -> ContentType { // set default value var contentPolicy: ContentType = .XMLHTTPRequest //return contentPolicy if let urlString = url?.absoluteString { let range = NSMakeRange(0, urlString.characters.count) if RE_JS?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Script } else if RE_CSS?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Stylesheet } else if RE_IMAGE?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Image } else if RE_FONT?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Font } else if RE_HTML?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Subdocument } else if RE_JSON?.numberOfMatchesInString(urlString, options: [], range: range) > 0 { contentPolicy = .Other } } return contentPolicy } }
mpl-2.0
5c300a8cd098faa4129fb248c3ea9082
39.43
142
0.598318
4.936508
false
false
false
false
xgdgsc/AlecrimCoreData
Source/AlecrimCoreData/Core/Structs/DataContextOptions.swift
1
7830
// // DataContextOptions.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 2015-02-26. // Copyright (c) 2015 Alecrim. All rights reserved. // import Foundation import CoreData public enum StoreType { case SQLite case InMemory } public struct DataContextOptions { // MARK: - options valid for all instances public static var defaultBatchSize: Int = 20 public static var defaultComparisonPredicateOptions: NSComparisonPredicateOptions = [.CaseInsensitivePredicateOption, .DiacriticInsensitivePredicateOption] @available(*, unavailable, renamed="defaultBatchSize") public static var batchSize: Int = 20 @available(*, unavailable, renamed="defaultComparisonPredicateOptions") public static var stringComparisonPredicateOptions: NSComparisonPredicateOptions = [.CaseInsensitivePredicateOption, .DiacriticInsensitivePredicateOption] // MARK: - public let managedObjectModelURL: NSURL? public let persistentStoreURL: NSURL? // MARK: - public var storeType: StoreType = .SQLite public var configuration: String? = nil public var options: [NSObject : AnyObject] = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true] // MARK: - THE constructor public init(managedObjectModelURL: NSURL, persistentStoreURL: NSURL) { self.managedObjectModelURL = managedObjectModelURL self.persistentStoreURL = persistentStoreURL } // MARK: - "convenience" initializers public init(managedObjectModelURL: NSURL) { let mainBundle = NSBundle.mainBundle() self.managedObjectModelURL = managedObjectModelURL self.persistentStoreURL = mainBundle.defaultPersistentStoreURL() } public init(persistentStoreURL: NSURL) { let mainBundle = NSBundle.mainBundle() self.managedObjectModelURL = mainBundle.defaultManagedObjectModelURL() self.persistentStoreURL = persistentStoreURL } public init() { let mainBundle = NSBundle.mainBundle() self.managedObjectModelURL = mainBundle.defaultManagedObjectModelURL() self.persistentStoreURL = mainBundle.defaultPersistentStoreURL() } // MARK: - public init(managedObjectModelBundle: NSBundle, managedObjectModelName: String, bundleIdentifier: String) { self.managedObjectModelURL = managedObjectModelBundle.managedObjectModelURLForManagedObjectModelName(managedObjectModelName) self.persistentStoreURL = managedObjectModelBundle.persistentStoreURLForManagedObjectModelName(managedObjectModelName, bundleIdentifier: bundleIdentifier) } /// Initializes ContextOptions with properties filled for use by main app and its extensions. /// /// - parameter managedObjectModelBundle: The managed object model bundle. You can use `NSBundle(forClass: MyModule.MyDataContext.self)`, for example. /// - parameter managedObjectModelName: The managed object model name without the extension. Example: `"MyGreatApp"`. /// - parameter bundleIdentifier: The bundle identifier for use when creating the directory for the persisent store. Example: `"com.mycompany.MyGreatApp"`. /// - parameter applicationGroupIdentifier: The application group identifier (see Xcode target settings). Example: `"group.com.mycompany.MyGreatApp"` for iOS or `"12ABCD3EF4.com.mycompany.MyGreatApp"` for OS X where `12ABCD3EF4` is your team identifier. /// /// - returns: An initialized ContextOptions with properties filled for use by main app and its extensions. public init(managedObjectModelBundle: NSBundle, managedObjectModelName: String, bundleIdentifier: String, applicationGroupIdentifier: String) { self.managedObjectModelURL = managedObjectModelBundle.managedObjectModelURLForManagedObjectModelName(managedObjectModelName) self.persistentStoreURL = managedObjectModelBundle.persistentStoreURLForManagedObjectModelName(managedObjectModelName, bundleIdentifier: bundleIdentifier, applicationGroupIdentifier: applicationGroupIdentifier) } } // MARK: - Ubiquity (iCloud) helpers extension DataContextOptions { #if os(OSX) || os(iOS) public var ubiquityEnabled: Bool { return self.storeType == .SQLite && self.options[NSPersistentStoreUbiquitousContainerIdentifierKey] != nil } public mutating func configureUbiquityWithContainerIdentifier(containerIdentifier: String, contentRelativePath: String = "Data/TransactionLogs", contentName: String = "UbiquityStore") { self.options[NSPersistentStoreUbiquitousContainerIdentifierKey] = containerIdentifier self.options[NSPersistentStoreUbiquitousContentURLKey] = contentRelativePath self.options[NSPersistentStoreUbiquitousContentNameKey] = contentName self.options[NSMigratePersistentStoresAutomaticallyOption] = true self.options[NSInferMappingModelAutomaticallyOption] = true } #endif } // MARK: - private NSBundle extensions extension NSBundle { private var bundleName: String? { return self.infoDictionary?[String(kCFBundleNameKey)] as? String } } extension NSBundle { private func defaultManagedObjectModelURL() -> NSURL? { if let managedObjectModelName = self.bundleName { return self.managedObjectModelURLForManagedObjectModelName(managedObjectModelName) } return nil } private func defaultPersistentStoreURL() -> NSURL? { if let managedObjectModelName = self.bundleName, let bundleIdentifier = self.bundleIdentifier { return self.persistentStoreURLForManagedObjectModelName(managedObjectModelName, bundleIdentifier: bundleIdentifier) } return nil } } extension NSBundle { private func managedObjectModelURLForManagedObjectModelName(managedObjectModelName: String) -> NSURL? { return self.URLForResource(managedObjectModelName, withExtension: "momd") } private func persistentStoreURLForManagedObjectModelName(managedObjectModelName: String, bundleIdentifier: String) -> NSURL? { if let applicationSupportURL = NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask).last { let url = applicationSupportURL .URLByAppendingPathComponent(bundleIdentifier, isDirectory: true) .URLByAppendingPathComponent("CoreData", isDirectory: true) .URLByAppendingPathComponent((managedObjectModelName as NSString).stringByAppendingPathExtension("sqlite")!, isDirectory: false) return url } return nil } private func persistentStoreURLForManagedObjectModelName(managedObjectModelName: String, bundleIdentifier: String, applicationGroupIdentifier: String) -> NSURL? { if let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(applicationGroupIdentifier) { let url = containerURL .URLByAppendingPathComponent("Library", isDirectory: true) .URLByAppendingPathComponent("Application Support", isDirectory: true) .URLByAppendingPathComponent(bundleIdentifier, isDirectory: true) .URLByAppendingPathComponent("CoreData", isDirectory: true) .URLByAppendingPathComponent((managedObjectModelName as NSString).stringByAppendingPathExtension("sqlite")!, isDirectory: false) return url } return nil } } // MARK: - @available(*, unavailable, renamed="DataContextOptions") public struct ContextOptions { }
mit
bc275b21373887b25bc422782bd074ba
40.871658
257
0.73014
5.977099
false
false
false
false
stomp1128/TIY-Assignments
37-VenueMenu/Venue.swift
1
3409
// // Venue.swift // 37-VenueMenu // // Created by Chris Stomp on 12/7/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import Foundation import CoreData import UIKit class Venue: NSManagedObject { // MARK: - Parse JSON static func searchResultsJSON(results: NSDictionary) -> [NSManagedObject] { var venueResults = [NSManagedObject]() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let venueArray = results.valueForKey("venues") as? NSArray for venue in venueArray! { //thanks RW: http://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial let venueEntity = NSEntityDescription.entityForName("Venue", inManagedObjectContext: managedObjectContext) let aVenue = Venue(entity: venueEntity!, insertIntoManagedObjectContext: nil) aVenue.setValue(venue.valueForKey("name") as? String ?? "", forKey: "name") let location = venue.valueForKey("location") as? NSDictionary aVenue.setValue(location?.valueForKey("address") as? String ?? "", forKey: "address") aVenue.setValue(0, forKey: "rating") aVenue.setValue(false, forKey: "userLike") aVenue.setValue(location?.valueForKey("lat") as? Double ?? 0.0, forKey: "lat") aVenue.setValue(location?.valueForKey("lng") as? Double ?? 0.0, forKey: "lng") do { try managedObjectContext.save() venueResults.append(aVenue) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } return venueResults } static func venueWithJSON(results: NSDictionary) -> [NSManagedObject] { var venueResults = [NSManagedObject]() let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let venueArray = results.valueForKey("venues") as? NSArray for venue in venueArray! { //thanks RW: http://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial let venueEntity = NSEntityDescription.entityForName("Venue", inManagedObjectContext: managedObjectContext) let aVenue = NSManagedObject(entity: venueEntity!, insertIntoManagedObjectContext: managedObjectContext) aVenue.setValue(venue.valueForKey("name") as? String, forKey: "name") let location = venue.valueForKey("location") as? NSDictionary aVenue.setValue(location?.valueForKey("address") as? String, forKey: "address") aVenue.setValue(0, forKey: "rating") aVenue.setValue(false, forKey: "userLike") aVenue.setValue(location?.valueForKey("lat") as? Double, forKey: "lat") aVenue.setValue(location?.valueForKey("lng") as? Double, forKey: "lng") do { try managedObjectContext.save() venueResults.append(aVenue) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } return venueResults } }
cc0-1.0
c484cc37d5ac11f959b2e3d9cb2dea6e
38.639535
118
0.605634
5.033973
false
false
false
false
zjjzmw1/speedxSwift
speedxSwift/speedxSwift/HomeViewController.swift
1
3427
// // HomeViewController.swift // swiftDemo1 // // Created by xiaoming on 16/3/7. // Copyright © 2016年 shandandan. All rights reserved. // import UIKit import MapKit class HomeViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate { // 表格数据 let arr = ["简单变量操作","控件大全","webView","请求","Polyline"] override func viewDidLoad() { super.viewDidLoad() self.title = "首页" // 初始化表格 let tableView = UITableView(frame: CGRectMake(0, 0, kScreenWidth, kScreenHeight), style: UITableViewStyle.Grouped) tableView.delegate = self tableView.dataSource = self self.view .addSubview(tableView) // Class 注册 tableView.registerClass(HomeCell.self, forCellReuseIdentifier: "HomeCellID") } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44.0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arr.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // 原生的cell // var cell = tableView.dequeueReusableCellWithIdentifier("kMyTableViewCell") as UITableViewCell! // if cell == nil { // cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "kMyTableViewCell") // } // cell?.textLabel?.text = arr[indexPath.row] // return cell!; // 自定义cell var cell:HomeCell! cell = tableView.dequeueReusableCellWithIdentifier("HomeCellID") as! HomeCell cell.indexP = indexPath cell?.testLabel?.text = arr[indexPath.row] cell.testLabel .sizeToFit() if indexPath.row == 0 { cell.testButton.hidden = true } cell.buttonClickBlock = { (ind,btn) -> () in print(indexPath.row) print(btn.currentTitle!) } return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // print(indexPath.row) // tableView.deselectRowAtIndexPath(indexPath, animated: true) // var detailVC : UIViewController? // if indexPath.row == 0 {// 简单变量操作 // detailVC = SimpleViewController() // }else if indexPath.row == 1 {// 控件大全 // detailVC = FirstViewController() // }else if indexPath.row == 2 {// webView // detailVC = WebViewController() // }else if indexPath.row == 3 {// 请求 // detailVC = NetWorkViewController() // }else if indexPath.row == 4 {// polyline 测试 // // 测试谷歌的polyLine // let encodedPolyline = "_p~iF~ps|U_ulLnnqC_mqNvxq`@" // // let coordinates : [CLLocationCoordinate2D]? = Polyline.decodePolyline(encodedPolyline) // // for coor:CLLocationCoordinate2D in coordinates! { // print("lon= \(coor.longitude) lat===\(coor.latitude) ") // } // } // if detailVC != nil { // self.navigationController!.pushViewController(detailVC!, animated: true) // } } }
mit
60830c161856eaf56ef17bcd73d4bb10
31.588235
122
0.591456
4.714894
false
false
false
false
richardpiazza/XCServerCoreData
Sources/Filter.swift
1
1043
import Foundation import CoreData import CodeQuickKit import XCServerAPI public class Filter: NSManagedObject { public convenience init?(managedObjectContext: NSManagedObjectContext, deviceSpecification: DeviceSpecification) { self.init(managedObjectContext: managedObjectContext) self.deviceSpecification = deviceSpecification } public func update(withFilter filter: XCSFilter) { guard let moc = self.managedObjectContext else { Log.warn("\(#function) failed; MOC is nil") return } self.filterType = filter.filterType as NSNumber? self.architectureType = filter.architectureType as NSNumber? if let filterPlatform = filter.platform { if self.platform == nil { self.platform = Platform(managedObjectContext: moc, filter: self) } if let platform = self.platform { platform.update(withPlatform: filterPlatform) } } } }
mit
641ad1c061ecb58dfc151dd2994a0381
31.59375
118
0.635666
5.637838
false
false
false
false
adding/iOS-BaseArch
iOS-BaseArch/iOS-BaseArch/GlobalConstants.swift
1
731
// // GlobalConstants.swift // PregnantAssistant // // Created by D on 15/5/25. // Copyright (c) 2015年 Adding. All rights reserved. // import UIKit let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height //#warning test let baseApiUrl = "http://api.addinghome.com" struct action { static let content = "adding://adco/content" static let video = "adding://adco/video" static let webview = "adding://adco/webview" static let tool = "adding://adco/adTool" } let Device = UIDevice.currentDevice() private let iosVersion = NSString(string: Device.systemVersion).doubleValue let iOS8 = iosVersion >= 8 let iOS7 = iosVersion >= 7 && iosVersion < 8
gpl-2.0
ccf27c26bd18865d0494e37b40e40076
24.172414
75
0.713306
3.591133
false
false
false
false
ps2/rileylink_ios
MinimedKitUI/MinimedHUDProvider.swift
1
4017
// // MinimedHUDProvider.swift // MinimedKitUI // // Created by Pete Schwamb on 2/4/19. // Copyright © 2019 Pete Schwamb. All rights reserved. // import Foundation import LoopKit import LoopKitUI import MinimedKit import SwiftUI class MinimedHUDProvider: HUDProvider { var managerIdentifier: String { return MinimedPumpManager.managerIdentifier } private var state: MinimedPumpManagerState { didSet { guard visible else { return } if oldValue.lastReservoirReading != state.lastReservoirReading { self.updateReservoirView() } } } private let pumpManager: MinimedPumpManager private let bluetoothProvider: BluetoothProvider private let colorPalette: LoopUIColorPalette private let allowedInsulinTypes: [InsulinType] public init(pumpManager: MinimedPumpManager, bluetoothProvider: BluetoothProvider, colorPalette: LoopUIColorPalette, allowedInsulinTypes: [InsulinType]) { self.pumpManager = pumpManager self.bluetoothProvider = bluetoothProvider self.state = pumpManager.state self.colorPalette = colorPalette self.allowedInsulinTypes = allowedInsulinTypes pumpManager.stateObservers.insert(self, queue: .main) } var visible: Bool = false { didSet { if oldValue != visible && visible { self.updateReservoirView() } } } private weak var reservoirView: ReservoirHUDView? private func updateReservoirView() { if let lastReservoirVolume = state.lastReservoirReading, let reservoirView = reservoirView { let reservoirLevel = (lastReservoirVolume.units / pumpManager.pumpReservoirCapacity).clamped(to: 0...1.0) reservoirView.level = reservoirLevel reservoirView.setReservoirVolume(volume: lastReservoirVolume.units, at: lastReservoirVolume.validAt) } } public func createHUDView() -> BaseHUDView? { reservoirView = ReservoirHUDView.instantiate() if visible { updateReservoirView() } return reservoirView } public func didTapOnHUDView(_ view: BaseHUDView, allowDebugFeatures: Bool) -> HUDTapAction? { let vc = pumpManager.settingsViewController(bluetoothProvider: bluetoothProvider, colorPalette: colorPalette, allowDebugFeatures: allowDebugFeatures, allowedInsulinTypes: allowedInsulinTypes) return HUDTapAction.presentViewController(vc) } public var hudViewRawState: HUDProvider.HUDViewRawState { var rawValue: HUDProvider.HUDViewRawState = [ "pumpReservoirCapacity": pumpManager.pumpReservoirCapacity ] if let lastReservoirReading = state.lastReservoirReading { rawValue["lastReservoirReading"] = lastReservoirReading.rawValue } return rawValue } public static func createHUDView(rawValue: HUDProvider.HUDViewRawState) -> BaseHUDView? { guard let pumpReservoirCapacity = rawValue["pumpReservoirCapacity"] as? Double else { return nil } let reservoirHUDView = ReservoirHUDView.instantiate() if let rawLastReservoirReading = rawValue["lastReservoirReading"] as? ReservoirReading.RawValue, let lastReservoirReading = ReservoirReading(rawValue: rawLastReservoirReading) { let reservoirLevel = (lastReservoirReading.units / pumpReservoirCapacity).clamped(to: 0...1.0) reservoirHUDView.level = reservoirLevel reservoirHUDView.setReservoirVolume(volume: lastReservoirReading.units, at: lastReservoirReading.validAt) } return reservoirHUDView } } extension MinimedHUDProvider: MinimedPumpManagerStateObserver { func didUpdatePumpManagerState(_ state: MinimedPumpManagerState) { dispatchPrecondition(condition: .onQueue(.main)) self.state = state } }
mit
fc7599cc897b726ffa3b43b5fdcd6eab
32.190083
199
0.687251
5.20882
false
false
false
false
JovannyEspinal/Checklists-iOS
Checklists/ItemDetailViewController.swift
1
7083
// // ItemDetailViewController.swift // Checklists // // Created by Jovanny Espinal on 12/20/15. // Copyright © 2015 Jovanny Espinal. All rights reserved. // import UIKit import Foundation protocol ItemDetailViewControllerDelegate: class { func itemDetailViewControllerDidCancel(controller: ItemDetailViewController) func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item:ChecklistItem) func itemDetailViewController(controller: ItemDetailViewController, didFinishEditingItem item:ChecklistItem) } class ItemDetailViewController: UITableViewController, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var doneBarButton: UIBarButtonItem! @IBOutlet weak var shouldRemindSwitch: UISwitch! @IBOutlet weak var dueDateLabel: UILabel! @IBOutlet weak var datePickerCell: UITableViewCell! @IBOutlet weak var datePicker: UIDatePicker! weak var delegate: ItemDetailViewControllerDelegate? var itemToEdit: ChecklistItem? var dueDate = NSDate() var datePickerVisible = false override func viewDidLoad() { super.viewDidLoad() if let item = itemToEdit { title = "Edit Item" textField.text = item.text doneBarButton.enabled = true shouldRemindSwitch.on = item.shouldRemind dueDate = item.dueDate } updateDueDateLabel() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) textField.becomeFirstResponder() } @IBAction func cancel() { delegate?.itemDetailViewControllerDidCancel(self) } @IBAction func done() { if let item = itemToEdit { item.text = textField.text! item.shouldRemind = shouldRemindSwitch.on item.dueDate = dueDate item.scheduleNotification() delegate?.itemDetailViewController(self, didFinishEditingItem: item) } else { let item = ChecklistItem() item.text = textField.text! item.checked = false item.shouldRemind = shouldRemindSwitch.on item.dueDate = dueDate item.scheduleNotification() delegate?.itemDetailViewController(self, didFinishAddingItem: item) } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 && datePickerVisible { return 3 } else { return super.tableView(tableView, numberOfRowsInSection: section) } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 1 && indexPath.row == 2 { return datePickerCell } else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 1 && indexPath.row == 2 { return 217 } else { return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 1 && indexPath.row == 1 { return indexPath } else { return nil } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) textField.resignFirstResponder() if indexPath.section == 1 && indexPath.row == 1 { if !datePickerVisible { showDatePicker() } else { hideDatePicker() } } } override func tableView(tableView: UITableView, var indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int { if indexPath.section == 1 && indexPath.row == 2 { indexPath = NSIndexPath(forRow: 0, inSection: indexPath.section) } return super.tableView(tableView, indentationLevelForRowAtIndexPath: indexPath) } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let oldText: NSString = textField.text! let newText: NSString = oldText.stringByReplacingCharactersInRange(range, withString: string) doneBarButton.enabled = (newText.length > 0) return true } func textFieldDidBeginEditing(textField: UITextField) { hideDatePicker() } func updateDueDateLabel() { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .ShortStyle dueDateLabel.text = formatter.stringFromDate(dueDate) } func showDatePicker() { datePickerVisible = true let indexPathDateRow = NSIndexPath(forRow: 1, inSection: 1) let indexPathDatePicker = NSIndexPath(forRow: 2, inSection: 1) if let dateCell = tableView.cellForRowAtIndexPath(indexPathDateRow) { dateCell.detailTextLabel!.textColor = dateCell.detailTextLabel!.tintColor } tableView.beginUpdates() tableView.insertRowsAtIndexPaths([indexPathDatePicker], withRowAnimation: .Fade) tableView.reloadRowsAtIndexPaths([indexPathDateRow], withRowAnimation: .None) tableView.endUpdates() datePicker.setDate(dueDate, animated: false) } func hideDatePicker() { if datePickerVisible { datePickerVisible = false let indexPathDateRow = NSIndexPath(forRow: 1, inSection: 1) let indexPathDatePicker = NSIndexPath(forRow: 2, inSection: 1) if let cell = tableView.cellForRowAtIndexPath(indexPathDateRow) { cell.detailTextLabel!.textColor = UIColor(white: 0, alpha: 0.5) } tableView.beginUpdates() tableView.reloadRowsAtIndexPaths([indexPathDateRow], withRowAnimation: .None) tableView.deleteRowsAtIndexPaths([indexPathDatePicker], withRowAnimation: .Fade) tableView.endUpdates() } } @IBAction func dateChanged(datePicker: UIDatePicker) { dueDate = datePicker.date updateDueDateLabel() } @IBAction func shouldRemindToggled(switchControl: UISwitch) { textField.resignFirstResponder() if switchControl.on { let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) } } }
mit
fe7d45af80d5825260137ef29f7706f5
34.415
132
0.646004
5.852893
false
false
false
false
0416354917/FeedMeIOS
FeedMeIOS/RestaurantTableViewController.swift
1
8069
// // RestaurantTableViewController.swift // FeedMeIOS // // Created by Jun Chen on 16/03/2016. // Copyright © 2016 FeedMe. All rights reserved. // import UIKit class RestaurantTableViewController: UITableViewController { // MARK: Properties var restaurants = [Restaurant]() override func viewDidLoad() { super.viewDidLoad() // Device ID NSLog("Device ID: %@", UIDevice.currentDevice().identifierForVendor!.UUIDString) // Initialization: FeedMe.Variable.images = [String: UIImage]() self.setBackground(self) self.setBar(self) // Load the data: if Reachability.isConnectedToNetwork() { loadAllRestaurants(FeedMe.Path.TEXT_HOST + "restaurants/allRestaurant") } else { Reachability.alertNoInternetConnection(self) } } func loadAllRestaurants(urlString: String) { let url = NSURL(string: urlString) let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (myData, response, error) in dispatch_async(dispatch_get_main_queue(), { self.setShopInfo(myData!) }) } task.resume() } func setShopInfo(shopData: NSData) { let json: Array<AnyObject> do { json = try NSJSONSerialization.JSONObjectWithData(shopData, options: .AllowFragments) as! Array<AnyObject> for index in 0...json.count-1 { if let ID = json[index]["id"] as?Int { let name = json[index]["name"] as?String let description = json[index]["description"] as?String let type = json[index]["type"] as?String let phone = json[index]["phone"] as?String let email = json[index]["email"] as?String let openTimeMorning = json[index]["openTimeMorning"] as?String let openTimeAfternoon = json[index]["openTimeAfternoon"] as?String // let checkin = json[index]["checkin"] as?Bool let checkin = true // MARK: TO BE CHANGED! // load image: let logoName = json[index]["logo"] as?String var image: UIImage? var restaurant = Restaurant(ID: ID, name: name, logo: image, description: description, type: type, phone: phone, email: email, openTimeMorning: openTimeMorning, openTimeAfternoon: openTimeAfternoon, checkin: checkin)! if logoName != nil { if let _ = FeedMe.Variable.images![logoName!] { image = FeedMe.Variable.images![logoName!] restaurant.setLogo(image) } else { dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), { self.setImageInBG(&restaurant, logoName: logoName) }) } } restaurants += [restaurant] } } do_table_refresh() } catch _ { Reachability.alertNoInternetConnection(self) } } func setImageInBG(inout restaurant: Restaurant, logoName: String?) { let url = NSURL(string: FeedMe.Path.PICTURE_HOST + "img/logo/" + logoName!) let data = NSData(contentsOfURL : url!) let image = UIImage(data : data!) restaurant.logo = image! // Cache the newly loaded image: FeedMe.Variable.images![logoName!] = image do_table_refresh() } func do_table_refresh() { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() return }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. FeedMe.Variable.images?.removeAll() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurants.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier. let cellIdentifier = "RestaurantTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RestaurantTableViewCell // Fetches the appropriate meal for the data source layout. let restaurant = restaurants[indexPath.row] cell.nameLabel.text = restaurant.name cell.typeLabel.text = restaurant.type cell.photoImageView.image = restaurant.logo cell.photoImageView.layer.cornerRadius = 10.0 cell.photoImageView.layer.borderWidth = 2.0 cell.photoImageView.clipsToBounds = true if((indexPath.row)%2 == 0) { cell.backgroundColor = FeedMe.transColor4 cell.photoImageView.layer.borderColor = FeedMe.transColor4.CGColor } else { cell.backgroundColor = FeedMe.transColor7 cell.photoImageView.layer.borderColor = FeedMe.transColor7.CGColor } if restaurant.openTimeMorning != nil && restaurant.openTimeAfternoon != nil { cell.timeLabel.text = restaurant.openTimeMorning! + "\n" + restaurant.openTimeAfternoon! } else { cell.timeLabel.text = "" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let restaurant = restaurants[indexPath.row] FeedMe.Variable.restaurantID = restaurant.ID FeedMe.Variable.restaurantName = restaurant.name } /* // 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. } */ }
bsd-3-clause
1deffafc1ed28726b879d1b60a09a275
35.179372
237
0.592588
5.262883
false
false
false
false
Geor9eLau/WorkHelper
Carthage/Checkouts/SwiftCharts/Examples/Examples/BarsExample.swift
1
7259
// // BarsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts // This example uses a normal view generator to create bars. This allows a high degree of customization at view level, since any UIView can be used. // Alternatively it's possible to use ChartBarsLayer (see e.g. implementation of BarsChart for a simple example), which provides more ready to use, bar-specific functionality, but is accordingly more constrained. class BarsExample: UIViewController { fileprivate var chart: Chart? let sideSelectorHeight: CGFloat = 50 fileprivate func barsChart(horizontal: Bool) -> Chart { let tuplesXY = [(2, 8), (4, 9), (6, 10), (8, 12), (12, 17)] func reverseTuples(_ tuples: [(Int, Int)]) -> [(Int, Int)] { return tuples.map{($0.1, $0.0)} } let chartPoints = (horizontal ? reverseTuples(tuplesXY) : tuplesXY).map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))} let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let (axisValues1, axisValues2) = ( stride(from: 0, through: 20, by: 2).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)}, stride(from: 0, through: 14, by: 2).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)} ) let (xValues, yValues) = horizontal ? (axisValues1, axisValues2) : (axisValues2, axisValues1) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let barViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsViewsLayer, chart: Chart) -> UIView? in let bottomLeft = CGPoint(x: layer.innerFrame.origin.x, y: layer.innerFrame.origin.y + layer.innerFrame.height) let barWidth: CGFloat = Env.iPad ? 60 : 30 let (p1, p2): (CGPoint, CGPoint) = { if horizontal { return (CGPoint(x: bottomLeft.x, y: chartPointModel.screenLoc.y), CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y)) } else { return (CGPoint(x: chartPointModel.screenLoc.x, y: bottomLeft.y), CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y)) } }() return ChartPointViewBar(p1: p1, p2: p2, width: barWidth, bgColor: UIColor.blue.withAlphaComponent(0.6)) } let frame = ExamplesDefaults.chartFrame(self.view.bounds) let chartFrame = self.chart?.frame ?? CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height - sideSelectorHeight) let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame) let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: barViewGenerator) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings) return Chart( frame: chartFrame, layers: [ xAxis, yAxis, guidelinesLayer, chartPointsLayer] ) } fileprivate func showChart(horizontal: Bool) { self.chart?.clearView() let chart = self.barsChart(horizontal: horizontal) self.view.addSubview(chart.view) self.chart = chart } override func viewDidLoad() { self.showChart(horizontal: false) if let chart = self.chart { let sideSelector = DirSelector(frame: CGRect(x: 0, y: chart.frame.origin.y + chart.frame.size.height, width: self.view.frame.size.width, height: self.sideSelectorHeight), controller: self) self.view.addSubview(sideSelector) } } class DirSelector: UIView { let horizontal: UIButton let vertical: UIButton weak var controller: BarsExample? fileprivate let buttonDirs: [UIButton : Bool] init(frame: CGRect, controller: BarsExample) { self.controller = controller self.horizontal = UIButton() self.horizontal.setTitle("Horizontal", for: UIControlState()) self.vertical = UIButton() self.vertical.setTitle("Vertical", for: UIControlState()) self.buttonDirs = [self.horizontal : true, self.vertical : false] super.init(frame: frame) self.addSubview(self.horizontal) self.addSubview(self.vertical) for button in [self.horizontal, self.vertical] { button.titleLabel?.font = ExamplesDefaults.fontWithSize(14) button.setTitleColor(UIColor.blue, for: UIControlState()) button.addTarget(self, action: #selector(DirSelector.buttonTapped(_:)), for: .touchUpInside) } } func buttonTapped(_ sender: UIButton) { let horizontal = sender == self.horizontal ? true : false controller?.showChart(horizontal: horizontal) } override func didMoveToSuperview() { let views = [self.horizontal, self.vertical] for v in views { v.translatesAutoresizingMaskIntoConstraints = false } let namedViews = views.enumerated().map{index, view in ("v\(index)", view) } var viewsDict = Dictionary<String, UIView>() for namedView in namedViews { viewsDict[namedView.0] = namedView.1 } let buttonsSpace: CGFloat = Env.iPad ? 20 : 10 let hConstraintStr = namedViews.reduce("H:|") {str, tuple in "\(str)-(\(buttonsSpace))-[\(tuple.0)]" } let vConstraits = namedViews.flatMap {NSLayoutConstraint.constraints(withVisualFormat: "V:|[\($0.0)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict)} self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: hConstraintStr, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDict) + vConstraits) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
mit
39743f69fba376681403b8f1c486d44d
43.262195
212
0.613721
4.938095
false
false
false
false
benlangmuir/swift
test/Generics/concrete_nesting_elimination_order.swift
8
1377
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s protocol P1 { associatedtype T } protocol P2 {} protocol P3 { associatedtype T : P2, P3 } protocol P4 : P3 {} protocol P5 : P4 {} struct C : P2, P5 { typealias T = C } struct G<T: P5> : P1 {} // CHECK-LABEL: concrete_nesting_elimination_order.(file).P6@ // CHECK-NEXT: Requirement signature: <Self where Self.[P6]X : P1, Self.[P6]Y : P5, Self.[P6]Y == Self.[P6]Z.[P1]T, Self.[P6]Z : P1> protocol P6 { associatedtype X : P1 associatedtype Y : P5 associatedtype Z : P1 where Z.T == Y } // CHECK-LABEL: concrete_nesting_elimination_order.(file).P7@ // CHECK-NEXT: Requirement signature: <Self where Self : P6, Self.[P6]X == G<Self.[P6]Y>, Self.[P6]Z == G<Self.[P6]Y>> protocol P7 : P6 where X == G<Y>, X == Z {} // CHECK-LABEL: concrete_nesting_elimination_order.(file).P8a@ // CHECK-NEXT: Requirement signature: <Self where Self : P7, Self.[P6]Y == C> protocol P8a : P7 where Y == C {} // CHECK-LABEL: concrete_nesting_elimination_order.(file).P8b@ // CHECK-NEXT: Requirement signature: <Self where Self : P7, Self.[P6]Y == C> protocol P8b : P7 where Y == C {} // Make sure we pick 'Y == C' and not 'Y == G<C>' here.
apache-2.0
e31f8a6cef57155acb3c645d56528e33
27.6875
141
0.659405
2.748503
false
false
false
false
andybest/SLisp
Sources/SLispCore/Reader.swift
1
5737
/* MIT License Copyright (c) 2017 Andy Best 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 class Reader { let tokens: [TokenType] var pos = 0 public init(tokens: [TokenType]) { self.tokens = tokens } func nextToken() -> TokenType? { defer { pos += 1 } if pos < tokens.count { return tokens[pos] } return nil } func read_token(_ token: TokenType) throws -> LispType { switch token { case .lParen: return try read_list() case .lBrace: return try read_dict() case .symbol(_, let str): // Handle keys if str.hasPrefix(":") { return .key(str.substring(from: str.index(after: str.startIndex))) } if str == "'" { return .list([.symbol("quote"), try read_token(nextToken()!)]) } if str == "`" { return .list([.symbol("quasiquote"), try read_token(nextToken()!)]) } if str == "~" { return .list([.symbol("unquote"), try read_token(nextToken()!)]) } if str == "~@" { return .list([.symbol("splice-unquote"), try read_token(nextToken()!)]) } if str.hasPrefix("'") { return .list([.symbol("quote"), .symbol(String(str.dropFirst()))]) } if str.hasPrefix("`") { return .list([.symbol("quasiquote"), .symbol(String(str.dropFirst()))]) } if str.hasPrefix("~@") { return .list([.symbol("splice-unquote"), .symbol(String(str.dropFirst(2)))]) } if str.hasPrefix("~") { return .list([.symbol("unquote"), .symbol(String(str.dropFirst()))]) } if str == "#" { let body = try read_token(nextToken()!) guard case let .list(f) = body else { throw LispError.lexer(msg: "Reader macro # expects a list") } return .list([.symbol("function")] + f) } return .symbol(str) case .string(_, let str): return .string(str) case .float(_, let num): return .number(.float(num)) case .integer(_, let num): return .number(.integer(num)) case .rParen(let tokenPos): throw LispError.lexer(msg: """ \(tokenPos.line):\(tokenPos.column): Unexpected ')' \t\(tokenPos.sourceLine) \t\(tokenPos.tokenMarker) """) case .rBrace(let tokenPos): throw LispError.lexer(msg: """ \(tokenPos.line):\(tokenPos.column): Unexpected '}' \t\(tokenPos.sourceLine) \t\(tokenPos.tokenMarker) """) } } func read_list() throws -> LispType { var list: [LispType] = [] var endOfList = false while let token = nextToken() { switch token { case .rParen: endOfList = true default: list.append(try read_token(token)) } if endOfList { break } } if !endOfList { throw LispError.readerNotEOF } return .list(list) } func read_dict() throws -> LispType { var endOfDict = false var dictValues = [LispType]() while let token = nextToken() { switch token { case .rBrace: endOfDict = true default: dictValues.append(try read_token(token)) } if endOfDict { break } } if !endOfDict { throw LispError.readerNotEOF } return .list([.symbol("hash-map")] + dictValues) } public static func read(_ input: String) throws -> LispType { let tokenizer = Tokenizer(source: input) let tokens = try tokenizer.tokenizeInput() let reader = Reader(tokens: tokens) return try reader.read_token(reader.nextToken()!) } }
mit
eb70dd476ce68afb5c5d68df8582434e
30.349727
96
0.488409
5.090506
false
false
false
false
iOS-Connect/PushNotifications
Pods/PusherSwift/Source/PusherConnection.swift
1
30123
// // PusherConnection.swift // PusherSwift // // Created by Hamilton Chapman on 01/04/2016. // // public typealias PusherEventJSON = [String: AnyObject] open class PusherConnection: NSObject { open let url: String open let key: String open var options: PusherClientOptions open var globalChannel: GlobalChannel! open var socketId: String? open var connectionState = ConnectionState.disconnected open var channels = PusherChannels() open var socket: WebSocket! open var URLSession: Foundation.URLSession open var userDataFetcher: (() -> PusherPresenceChannelMember)? open var reconnectAttemptsMax: Int? = 6 open var reconnectAttempts: Int = 0 open var maxReconnectGapInSeconds: Double? = nil open weak var delegate: PusherConnectionDelegate? internal var reconnectTimer: Timer? = nil open lazy var reachability: Reachability? = { let reachability = Reachability.init() reachability?.whenReachable = { [unowned self] reachability in self.delegate?.debugLog?(message: "[PUSHER DEBUG] Network reachable") if self.connectionState == .disconnected || self.connectionState == .reconnectingWhenNetworkBecomesReachable { self.attemptReconnect() } } reachability?.whenUnreachable = { [unowned self] reachability in self.delegate?.debugLog?(message: "[PUSHER DEBUG] Network unreachable") } return reachability }() /** Initializes a new PusherConnection with an app key, websocket, URL, options and URLSession - parameter key: The Pusher app key - parameter socket: The websocket object - parameter url: The URL the connection is made to - parameter options: A PusherClientOptions instance containing all of the user-speficied client options - parameter URLSession: An NSURLSession instance for the connection to use for making authentication requests - returns: A new PusherConnection instance */ public init( key: String, socket: WebSocket, url: String, options: PusherClientOptions, URLSession: Foundation.URLSession = Foundation.URLSession.shared) { self.url = url self.key = key self.options = options self.URLSession = URLSession self.socket = socket super.init() self.socket.delegate = self } /** Initializes a new PusherChannel with a given name - parameter channelName: The name of the channel - parameter onMemberAdded: A function that will be called with information about the member who has just joined the presence channel - parameter onMemberRemoved: A function that will be called with information about the member who has just left the presence channel - returns: A new PusherChannel instance */ internal func subscribe( channelName: String, onMemberAdded: ((PusherPresenceChannelMember) -> ())? = nil, onMemberRemoved: ((PusherPresenceChannelMember) -> ())? = nil) -> PusherChannel { let newChannel = channels.add(name: channelName, connection: self, onMemberAdded: onMemberAdded, onMemberRemoved: onMemberRemoved) if self.connectionState == .connected { if !self.authorize(newChannel) { print("Unable to subscribe to channel: \(newChannel.name)") } } return newChannel } /** Initializes a new PusherChannel with a given name - parameter channelName: The name of the channel - parameter onMemberAdded: A function that will be called with information about the member who has just joined the presence channel - parameter onMemberRemoved: A function that will be called with information about the member who has just left the presence channel - returns: A new PusherChannel instance */ internal func subscribeToPresenceChannel( channelName: String, onMemberAdded: ((PusherPresenceChannelMember) -> ())? = nil, onMemberRemoved: ((PusherPresenceChannelMember) -> ())? = nil) -> PusherPresenceChannel { let newChannel = channels.addPresence(channelName: channelName, connection: self, onMemberAdded: onMemberAdded, onMemberRemoved: onMemberRemoved) if self.connectionState == .connected { if !self.authorize(newChannel) { print("Unable to subscribe to channel: \(newChannel.name)") } } return newChannel } /** Unsubscribes from a PusherChannel with a given name - parameter channelName: The name of the channel */ internal func unsubscribe(channelName: String) { if let chan = self.channels.find(name: channelName) , chan.subscribed { self.sendEvent(event: "pusher:unsubscribe", data: [ "channel": channelName ] as [String : Any] ) self.channels.remove(name: channelName) } } /** Either writes a string directly to the websocket with the given event name and data, or calls a client event to be sent if the event is prefixed with "client" - parameter event: The name of the event - parameter data: The data to be stringified and sent - parameter channelName: The name of the channel */ open func sendEvent(event: String, data: Any, channel: PusherChannel? = nil) { if event.components(separatedBy: "-")[0] == "client" { sendClientEvent(event: event, data: data, channel: channel) } else { let dataString = JSONStringify(["event": event, "data": data]) self.delegate?.debugLog?(message: "[PUSHER DEBUG] sendEvent \(dataString)") self.socket.write(string: dataString) } } /** Sends a client event with the given event, data, and channel name - parameter event: The name of the event - parameter data: The data to be stringified and sent - parameter channelName: The name of the channel */ fileprivate func sendClientEvent(event: String, data: Any, channel: PusherChannel?) { if let channel = channel { if channel.type == .presence || channel.type == .private { let dataString = JSONStringify(["event": event, "data": data, "channel": channel.name] as [String : Any]) self.delegate?.debugLog?(message: "[PUSHER DEBUG] sendClientEvent \(dataString)") self.socket.write(string: dataString) } else { print("You must be subscribed to a private or presence channel to send client events") } } } /** JSON stringifies an object - parameter value: The value to be JSON stringified - returns: A JSON-stringified version of the value */ fileprivate func JSONStringify(_ value: Any) -> String { if JSONSerialization.isValidJSONObject(value) { do { let data = try JSONSerialization.data(withJSONObject: value, options: []) let string = String(data: data, encoding: .utf8) if string != nil { return string! } } catch _ { } } return "" } /** Disconnects the websocket */ open func disconnect() { if self.connectionState == .connected { self.reachability?.stopNotifier() updateConnectionState(to: .disconnecting) self.socket.disconnect() } } /** Establish a websocket connection */ @objc open func connect() { if self.connectionState == .connected { return } else { updateConnectionState(to: .connecting) self.socket.connect() if self.options.autoReconnect { // can call this multiple times and only one notifier will be started _ = try? reachability?.startNotifier() } } } /** Instantiate a new GloblalChannel instance for the connection */ internal func createGlobalChannel() { self.globalChannel = GlobalChannel(connection: self) } /** Add callback to the connection's global channel - parameter callback: The callback to be stored - returns: A callbackId that can be used to remove the callback from the connection */ internal func addCallbackToGlobalChannel(_ callback: @escaping (Any?) -> Void) -> String { return globalChannel.bind(callback) } /** Remove the callback with id of callbackId from the connection's global channel - parameter callbackId: The unique string representing the callback to be removed */ internal func removeCallbackFromGlobalChannel(callbackId: String) { globalChannel.unbind(callbackId: callbackId) } /** Remove all callbacks from the connection's global channel */ internal func removeAllCallbacksFromGlobalChannel() { globalChannel.unbindAll() } /** Set the connection state and call the stateChangeDelegate, if set - parameter newState: The new ConnectionState value */ internal func updateConnectionState(to newState: ConnectionState) { let oldState = self.connectionState self.connectionState = newState self.delegate?.connectionStateDidChange?(from: oldState, to: newState) } /** Handle setting channel state and triggering unsent client events, if applicable, upon receiving a successful subscription event - parameter json: The PusherEventJSON containing successful subscription data */ fileprivate func handleSubscriptionSucceededEvent(json: PusherEventJSON) { if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) { chan.subscribed = true if let eData = json["data"] as? String { callGlobalCallbacks(forEvent: "pusher:subscription_succeeded", jsonObject: json) chan.handleEvent(name: "pusher:subscription_succeeded", data: eData) } if PusherChannelType.isPresenceChannel(name: channelName) { if let presChan = self.channels.find(name: channelName) as? PusherPresenceChannel { if let data = json["data"] as? String, let dataJSON = getPusherEventJSON(from: data) { if let presenceData = dataJSON["presence"] as? [String : AnyObject], let presenceHash = presenceData["hash"] as? [String : AnyObject] { presChan.addExistingMembers(memberHash: presenceHash) } } } } self.delegate?.subscriptionDidSucceed?(channelName: channelName) while chan.unsentEvents.count > 0 { if let pusherEvent = chan.unsentEvents.popLast() { chan.trigger(eventName: pusherEvent.name, data: pusherEvent.data) } } } } /** Handle setting connection state and making subscriptions that couldn't be attempted while the connection was not in a connected state - parameter json: The PusherEventJSON containing connection established data */ fileprivate func handleConnectionEstablishedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let connectionData = getPusherEventJSON(from: data), let socketId = connectionData["socket_id"] as? String { self.socketId = socketId updateConnectionState(to: .connected) self.reconnectAttempts = 0 self.reconnectTimer?.invalidate() for (_, channel) in self.channels.channels { if !channel.subscribed { if !self.authorize(channel) { print("Unable to subscribe to channel: \(channel.name)") } } } } } } /** Handle a new member subscribing to a presence channel - parameter json: The PusherEventJSON containing the member data */ fileprivate func handleMemberAddedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) as? PusherPresenceChannel { if let memberJSON = getPusherEventJSON(from: data) { chan.addMember(memberJSON: memberJSON) } else { print("Unable to add member") } } } } /** Handle a member unsubscribing from a presence channel - parameter json: The PusherEventJSON containing the member data */ fileprivate func handleMemberRemovedEvent(json: PusherEventJSON) { if let data = json["data"] as? String { if let channelName = json["channel"] as? String, let chan = self.channels.find(name: channelName) as? PusherPresenceChannel { if let memberJSON = getPusherEventJSON(from: data) { chan.removeMember(memberJSON: memberJSON) } else { print("Unable to remove member") } } } } /** Handle failure of our auth endpoint - parameter channelName: The name of channel for which authorization failed - parameter data: The error returned by the auth endpoint */ fileprivate func handleAuthorizationError(forChannel channelName: String, response: URLResponse?, data: String?, error: NSError?) { let eventName = "pusher:subscription_error" let json = [ "event": eventName, "channel": channelName, "data": data ?? "" ] DispatchQueue.main.async { // TODO: Consider removing in favour of exclusively using delegate self.handleEvent(eventName: eventName, jsonObject: json as [String : AnyObject]) } self.delegate?.subscriptionDidFail?(channelName: channelName, response: response, data: data, error: error) } /** Parse a string to extract Pusher event information from it - parameter string: The string received over the websocket connection containing Pusher event information - returns: A dictionary of Pusher-relevant event data */ open func getPusherEventJSON(from string: String) -> [String : AnyObject]? { let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) do { if let jsonData = data, let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String : AnyObject] { return jsonObject } else { print("Unable to parse string from WebSocket: \(string)") } } catch let error as NSError { print("Error: \(error.localizedDescription)") } return nil } /** Parse a string to extract Pusher event data from it - parameter string: The data string received as part of a Pusher message - returns: The object sent as the payload part of the Pusher message */ open func getEventDataJSON(from string: String) -> Any { let data = (string as NSString).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false) do { if let jsonData = data, let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) { return jsonObject } else { print("Returning data string instead because unable to parse string as JSON - check that your JSON is valid.") } } return string } /** Handles incoming events and passes them on to be handled by the appropriate function - parameter eventName: The name of the incoming event - parameter jsonObject: The event-specific data related to the incoming event */ open func handleEvent(eventName: String, jsonObject: [String : AnyObject]) { switch eventName { case "pusher_internal:subscription_succeeded": handleSubscriptionSucceededEvent(json: jsonObject) case "pusher:connection_established": handleConnectionEstablishedEvent(json: jsonObject) case "pusher_internal:member_added": handleMemberAddedEvent(json: jsonObject) case "pusher_internal:member_removed": handleMemberRemovedEvent(json: jsonObject) default: callGlobalCallbacks(forEvent: eventName, jsonObject: jsonObject) if let channelName = jsonObject["channel"] as? String, let internalChannel = self.channels.find(name: channelName) { if let eName = jsonObject["event"] as? String, let eData = jsonObject["data"] as? String { internalChannel.handleEvent(name: eName, data: eData) } } } } /** Call any global callbacks - parameter eventName: The name of the incoming event - parameter jsonObject: The event-specific data related to the incoming event */ fileprivate func callGlobalCallbacks(forEvent eventName: String, jsonObject: [String : AnyObject]) { if let globalChannel = self.globalChannel { if let eData = jsonObject["data"] as? String { let channelName = jsonObject["channel"] as! String? globalChannel.handleEvent(name: eventName, data: eData, channelName: channelName) } else if let eData = jsonObject["data"] as? [String: AnyObject] { globalChannel.handleErrorEvent(name: eventName, data: eData) } } } /** Uses the appropriate authentication method to authenticate subscriptions to private and presence channels - parameter channel: The PusherChannel to authenticate - parameter callback: An optional callback to be passed along to relevant auth handlers - returns: A Bool indicating whether or not the authentication request was made successfully */ fileprivate func authorize(_ channel: PusherChannel, callback: ((Dictionary<String, String>?) -> Void)? = nil) -> Bool { if channel.type != .presence && channel.type != .private { subscribeToNormalChannel(channel) return true } else { if let socketID = self.socketId { switch self.options.authMethod { case .noMethod: let errorMessage = "Authentication method required for private / presence channels but none provided." let error = NSError(domain: "com.pusher.PusherSwift", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: errorMessage]) print(errorMessage) handleAuthorizationError(forChannel: channel.name, response: nil, data: nil, error: error) return false case .endpoint(authEndpoint: let authEndpoint): let request = requestForAuthValue(from: authEndpoint, socketID: socketID, channel: channel) sendAuthorisationRequest(request: request, channel: channel, callback: callback) return true case .authRequestBuilder(authRequestBuilder: let builder): if let request = builder.requestFor(socketID: socketID, channel: channel) { sendAuthorisationRequest(request: request as URLRequest, channel: channel, callback: callback) return true } else { let errorMessage = "Authentication request could not be built" let error = NSError(domain: "com.pusher.PusherSwift", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey: errorMessage]) handleAuthorizationError(forChannel: channel.name, response: nil, data: nil, error: error) return false } case .inline(secret: let secret): var msg = "" var channelData = "" if channel.type == .presence { channelData = getUserDataJSON() msg = "\(self.socketId!):\(channel.name):\(channelData)" } else { msg = "\(self.socketId!):\(channel.name)" } let secretBuff: [UInt8] = Array(secret.utf8) let msgBuff: [UInt8] = Array(msg.utf8) if let hmac = try? HMAC(key: secretBuff, variant: .sha256).authenticate(msgBuff) { let signature = Data(bytes: hmac).toHexString() let auth = "\(self.key):\(signature)".lowercased() if channel.type == .private { self.handlePrivateChannelAuth(authValue: auth, channel: channel, callback: callback) } else { self.handlePresenceChannelAuth(authValue: auth, channel: channel, channelData: channelData, callback: callback) } } return true } } else { print("socketId value not found. You may not be connected.") return false } } } /** Calls the provided userDataFetcher function, if provided, otherwise will use the socketId as the user_id and return that stringified - returns: A JSON stringified user data object */ fileprivate func getUserDataJSON() -> String { if let userDataFetcher = self.userDataFetcher { let userData = userDataFetcher() if let userInfo: Any = userData.userInfo { return JSONStringify(["user_id": userData.userId, "user_info": userInfo]) } else { return JSONStringify(["user_id": userData.userId]) } } else { if let socketId = self.socketId { return JSONStringify(["user_id": socketId]) } else { print("Authentication failed. You may not be connected") return "" } } } /** Send subscription event for subscribing to a public channel - parameter channel: The PusherChannel to subscribe to */ fileprivate func subscribeToNormalChannel(_ channel: PusherChannel) { self.sendEvent( event: "pusher:subscribe", data: [ "channel": channel.name ] ) } /** Creates an authentication request for the given authEndpoint - parameter endpoint: The authEndpoint to which the request will be made - parameter socketID: The socketId of the connection's websocket - parameter channel: The PusherChannel to authenticate subsciption for - returns: NSURLRequest object to be used by the function making the auth request */ fileprivate func requestForAuthValue(from endpoint: String, socketID: String, channel: PusherChannel) -> URLRequest { var request = URLRequest(url: URL(string: endpoint)!) request.httpMethod = "POST" request.httpBody = "socket_id=\(socketID)&channel_name=\(channel.name)".data(using: String.Encoding.utf8) return request } /** Send authentication request to the authEndpoint specified - parameter request: The request to send - parameter channel: The PusherChannel to authenticate subsciption for - parameter callback: An optional callback to be passed along to relevant auth handlers */ fileprivate func sendAuthorisationRequest(request: URLRequest, channel: PusherChannel, callback: (([String : String]?) -> Void)? = nil) { let task = URLSession.dataTask(with: request, completionHandler: { data, response, sessionError in if let error = sessionError { print("Error authorizing channel [\(channel.name)]: \(error)") self.handleAuthorizationError(forChannel: channel.name, response: response, data: nil, error: error as NSError?) return } guard let data = data else { print("Error authorizing channel [\(channel.name)]") self.handleAuthorizationError(forChannel: channel.name, response: response, data: nil, error: nil) return } guard let httpResponse = response as? HTTPURLResponse, (httpResponse.statusCode == 200 || httpResponse.statusCode == 201) else { let dataString = String(data: data, encoding: String.Encoding.utf8) print ("Error authorizing channel [\(channel.name)]: \(dataString)") self.handleAuthorizationError(forChannel: channel.name, response: response, data: dataString, error: nil) return } guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), let json = jsonObject as? [String: AnyObject] else { print("Error authorizing channel [\(channel.name)]") self.handleAuthorizationError(forChannel: channel.name, response: httpResponse, data: nil, error: nil) return } self.handleAuthResponse(json: json, channel: channel, callback: callback) }) task.resume() } /** Handle authentication request response and call appropriate handle function - parameter json: The auth response as a dictionary - parameter channel: The PusherChannel to authenticate subsciption for - parameter callback: An optional callback to be passed along to relevant auth handlers */ fileprivate func handleAuthResponse( json: [String : AnyObject], channel: PusherChannel, callback: (([String : String]?) -> Void)? = nil) { if let auth = json["auth"] as? String { if let channelData = json["channel_data"] as? String { handlePresenceChannelAuth(authValue: auth, channel: channel, channelData: channelData, callback: callback) } else { handlePrivateChannelAuth(authValue: auth, channel: channel, callback: callback) } } } /** Handle presence channel auth response and send subscribe message to Pusher API - parameter auth: The auth string - parameter channel: The PusherChannel to authenticate subsciption for - parameter channelData: The channelData to send along with the auth request - parameter callback: An optional callback to be called with auth and channelData, if provided */ fileprivate func handlePresenceChannelAuth( authValue: String, channel: PusherChannel, channelData: String, callback: (([String : String]?) -> Void)? = nil) { (channel as? PusherPresenceChannel)?.setMyUserId(channelData: channelData) if let cBack = callback { cBack(["auth": authValue, "channel_data": channelData]) } else { self.sendEvent( event: "pusher:subscribe", data: [ "channel": channel.name, "auth": authValue, "channel_data": channelData ] ) } } /** Handle private channel auth response and send subscribe message to Pusher API - parameter auth: The auth string - parameter channel: The PusherChannel to authenticate subsciption for - parameter callback: An optional callback to be called with auth and channelData, if provided */ fileprivate func handlePrivateChannelAuth( authValue auth: String, channel: PusherChannel, callback: (([String : String]?) -> Void)? = nil) { if let cBack = callback { cBack(["auth": auth]) } else { self.sendEvent( event: "pusher:subscribe", data: [ "channel": channel.name, "auth": auth ] ) } } } @objc public enum ConnectionState: Int { case connecting case connected case disconnecting case disconnected case reconnecting case reconnectingWhenNetworkBecomesReachable static let connectionStates = [ connecting: "connecting", connected: "connected", disconnecting: "disconnecting", disconnected: "disconnected", reconnecting: "reconnecting", reconnectingWhenNetworkBecomesReachable: "reconnreconnectingWhenNetworkBecomesReachable", ] public func stringValue() -> String { return ConnectionState.connectionStates[self]! } }
mit
e42c089c25139d83e780d11ebc156d00
40.095498
153
0.596255
5.374309
false
false
false
false
billypchan/GravityTagCloudView
GravityTagCloudView/DemoPlayground.playground/Contents.swift
1
1992
////: Playground - noun: a place where people can play import UIKit import PlaygroundSupport import GravityTagCloudView let gravityTagCloudView = GravityTagCloudView() gravityTagCloudView.frame = CGRect(x: 0, y: 0, width: 360, height: 200) let container = UIView(frame: CGRect(x: 0, y: 0, width: 360, height: 200)) /* Test case: tag cloud with 7 tags with weighted size*/ container.addSubview(gravityTagCloudView) ///TODO: gravity not work? Please look at the demo project! PlaygroundPage.current.liveView = container PlaygroundPage.current.needsIndefiniteExecution = true /* Test case: tag cloud with random size */ gravityTagCloudView.labelSizeType = .random gravityTagCloudView.titles = ["elephant", "cow", "horse", "dog", "cat", "rat"] gravityTagCloudView.generate(labelCreatedHandler:{ label in /* label added = 4~24 */ print("label added:\(label)") }) container gravityTagCloudView.labelSizeType = .weighted gravityTagCloudView.titleWeights = [["title":"elephant", "weight":10], ["title":"cow", "weight":7], ["title":"horse", "weight":7], ["title":"dog", "weight":5], ["title":"cat", "weight":3], ["title":"rat", "weight":1], ["title":"mouse", "weight":1] ] gravityTagCloudView.generate(labelCreatedHandler:{ label in /* label added = 4~24 */ print("label added:\(label)") }) container /* Test case: try to create a tag cloud with 100 tags */ var array = [[String:Any]]() for i in 1...100 { array.append(["title":"bug\(i)", "weight":100]) } gravityTagCloudView.titleWeights = array gravityTagCloudView.generate(completionHandler:{ finish, numLabelAdded in let log = "finish=\(finish), label added = \(numLabelAdded)" }) /* try to fill the view with bugs! ~ 71~74 tags in the view */ container
mit
3976b3de0797fdc27b6cd141002ff6c6
31.655738
101
0.61747
4.057026
false
false
false
false
ExTEnS10N/JSONRequestTOUIView
JsonToObject.swift
1
3985
// // JsonToObject.swift // JsonToUIView // // Created by macsjh on 16/1/6. // Copyright © 2016年 TurboExtension. All rights reserved. // /// use the code below in your app to init Object Like UIView import UIKit import Alamofire import SwiftyJSON /// set values of object's members, which is listed in the keylist via KVC. jsonValue is the datasource. /// /// - parameter jsonValue: the source data /// - parameter object: Normally is UITableViewCell or other UIView /// - parameter keyList: the members' name in object /// /// - returns: the object parameter itself func JsonToObject(jsonValue:AnyObject, object: AnyObject, keyList:[String]=[])->AnyObject { var json = JSON.init(jsonValue) for key in keyList { let item = json[key] if(item.isExists()) { switch item.type { case .Number: if(item.stringValue.containsString(".")){ object.setValue(item.doubleValue, forKey: key) } else{ object.setValue(item.intValue, forKey: key) } break case .String: object.setValue(item.stringValue, forKey: key) break case.Bool: object.setValue(item.boolValue, forKey: key) break case .Array: if(item[0].type != .Dictionary && item[0].type != .Array) { object.setValue(item.arrayObject!, forKeyPath: key) } break default: break } } } return object } /// Automatically check JSON returned by request, and return valuable part by calling completion. /// /// - parameter urlString: the url going to be requested /// - parameter parameters: things you want to transfer to server /// - parameter returnArrayOnly: Array type JSON is considered valuable by default /// - parameter completion: return the valuable part of JSON /// - parameter errorCode: when error occur, this method will be called, you will received -3 if returnArrayOnly is true but no Array found in top level JSON members. func JsonRequest(urlString: String, parameters: [String : AnyObject]?, returnArrayOnly:Bool = true,completion: AnyObject->(), errorCode: Int->()?) { Alamofire.request(.POST, urlString, parameters: parameters) .responseJSON { response in if let value = response.result.value { let json = JSON(value) // Assuming that there is a "result" value indicates the operation on server is success or not if json["result"].isExists() { if json["result"].intValue != 0{ errorCode(json["result"].intValue) return } } if(!returnArrayOnly) { completion(value) return } else { for (_, subJson):(String, JSON) in json { if(subJson.type == .Array){ completion(subJson.object) return } } errorCode(-3) } } } } extension String{ /// download image and store in cache, if the image is already in cache, download will never begin and the local image will be return /// /// - parameter catalogue: the name of a directory that the image should be stored in. /// /// - returns: downloaded image or local image public func downloadImage(catalogue:String) -> UIImage? { let fileName:String if let lastPath = NSURL(string: self)?.lastPathComponent{ fileName = lastPath } else{ fileName = self } let fileManager = NSFileManager() var cachePath = try! fileManager.URLForDirectory( .CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false) cachePath = cachePath.URLByAppendingPathComponent(catalogue) cachePath = cachePath.URLByAppendingPathComponent(fileName) let isDirectory = UnsafeMutablePointer<ObjCBool>.alloc(1) if(fileManager.fileExistsAtPath(cachePath.path!, isDirectory: isDirectory)){ if isDirectory.memory.boolValue { let data = NSData(contentsOfURL: cachePath) return UIImage(data: data) } } Alamofire.request(.POST, self) .responseData { response in response.data?.writeToURL(cachePath, atomically: true) return UIImage(data: response.data) } return nil } }
mit
e5b5c95d39c0200e1dcf289dcd718c34
27.45
168
0.68885
3.697307
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Discover/Controllers/TakeMovieVC.swift
3
12480
// // TakeMovieVC.swift // iOSStar // // Created by sum on 2017/8/15. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import PLShortVideoKit import Qiniu import SVProgressHUD class TakeMovieVC: UIViewController ,PLShortVideoRecorderDelegate ,PLShortVideoUploaderDelegate ,PLPlayerDelegate{ @IBOutlet var content: UILabel! @IBOutlet var header: UIImageView! @IBOutlet var name: UILabel! var didTap = false var q_content = "" var index = 1 var shortVideoRecorder : PLShortVideoRecorder? var resultBlock: CompleteBlock? var filePath : URL? var player : PLPlayer? var totalTime = 0 var canle : Bool = false var stopTake = false //设置按住松开的view @IBOutlet var width: NSLayoutConstraint! lazy var ProgressView : OProgressView = { let Progress = OProgressView.init(frame: CGRect.init(x: self.view.center.x - 50, y: kScreenHeight - 120, width: 100, height: 100)) return Progress }() @IBOutlet var showStartImg: UIImageView! @IBOutlet var timeProgress: UIView! var timer : Timer! @IBOutlet var bgView: UIView! @IBOutlet var tipView: UIView! //切换摄像头 @IBOutlet var switchBtn: UIButton! //退出按钮 @IBOutlet var closeBtn: UIButton! //重置按钮 @IBOutlet var resetBtn: UIButton! //确定按钮 @IBOutlet var sureBtn: UIButton! // 录制视频的video override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } override func viewDidLoad() { super.viewDidLoad() updateUserInfo() configViedeo() width.constant = 0 SVProgressHUD.showWainningMessage(WainningMessage: "长按录制视频", ForDuration: 3, completion: nil) self.view.bringSubview(toFront: self.tipView) self.view.bringSubview(toFront: self.switchBtn) self.view.addSubview(ProgressView) tap() timeProgress.isHidden = true self.view.bringSubview(toFront: timeProgress) self.view.bringSubview(toFront: self.closeBtn) } func updateGrogress(){ if player?.totalDuration.value == 0{ return } let current = CGFloat((player?.currentTime.value)!)/CGFloat((player?.currentTime.timescale)!) let total = CGFloat((player?.totalDuration.value)!)/CGFloat((player?.totalDuration.timescale)!) if current == total{ } width.constant = (kScreenWidth - 20 ) * current/total } //MARK: -配置段视频链接 func configViedeo(){ let videoConfiguration = PLSVideoConfiguration.default() let audioConfiguration = PLSAudioConfiguration.default() self.shortVideoRecorder = PLShortVideoRecorder.init(videoConfiguration: videoConfiguration!, audioConfiguration: audioConfiguration!) self.view.addSubview((self.shortVideoRecorder?.previewView)!) // self.shortVideoRecorder?.toggleCamera() self.shortVideoRecorder?.maxDuration = 15.0 self.shortVideoRecorder?.minDuration = 1.0 self.shortVideoRecorder?.delegate = self self.shortVideoRecorder?.setBeautify(1) self.shortVideoRecorder?.setBeautifyModeOn(true) self.shortVideoRecorder?.isTouchToFocusEnable = false self.shortVideoRecorder?.startCaptureSession() } //MARK: -添加手势 func tap(){ ProgressView.backgroundColor = UIColor.clear let longpressGesutre = UILongPressGestureRecognizer.init(target: self, action: #selector(start(_ :))) //所需触摸1次 longpressGesutre.numberOfTouchesRequired = 1 ProgressView.addGestureRecognizer(longpressGesutre) } //确定按钮 @IBAction func didsure(_ sender: Any) { SVProgressHUD.show(withStatus: "上传中") uploadthumbnail() QiniuTool.qiniuUploadImage(image: showStartImg.image!, imageName: "thumbnail", complete: { (result) in if self.resultBlock != nil{ if let thumbnail = result as? String{ QiniuTool.qiniuUploadVideo(filePath: (self.filePath?.path)!, videoName: "short_video", complete: { (result) in if self.resultBlock != nil{ if let response = result as? String{ SVProgressHUD.showSuccessMessage(SuccessMessage: "录制成功", ForDuration: 1.5, completion: { let outputSettings = ["movieUrl" : response as AnyObject,"totalTime":self.totalTime as AnyObject,"thumbnail" : thumbnail as AnyObject,"thumbnailImg" : self.showStartImg.image as AnyObject,] as [String : AnyObject] self.resultBlock!(outputSettings as AnyObject) self.navigationController?.popViewController(animated: true) }) } } }) { (error) in } } } }) { (erro) in } } @IBAction func switchbtn(_ sender: Any) { self.shortVideoRecorder?.toggleCamera() } @IBAction func exit(_ sender: Any) { _ = navigationController?.popViewController(animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if timer != nil{ timer.invalidate() } if (player?.isPlaying == true){ canle = true player?.stop() } } //重置按钮 @IBAction func didreset(_ sender: Any) { //播放器停止 if (player?.isPlaying == true){ canle = true player?.stop() } stopTake = false timer.invalidate() canle = true width.constant = 0 self.bgView.isHidden = true ProgressView.isHidden = false self.switchBtn.isHidden = false self.closeBtn.isHidden = false self.showStartImg.isHidden = true timeProgress.isHidden = true self.shortVideoRecorder?.previewView?.isHidden = false self.view.bringSubview(toFront: (self.shortVideoRecorder?.previewView)!) self.view.bringSubview(toFront: ProgressView) self.view.bringSubview(toFront: switchBtn) self.view.bringSubview(toFront: closeBtn) self.view.bringSubview(toFront: self.tipView) self.shortVideoRecorder?.cancelRecording() self.shortVideoRecorder?.stopRecording() ProgressView.setProgress(0, animated: true) } func start( _ sender: UIRotationGestureRecognizer){ if sender.state == .began { canle = false self.shortVideoRecorder?.startRecording() } if sender.state == .ended { self.shortVideoRecorder?.stopRecording() } } } extension TakeMovieVC { func player(_ player: PLPlayer, statusDidChange state: PLPlayerStatus) { if state == .statusStopped{ if !canle && stopTake == true { self.perform(#selector(didplay), with: self , afterDelay: 1) self.view.bringSubview(toFront: self.tipView) self.view.bringSubview(toFront: self.timeProgress) }else{ self.view.bringSubview(toFront: self.tipView) } } else if state == .statusPlaying { stopTake = true } else if state == .statusPaused{ } } func didplay(){ player?.play(with: self.filePath) } func shortVideoRecorder(_ recorder: PLShortVideoRecorder, didRecordingToOutputFileAt fileURL: URL, fileDuration: CGFloat, totalDuration: CGFloat) { ProgressView.setProgress(ProgressView.progress + 0.4, animated: true) } func shortVideoRecorder(_ recorder: PLShortVideoRecorder, didFinishRecordingMaxDuration maxDuration: CGFloat) { ProgressView.isHidden = true totalTime = Int(maxDuration) self.shortVideoRecorder?.stopRecording() // sureBtn.isHidden = false timeProgress.isHidden = false timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true) self.view.bringSubview(toFront: (player?.playerView)!) self.view.bringSubview(toFront: self.tipView) self.view.bringSubview(toFront: self.bgView) self.view.bringSubview(toFront: self.timeProgress) self.bgView.isHidden = false ProgressView.setProgress(0, animated: true) } func shortVideoRecorder(_ recorder: PLShortVideoRecorder, didFinishRecordingToOutputFileAt fileURL: URL, fileDuration: CGFloat, totalDuration: CGFloat) { ProgressView.isHidden = true stopTake = false self.shortVideoRecorder?.stopRecording() UIView.animate(withDuration: 0.23) { self.sureBtn.isHidden = false self.resetBtn.isHidden = false self.bgView.isHidden = false } timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateGrogress), userInfo: nil, repeats: true) self.filePath = fileURL totalTime = Int(totalDuration) self.shortVideoRecorder?.previewView?.isHidden = true getScreenImg() ProgressView.setProgress(0, animated: true) if (player == nil){ let option = PLPlayerOption.default() player = PLPlayer.init(url: fileURL, option: option) self.view.addSubview((player?.playerView)!) self.showStartImg.isHidden = false self.view.bringSubview(toFront: (player?.playerView)!) self.view.bringSubview(toFront: self.tipView) self.switchBtn.isHidden = true self.closeBtn.isHidden = true self.view.bringSubview(toFront: self.bgView) timeProgress.isHidden = false self.view.bringSubview(toFront: self.timeProgress) player?.delegate = self player?.play() self.view.bringSubview(toFront: resetBtn) }else{ player?.play(with: fileURL) self.showStartImg.isHidden = false self.switchBtn.isHidden = true self.closeBtn.isHidden = true self.bgView.isHidden = false self.view.bringSubview(toFront: (player?.playerView)!) self.view.bringSubview(toFront: self.tipView) self.view.bringSubview(toFront: self.bgView) self.view.bringSubview(toFront: sureBtn) timeProgress.isHidden = false self.view.bringSubview(toFront: self.timeProgress) self.view.bringSubview(toFront: resetBtn) } } // //获取屏幕截图 func getScreenImg(){ let avAsset = AVAsset(url : self.filePath!) let generator = AVAssetImageGenerator(asset: avAsset) generator.appliesPreferredTrackTransform = true let time = CMTimeMakeWithSeconds(0.0,600) var actualTime:CMTime = CMTimeMake(0,0) let imageRef:CGImage = try! generator.copyCGImage(at: time, actualTime: &actualTime) let frameImg = UIImage(cgImage:imageRef ) showStartImg.image = frameImg } func updateUserInfo() { getUserInfo { (result) in if let response = result{ let model = response as! UserInfoModel if model.nick_name == "" { let nameUid = StarUserModel.getCurrentUser()?.userinfo?.id let stringUid = String.init(format: "%d", nameUid!) self.name.text = "星享时光用户" + stringUid } else { self.name.text = model.nick_name } self.content.text = self.q_content self.header.kf.setImage(with: URL(string: model.head_url), placeholder: UIImage(named:"avatar_team"), options: nil, progressBlock: nil, completionHandler: nil) } } } func uploadthumbnail(){ } }
gpl-3.0
b74df9d26e86d5c218d014d90f2ac0cf
36.88
249
0.608155
4.747782
false
false
false
false
wl879/SwiftyCss
SwiftyCss/SwiftyCss/Animate.swift
1
6431
// // Animate.swift // SwiftyCss // // Created by Wang Liang on 2017/5/13. // Copyright © 2017年 Wang Liang. All rights reserved. // import UIKit public extension CAMediaTimingFunction { public static let linear = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) public static let easeIn = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) public static let easeOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) public static let easeInOut = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } extension Css { public enum Animate: String { case shake, pop, morph, wobble, swing case fadeIn, fadeOut, fadeUp, fadeDown, fadeUpOut, fadeDownOut } class AnimateDelegate: NSObject, CAAnimationDelegate { let completion: (Bool) -> Void init(_ completion: @escaping (Bool) -> Void) { self.completion = completion super.init() } func animationDidStop(_ ani: CAAnimation, finished: Bool) { self.completion(finished) } } static func keyframe(_ duration: TimeInterval, _ delay: TimeInterval = 0, _ repet: Float = 1, _ function: CAMediaTimingFunction? = nil) -> CAKeyframeAnimation { let ani = CAKeyframeAnimation() if delay > 0 { ani.beginTime = CACurrentMediaTime() + delay } if function != nil { ani.timingFunction = function! } if repet > 1 { ani.repeatCount = repet } ani.duration = duration ani.isAdditive = true return ani } static public func animate(type: Animate, duration: TimeInterval, layer: CALayer, delay: TimeInterval = 0, force: CGFloat = 1, repeat repet: Float = 1, function: CAMediaTimingFunction? = nil, completion: ((Bool)->Void)? = nil) { let ani = Css.keyframe(duration, delay, repet, function) switch type { case .shake: ani.keyPath = "position.x" ani.values = [0, 30*force, -30*force, 30*force, 0] ani.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] case .pop: ani.keyPath = "transform.scale" ani.values = [0, 0.2*force, -0.2*force, 0.2*force, 0] ani.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] case .morph: let aniX = Css.keyframe(duration, delay, repet, function) aniX.keyPath = "transform.scale.x" aniX.values = [1, 1.3*force, 0.7, 1.3*force, 1] aniX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] layer.add(aniX, forKey: "morphX") ani.keyPath = "transform.scale.y" ani.values = [1, 0.7, 1.3*force, 0.7, 1] ani.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] case .wobble: let aniX = Css.keyframe(duration, delay, repet, function) aniX.keyPath = "position.x" aniX.values = [0, 30*force, -30*force, 30*force, 0] aniX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] layer.add(aniX, forKey: "wobbleX") ani.keyPath = "transform.rotation" ani.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] ani.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] case .swing: ani.keyPath = "transform.rotation" ani.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] ani.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] case .fadeIn, .fadeUp, .fadeDown: layer.opacity = 1 ani.keyPath = "opacity" ani.values = [-1, 0] ani.keyTimes = [0, 1] if type == .fadeUp || type == .fadeDown { let aniY = Css.keyframe(duration, delay, repet, function) aniY.keyPath = "transform.translation.y" aniY.values = type == .fadeUp ? [30, 0] : [-30, 0] aniY.keyTimes = [0, 1] layer.add(aniY, forKey: "fadeUpY") } case .fadeOut, .fadeUpOut, .fadeDownOut: layer.opacity = 0 ani.keyPath = "opacity" ani.values = [1, 0] ani.keyTimes = [0, 1] if type == .fadeUpOut || type == .fadeDownOut { let aniY = Css.keyframe(duration, delay, repet, function) aniY.keyPath = "transform.translation.y" aniY.values = type == .fadeUpOut ? [0, -30] : [0, 30] aniY.keyTimes = [0, 1] layer.add(aniY, forKey: "fadeUpY") } } if completion != nil { ani.delegate = AnimateDelegate(completion!) } layer.add(ani, forKey: type.rawValue) } static public func nonAnimate(_ animations: ()->Void) { CATransaction.begin() CATransaction.setDisableActions(true) animations() CATransaction.commit() } static public func animate(_ duration: TimeInterval, _ function: CAMediaTimingFunction? = nil , _ animations: ()->Void){ CATransaction.begin() CATransaction.setAnimationDuration(duration) if function != nil { CATransaction.setAnimationTimingFunction(function) } animations() CATransaction.commit() } static public func animate(delay: TimeInterval, duration: TimeInterval, function: CAMediaTimingFunction? = nil, animations: @escaping ()->Void, completion: (()->Void)? = nil ){ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: { Css.animate(duration: duration, function: function, animations: animations, completion: completion) }) } static public func animate(duration: TimeInterval, function: CAMediaTimingFunction? = nil , animations: ()->Void, completion: (()->Void)? = nil ){ CATransaction.begin() if duration > 0 { CATransaction.setAnimationDuration(duration) }else{ CATransaction.setDisableActions(true) } if function != nil { CATransaction.setAnimationTimingFunction(function) } if completion != nil { CATransaction.setCompletionBlock(completion) } animations() CATransaction.commit() } }
mit
324a40f98905a8acb385d754c9bf176b
36.156069
233
0.551182
4.136422
false
false
false
false
mathewsanders/Mustard
Tests/FuzzyMatchTokenTests.swift
1
3880
// FuzzyMatchTokenTests.swift // // Copyright (c) 2017 Mathew Sanders // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import XCTest import Mustard infix operator ~= func ~= (option: CharacterSet, input: UnicodeScalar) -> Bool { return option.contains(input) } final class FuzzyLiteralMatch: TokenizerType { let target: String private let exclusions: CharacterSet private var position: String.UnicodeScalarIndex init(target: String, ignoring exclusions: CharacterSet) { self.target = target self.position = target.unicodeScalars.startIndex self.exclusions = exclusions } func tokenCanTake(_ scalar: UnicodeScalar) -> Bool { guard position < target.unicodeScalars.endIndex else { return false // we've matched all of the target } let targetScalar = target.unicodeScalars[position] switch (scalar, targetScalar) { // following 3 cases check either that scalar and target scalar are exactly the same // or the equivilant upper/lowercase pair case (_, _) where scalar == targetScalar: incrementPosition() return true case (CharacterSet.lowercaseLetters, CharacterSet.uppercaseLetters) where scalar.value - targetScalar.value == 32: incrementPosition() return true case (CharacterSet.uppercaseLetters, CharacterSet.lowercaseLetters) where targetScalar.value - scalar.value == 32: incrementPosition() return true case (exclusions, _) where position > target.unicodeScalars.startIndex: // scalar matches character from exclusions charater set return true default: // scalar isn't the next target scalar, or a scalar that can be ignored return false } } private func incrementPosition() { position = target.unicodeScalars.index(after: position) } func tokenIsComplete() -> Bool { return position == target.unicodeScalars.endIndex } func prepareForReuse() { position = target.unicodeScalars.startIndex } } class FuzzyMatchTokenTests: XCTestCase { func testSpecialFormat() { let fuzzyTokenzier = FuzzyLiteralMatch(target: "#YF1942B", ignoring: CharacterSet.whitespaces.union(.punctuationCharacters)) let messyInput = "Serial: #YF 1942-b 12/01/27 (Scanned) 12/02/27 (Arrived) ref: 99/99/99" let tokens = messyInput.tokens(matchedWith: fuzzyTokenzier) XCTAssert(tokens.count == 1, "Unexpected number of tokens [\(tokens.count)]") XCTAssert(tokens[0].text == "#YF 1942-b") } }
mit
bd1b6bf7aa3094b4ac9fe459de2be6bc
36.307692
122
0.660825
5
false
false
false
false
ktatroe/MPA-Horatio
Horatio/Horatio/Classes/Operations/ExclusivityController.swift
2
3256
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The file contains the code to automatically set up dependencies between mutually exclusive operations. */ import Foundation /** `ExclusivityController` is a singleton to keep track of all the in-flight `Operation` instances that have declared themselves as requiring mutual exclusivity. We use a singleton because mutual exclusivity must be enforced across the entire app, regardless of the `OperationQueue` on which an `Operation` was executed. */ open class ExclusivityController { static let sharedExclusivityController = ExclusivityController() fileprivate let serialQueue = DispatchQueue(label: "Operations.ExclusivityController", attributes: []) fileprivate var operations: [String: [Operation]] = [:] fileprivate init() { /* A private initializer effectively prevents any other part of the app from accidentally creating an instance. */ } /// Registers an operation as being mutually exclusive open func addOperation(_ operation: Operation, categories: [String]) { /* This needs to be a synchronous operation. If this were async, then we might not get around to adding dependencies until after the operation had already begun, which would be incorrect. */ serialQueue.sync { for category in categories { self.noqueue_addOperation(operation, category: category) } } } /// Unregisters an operation from being mutually exclusive. open func removeOperation(_ operation: Operation, categories: [String]) { serialQueue.sync { for category in categories { self.noqueue_removeOperation(operation, category: category) } } } // MARK: Operation Management fileprivate func noqueue_addOperation(_ operation: Operation, category: String) { var operationsWithThisCategory = operations[category] ?? [] if let last = operationsWithThisCategory.last { assert(last.dependencies.contains(operation) == false, "Deadlocked") operation.addDependency(last) } operationsWithThisCategory.append(operation) if operationsWithThisCategory.count >= 3, let first = operationsWithThisCategory.first { let ready = first.isReady let executing = first.isExecuting let hasNoDependencies = first.dependencies.count == 0 let hasStalled = ready && !executing && hasNoDependencies if hasStalled { first.cancel() } } operations[category] = operationsWithThisCategory } fileprivate func noqueue_removeOperation(_ operation: Operation, category: String) { let matchingOperations = operations[category] guard var operationsWithThisCategory = matchingOperations else { return } if let index = operationsWithThisCategory.index(of: operation) { operationsWithThisCategory.remove(at: index) operations[category] = operationsWithThisCategory } } }
mit
d25d074fee8a1a87101dd8c1e766fd43
34.758242
106
0.669945
5.414309
false
false
false
false
IvanRublev/PersistentStorageSerializable
Example/PersistentStorageSerializable_MacExample/AppSettings.swift
1
675
// // AppSettings.swift // PersistentStorageSerializable // // Created by Ivan Rublev on 4/6/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import PersistentStorageSerializable final class AppSettings: NSObject, PersistentStorageSerializable { dynamic var flag = false dynamic var title = "Default text" dynamic var number = 1 // MARK: Adopt PersistentStorageSerializable var persistentStorage: PersistentStorage! = PlistStorage(at: FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("storage.plist")) var persistentStorageKeyPrefix: String! = "AppSettings" }
mit
8606355b1e5495db155419a7261a7a31
32.7
182
0.75816
4.585034
false
false
false
false
ivanbruel/SwipeIt
SwipeIt/ViewControllers/Base/WebViewController.swift
1
2133
// // WebViewController.swift // Reddit // // Created by Ivan Bruel on 26/04/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import UIKit import WebKit // MARK: - Properties, Lifecycle and API class WebViewController: UIViewController { let webView = WKWebView() let progressView: UIProgressView = UIProgressView(progressViewStyle: .Bar) override func viewDidLoad() { super.viewDidLoad() setupViews() } func loadURL(URLString: String) { guard let url = NSURL(string: URLString) else { print("\(URLString) is not a valid URL string") return } webView.loadRequest(NSURLRequest(URL: url)) } } // MARK: - Setup extension WebViewController: WKNavigationDelegate { private func setupViews() { setupWebView() setupProgressView() } private func setupWebView() { webView.navigationDelegate = self view.addSubview(webView) webView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } } private func setupProgressView() { view.addSubview(progressView) progressView.snp_makeConstraints { (make) in make.top.equalTo(self.snp_topLayoutGuideBottom) make.left.right.equalTo(view) } webView.rx_observe(Double.self, "estimatedProgress") .bindNext { estimatedProgress in guard let estimatedProgress = estimatedProgress else { return } self.progressView.layer.removeAllAnimations() let floatEstimatedProgress = Float(estimatedProgress) let animateChange = self.progressView.progress < floatEstimatedProgress self.progressView.setProgress(floatEstimatedProgress, animated: animateChange) if estimatedProgress == 1 { self.hideProgressView() } else { self.progressView.alpha = 1 } }.addDisposableTo(rx_disposeBag) } } // MARK: - Animations extension WebViewController { private func hideProgressView() { UIView.animateWithDuration(0.3, delay: 0.5, options: [], animations: { self.progressView.alpha = 0 }) { _ in self.progressView.progress = 0 } } }
mit
2c84c1db5fc26f0404e3f2345539d1a2
23.790698
86
0.677298
4.545842
false
false
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/SocialAppLayout/CommentsNode.swift
1
1255
// // CommentsNode.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/26. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit class CommentsNode: ASControlNode { let iconNode = ASImageNode() let countNode = ASTextNode() var commentsCount = 0 init(comentsCount: Int) { super.init() commentsCount = comentsCount iconNode.image = UIImage(named: "icon_comment") addSubnode(iconNode) if commentsCount > 0 { countNode.attributedText = NSAttributedString(string: "\(commentsCount)", attributes: TextStyles.cellControlStyle) } addSubnode(countNode) // make it tappable easily hitTestSlop = UIEdgeInsets.init(top: -10, left: -10, bottom: -10, right: -10) } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { let mainStack = ASStackLayoutSpec(direction: .horizontal, spacing: 6, justifyContent: .start, alignItems: .center, children: [iconNode, countNode]) // Adjust size mainStack.style.minWidth = ASDimensionMakeWithPoints(60.0) mainStack.style.maxHeight = ASDimensionMakeWithPoints(40.0) return mainStack } }
mit
fbff076010a5a9fb160fdfd0e69bbab2
29.243902
155
0.658871
4.305556
false
false
false
false
Zewo/Epoch
Sources/Media/JSON/JSONEncodingMedia.swift
2
4884
import Core import Venice extension JSON : EncodingMedia { public func encode(to writable: Writable, deadline: Deadline) throws { let serializer = JSONSerializer() try serializer.serialize(self) { buffer in try writable.write(buffer, deadline: deadline) } } public func topLevel() throws -> EncodingMedia { if isObject { return self } if isArray { return self } throw EncodingError.invalidValue(self, EncodingError.Context()) } public static func makeKeyedContainer() throws -> EncodingMedia { return JSON.object([:]) } public static func makeUnkeyedContainer() throws -> EncodingMedia { return JSON.array([]) } public mutating func encode(_ value: EncodingMedia, forKey key: CodingKey) throws { guard case var .object(object) = self else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [key])) } guard let json = value as? JSON else { throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: [key])) } object[key.stringValue] = json self = .object(object) } public mutating func encode(_ value: EncodingMedia) throws { guard case var .array(array) = self else { throw EncodingError.invalidValue(value, EncodingError.Context()) } guard let json = value as? JSON else { throw EncodingError.invalidValue(value, EncodingError.Context()) } array.append(json) self = .array(array) } public static func encodeNil() throws -> EncodingMedia { return JSON.null } public static func encode(_ value: Bool) throws -> EncodingMedia { return JSON.bool(value) } public static func encode(_ value: Int) throws -> EncodingMedia { return JSON.int(value) } public static func encode(_ value: Int8) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: Int16) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: Int32) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: Int64) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: UInt) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: UInt8) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: UInt16) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: UInt32) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: UInt64) throws -> EncodingMedia { guard let int = Int(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.int(int) } public static func encode(_ value: Float) throws -> EncodingMedia { guard let double = Double(exactly: value) else { throw EncodingError.invalidValue(value, EncodingError.Context()) } return JSON.double(double) } public static func encode(_ value: Double) throws -> EncodingMedia { return JSON.double(value) } public static func encode(_ value: String) throws -> EncodingMedia { return JSON.string(value) } }
mit
14cde887412306810747c6334cf9a017
29.911392
93
0.591728
5.004098
false
false
false
false
ahoppen/swift
stdlib/public/core/NativeSet.swift
4
23099
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A wrapper around __RawSetStorage that provides most of the /// implementation of Set. @usableFromInline @frozen internal struct _NativeSet<Element: Hashable> { /// See the comments on __RawSetStorage and its subclasses to understand why we /// store an untyped storage here. @usableFromInline internal var _storage: __RawSetStorage /// Constructs an instance from the empty singleton. @inlinable @inline(__always) internal init() { self._storage = __RawSetStorage.empty } /// Constructs a native set adopting the given storage. @inlinable @inline(__always) internal init(_ storage: __owned __RawSetStorage) { self._storage = storage } @inlinable internal init(capacity: Int) { if capacity == 0 { self._storage = __RawSetStorage.empty } else { self._storage = _SetStorage<Element>.allocate(capacity: capacity) } } #if _runtime(_ObjC) @inlinable internal init(_ cocoa: __owned __CocoaSet) { self.init(cocoa, capacity: cocoa.count) } @inlinable internal init(_ cocoa: __owned __CocoaSet, capacity: Int) { if capacity == 0 { self._storage = __RawSetStorage.empty } else { _internalInvariant(cocoa.count <= capacity) self._storage = _SetStorage<Element>.convert(cocoa, capacity: capacity) for element in cocoa { let nativeElement = _forceBridgeFromObjectiveC(element, Element.self) insertNew(nativeElement, isUnique: true) } } } #endif } extension _NativeSet { // Primitive fields @usableFromInline internal typealias Bucket = _HashTable.Bucket @inlinable internal var capacity: Int { @inline(__always) get { return _assumeNonNegative(_storage._capacity) } } @_alwaysEmitIntoClient @inline(__always) internal var bucketCount: Int { _assumeNonNegative(_storage._bucketCount) } @inlinable internal var hashTable: _HashTable { @inline(__always) get { return _storage._hashTable } } @inlinable internal var age: Int32 { @inline(__always) get { return _storage._age } } // This API is unsafe and needs a `_fixLifetime` in the caller. @inlinable internal var _elements: UnsafeMutablePointer<Element> { return _storage._rawElements.assumingMemoryBound(to: Element.self) } @inlinable @inline(__always) internal func invalidateIndices() { _storage._age &+= 1 } } extension _NativeSet { // Low-level unchecked operations @inlinable @inline(__always) internal func uncheckedElement(at bucket: Bucket) -> Element { defer { _fixLifetime(self) } _internalInvariant(hashTable.isOccupied(bucket)) return _elements[bucket.offset] } @inlinable @inline(__always) internal func uncheckedInitialize( at bucket: Bucket, to element: __owned Element ) { _internalInvariant(hashTable.isValid(bucket)) (_elements + bucket.offset).initialize(to: element) } @_alwaysEmitIntoClient @inlinable // Introduced in 5.1 @inline(__always) internal func uncheckedAssign( at bucket: Bucket, to element: __owned Element ) { _internalInvariant(hashTable.isOccupied(bucket)) (_elements + bucket.offset).pointee = element } } extension _NativeSet { // Low-level lookup operations @inlinable @inline(__always) internal func hashValue(for element: Element) -> Int { return element._rawHashValue(seed: _storage._seed) } @inlinable @inline(__always) internal func find(_ element: Element) -> (bucket: Bucket, found: Bool) { return find(element, hashValue: self.hashValue(for: element)) } /// Search for a given element, assuming it has the specified hash value. /// /// If the element is not present in this set, return the position where it /// could be inserted. @inlinable @inline(__always) internal func find( _ element: Element, hashValue: Int ) -> (bucket: Bucket, found: Bool) { let hashTable = self.hashTable var bucket = hashTable.idealBucket(forHashValue: hashValue) while hashTable._isOccupied(bucket) { if uncheckedElement(at: bucket) == element { return (bucket, true) } bucket = hashTable.bucket(wrappedAfter: bucket) } return (bucket, false) } } extension _NativeSet { // ensureUnique @inlinable internal mutating func resize(capacity: Int) { let capacity = Swift.max(capacity, self.capacity) let result = _NativeSet(_SetStorage<Element>.resize( original: _storage, capacity: capacity, move: true)) if count > 0 { for bucket in hashTable { let element = (self._elements + bucket.offset).move() result._unsafeInsertNew(element) } // Clear out old storage, ensuring that its deinit won't overrelease the // elements we've just moved out. _storage._hashTable.clear() _storage._count = 0 } _storage = result._storage } @inlinable internal mutating func copyAndResize(capacity: Int) { let capacity = Swift.max(capacity, self.capacity) let result = _NativeSet(_SetStorage<Element>.resize( original: _storage, capacity: capacity, move: false)) if count > 0 { for bucket in hashTable { result._unsafeInsertNew(self.uncheckedElement(at: bucket)) } } _storage = result._storage } @inlinable internal mutating func copy() { let newStorage = _SetStorage<Element>.copy(original: _storage) _internalInvariant(newStorage._scale == _storage._scale) _internalInvariant(newStorage._age == _storage._age) _internalInvariant(newStorage._seed == _storage._seed) let result = _NativeSet(newStorage) if count > 0 { result.hashTable.copyContents(of: hashTable) result._storage._count = self.count for bucket in hashTable { let element = uncheckedElement(at: bucket) result.uncheckedInitialize(at: bucket, to: element) } } _storage = result._storage } /// Ensure storage of self is uniquely held and can hold at least `capacity` /// elements. /// /// -Returns: `true` if contents were rehashed; otherwise, `false`. @inlinable @inline(__always) internal mutating func ensureUnique(isUnique: Bool, capacity: Int) -> Bool { if _fastPath(capacity <= self.capacity && isUnique) { return false } if isUnique { resize(capacity: capacity) return true } if capacity <= self.capacity { copy() return false } copyAndResize(capacity: capacity) return true } internal mutating func reserveCapacity(_ capacity: Int, isUnique: Bool) { _ = ensureUnique(isUnique: isUnique, capacity: capacity) } } extension _NativeSet { @inlinable @inline(__always) func validatedBucket(for index: _HashTable.Index) -> Bucket { _precondition(hashTable.isOccupied(index.bucket) && index.age == age, "Attempting to access Set elements using an invalid index") return index.bucket } @inlinable @inline(__always) func validatedBucket(for index: Set<Element>.Index) -> Bucket { #if _runtime(_ObjC) guard index._isNative else { index._cocoaPath() let cocoa = index._asCocoa // Accept Cocoa indices as long as they contain an element that exists in // this set, and the address of their Cocoa object generates the same age. if cocoa.age == self.age { let element = _forceBridgeFromObjectiveC(cocoa.element, Element.self) let (bucket, found) = find(element) if found { return bucket } } _preconditionFailure( "Attempting to access Set elements using an invalid index") } #endif return validatedBucket(for: index._asNative) } } extension _NativeSet: _SetBuffer { @usableFromInline internal typealias Index = Set<Element>.Index @inlinable internal var startIndex: Index { let bucket = hashTable.startBucket return Index(_native: _HashTable.Index(bucket: bucket, age: age)) } @inlinable internal var endIndex: Index { let bucket = hashTable.endBucket return Index(_native: _HashTable.Index(bucket: bucket, age: age)) } @inlinable internal func index(after index: Index) -> Index { // Note that _asNative forces this not to work on Cocoa indices. let bucket = validatedBucket(for: index._asNative) let next = hashTable.occupiedBucket(after: bucket) return Index(_native: _HashTable.Index(bucket: next, age: age)) } @inlinable @inline(__always) internal func index(for element: Element) -> Index? { if count == 0 { // Fast path that avoids computing the hash of the key. return nil } let (bucket, found) = find(element) guard found else { return nil } return Index(_native: _HashTable.Index(bucket: bucket, age: age)) } @inlinable internal var count: Int { @inline(__always) get { return _assumeNonNegative(_storage._count) } } @inlinable @inline(__always) internal func contains(_ member: Element) -> Bool { // Fast path: Don't calculate the hash if the set has no elements. if count == 0 { return false } return find(member).found } @inlinable @inline(__always) internal func element(at index: Index) -> Element { let bucket = validatedBucket(for: index) return uncheckedElement(at: bucket) } } // This function has a highly visible name to make it stand out in stack traces. @usableFromInline @inline(never) internal func ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS( _ elementType: Any.Type ) -> Never { _assertionFailure( "Fatal error", """ Duplicate elements of type '\(elementType)' were found in a Set. This usually means either that the type violates Hashable's requirements, or that members of such a set were mutated after insertion. """, flags: _fatalErrorFlags()) } extension _NativeSet { // Insertions /// Insert a new element into uniquely held storage. /// Storage must be uniquely referenced with adequate capacity. /// The `element` must not be already present in the Set. @inlinable internal func _unsafeInsertNew(_ element: __owned Element) { _internalInvariant(count + 1 <= capacity) let hashValue = self.hashValue(for: element) if _isDebugAssertConfiguration() { // In debug builds, perform a full lookup and trap if we detect duplicate // elements -- these imply that the Element type violates Hashable // requirements. This is generally more costly than a direct insertion, // because we'll need to compare elements in case of hash collisions. let (bucket, found) = find(element, hashValue: hashValue) guard !found else { ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self) } hashTable.insert(bucket) uncheckedInitialize(at: bucket, to: element) } else { let bucket = hashTable.insertNew(hashValue: hashValue) uncheckedInitialize(at: bucket, to: element) } _storage._count &+= 1 } /// Insert a new element into uniquely held storage. /// Storage must be uniquely referenced. /// The `element` must not be already present in the Set. @inlinable internal mutating func insertNew(_ element: __owned Element, isUnique: Bool) { _ = ensureUnique(isUnique: isUnique, capacity: count + 1) _unsafeInsertNew(element) } @inlinable internal func _unsafeInsertNew(_ element: __owned Element, at bucket: Bucket) { hashTable.insert(bucket) uncheckedInitialize(at: bucket, to: element) _storage._count += 1 } @inlinable internal mutating func insertNew( _ element: __owned Element, at bucket: Bucket, isUnique: Bool ) { _internalInvariant(!hashTable.isOccupied(bucket)) var bucket = bucket let rehashed = ensureUnique(isUnique: isUnique, capacity: count + 1) if rehashed { let (b, f) = find(element) if f { ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self) } bucket = b } _unsafeInsertNew(element, at: bucket) } @inlinable internal mutating func update( with element: __owned Element, isUnique: Bool ) -> Element? { var (bucket, found) = find(element) let rehashed = ensureUnique( isUnique: isUnique, capacity: count + (found ? 0 : 1)) if rehashed { let (b, f) = find(element) if f != found { ELEMENT_TYPE_OF_SET_VIOLATES_HASHABLE_REQUIREMENTS(Element.self) } bucket = b } if found { let old = (_elements + bucket.offset).move() uncheckedInitialize(at: bucket, to: element) return old } _unsafeInsertNew(element, at: bucket) return nil } /// Insert an element into uniquely held storage, replacing an existing value /// (if any). Storage must be uniquely referenced with adequate capacity. @_alwaysEmitIntoClient @inlinable // Introduced in 5.1 internal mutating func _unsafeUpdate( with element: __owned Element ) { let (bucket, found) = find(element) if found { uncheckedAssign(at: bucket, to: element) } else { _precondition(count < capacity) _unsafeInsertNew(element, at: bucket) } } } extension _NativeSet { @inlinable @inline(__always) func isEqual(to other: _NativeSet) -> Bool { if self._storage === other._storage { return true } if self.count != other.count { return false } for member in self { guard other.find(member).found else { return false } } return true } #if _runtime(_ObjC) @inlinable func isEqual(to other: __CocoaSet) -> Bool { if self.count != other.count { return false } defer { _fixLifetime(self) } for bucket in self.hashTable { let key = self.uncheckedElement(at: bucket) let bridgedKey = _bridgeAnythingToObjectiveC(key) guard other.contains(bridgedKey) else { return false } } return true } #endif } extension _NativeSet: _HashTableDelegate { @inlinable @inline(__always) internal func hashValue(at bucket: Bucket) -> Int { return hashValue(for: uncheckedElement(at: bucket)) } @inlinable @inline(__always) internal func moveEntry(from source: Bucket, to target: Bucket) { (_elements + target.offset) .moveInitialize(from: _elements + source.offset, count: 1) } } extension _NativeSet { // Deletion @inlinable @_effects(releasenone) internal mutating func _delete(at bucket: Bucket) { hashTable.delete(at: bucket, with: self) _storage._count -= 1 _internalInvariant(_storage._count >= 0) invalidateIndices() } @inlinable @inline(__always) internal mutating func uncheckedRemove( at bucket: Bucket, isUnique: Bool) -> Element { _internalInvariant(hashTable.isOccupied(bucket)) let rehashed = ensureUnique(isUnique: isUnique, capacity: capacity) _internalInvariant(!rehashed) let old = (_elements + bucket.offset).move() _delete(at: bucket) return old } @usableFromInline internal mutating func removeAll(isUnique: Bool) { guard isUnique else { let scale = self._storage._scale _storage = _SetStorage<Element>.allocate( scale: scale, age: nil, seed: nil) return } for bucket in hashTable { (_elements + bucket.offset).deinitialize(count: 1) } hashTable.clear() _storage._count = 0 invalidateIndices() } } extension _NativeSet: Sequence { @usableFromInline @frozen internal struct Iterator { // The iterator is iterating over a frozen view of the collection state, so // it keeps its own reference to the set. @usableFromInline internal let base: _NativeSet @usableFromInline internal var iterator: _HashTable.Iterator @inlinable @inline(__always) init(_ base: __owned _NativeSet) { self.base = base self.iterator = base.hashTable.makeIterator() } } @inlinable @inline(__always) internal __consuming func makeIterator() -> Iterator { return Iterator(self) } } extension _NativeSet.Iterator: IteratorProtocol { @inlinable @inline(__always) internal mutating func next() -> Element? { guard let index = iterator.next() else { return nil } return base.uncheckedElement(at: index) } } extension _NativeSet { @_alwaysEmitIntoClient internal func isSubset<S: Sequence>(of possibleSuperset: S) -> Bool where S.Element == Element { _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in // Mark elements in self that we've seen in `possibleSuperset`. var seenCount = 0 for element in possibleSuperset { let (bucket, found) = find(element) guard found else { continue } let inserted = seen.uncheckedInsert(bucket.offset) if inserted { seenCount += 1 if seenCount == self.count { return true } } } return false } } @_alwaysEmitIntoClient internal func isStrictSubset<S: Sequence>(of possibleSuperset: S) -> Bool where S.Element == Element { _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in // Mark elements in self that we've seen in `possibleSuperset`. var seenCount = 0 var isStrict = false for element in possibleSuperset { let (bucket, found) = find(element) guard found else { if !isStrict { isStrict = true if seenCount == self.count { return true } } continue } let inserted = seen.uncheckedInsert(bucket.offset) if inserted { seenCount += 1 if seenCount == self.count, isStrict { return true } } } return false } } @_alwaysEmitIntoClient internal func isStrictSuperset<S: Sequence>(of possibleSubset: S) -> Bool where S.Element == Element { _UnsafeBitset.withTemporaryBitset(capacity: self.bucketCount) { seen in // Mark elements in self that we've seen in `possibleStrictSubset`. var seenCount = 0 for element in possibleSubset { let (bucket, found) = find(element) guard found else { return false } let inserted = seen.uncheckedInsert(bucket.offset) if inserted { seenCount += 1 if seenCount == self.count { return false } } } return true } } @_alwaysEmitIntoClient internal __consuming func extractSubset( using bitset: _UnsafeBitset, count: Int ) -> _NativeSet { var count = count if count == 0 { return _NativeSet() } if count == self.count { return self } let result = _NativeSet(capacity: count) for offset in bitset { result._unsafeInsertNew(self.uncheckedElement(at: Bucket(offset: offset))) // The hash table can have set bits after the end of the bitmap. // Ignore them. count -= 1 if count == 0 { break } } return result } @_alwaysEmitIntoClient internal __consuming func subtracting<S: Sequence>(_ other: S) -> _NativeSet where S.Element == Element { guard count > 0 else { return _NativeSet() } // Find one item that we need to remove before creating a result set. var it = other.makeIterator() var bucket: Bucket? = nil while let next = it.next() { let (b, found) = find(next) if found { bucket = b break } } guard let bucket = bucket else { return self } // Rather than directly creating a new set, calculate the difference in a // bitset first. This ensures we hash each element (in both sets) only once, // and that we'll have an exact count for the result set, preventing // rehashings during insertions. return _UnsafeBitset.withTemporaryCopy(of: hashTable.bitset) { difference in var remainingCount = self.count let removed = difference.uncheckedRemove(bucket.offset) _internalInvariant(removed) remainingCount -= 1 while let element = it.next() { let (bucket, found) = find(element) if found { if difference.uncheckedRemove(bucket.offset) { remainingCount -= 1 if remainingCount == 0 { return _NativeSet() } } } } _internalInvariant(difference.count > 0) return extractSubset(using: difference, count: remainingCount) } } @_alwaysEmitIntoClient internal __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> _NativeSet<Element> { try _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in var count = 0 for bucket in hashTable { if try isIncluded(uncheckedElement(at: bucket)) { bitset.uncheckedInsert(bucket.offset) count += 1 } } return extractSubset(using: bitset, count: count) } } @_alwaysEmitIntoClient internal __consuming func intersection( _ other: _NativeSet<Element> ) -> _NativeSet<Element> { // Prefer to iterate over the smaller set. However, we must be careful to // only include elements from `self`, not `other`. guard self.count <= other.count else { return genericIntersection(other) } // Rather than directly creating a new set, mark common elements in a bitset // first. This minimizes hashing, and ensures that we'll have an exact count // for the result set, preventing rehashings during insertions. return _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in var count = 0 for bucket in hashTable { if other.find(uncheckedElement(at: bucket)).found { bitset.uncheckedInsert(bucket.offset) count += 1 } } return extractSubset(using: bitset, count: count) } } @_alwaysEmitIntoClient internal __consuming func genericIntersection<S: Sequence>( _ other: S ) -> _NativeSet<Element> where S.Element == Element { // Rather than directly creating a new set, mark common elements in a bitset // first. This minimizes hashing, and ensures that we'll have an exact count // for the result set, preventing rehashings during insertions. _UnsafeBitset.withTemporaryBitset(capacity: bucketCount) { bitset in var count = 0 for element in other { let (bucket, found) = find(element) if found { bitset.uncheckedInsert(bucket.offset) count += 1 } } return extractSubset(using: bitset, count: count) } } }
apache-2.0
683b7b5b6edaa58446a9f521b9299bbc
28.538363
81
0.650894
4.311928
false
false
false
false
ahoppen/swift
test/stmt/foreach.swift
4
6729
// RUN: %target-typecheck-verify-swift // Bad containers and ranges struct BadContainer1 { } func bad_containers_1(bc: BadContainer1) { for e in bc { } // expected-error{{for-in loop requires 'BadContainer1' to conform to 'Sequence'}} } struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}} var generate : Int } func bad_containers_2(bc: BadContainer2) { for e in bc { } } struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}} func makeIterator() { } // expected-note{{candidate can not infer 'Iterator' = '()' because '()' is not a nominal type and so can't conform to 'IteratorProtocol'}} } func bad_containers_3(bc: BadContainer3) { for e in bc { } } struct BadIterator1 {} struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}} typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'BadContainer4.Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}} func makeIterator() -> BadIterator1 { } } func bad_containers_4(bc: BadContainer4) { for e in bc { } } // Pattern type-checking struct GoodRange<Int> : Sequence, IteratorProtocol { typealias Element = Int func next() -> Int? {} typealias Iterator = GoodRange<Int> func makeIterator() -> GoodRange<Int> { return self } } struct GoodTupleIterator: Sequence, IteratorProtocol { typealias Element = (Int, Float) func next() -> (Int, Float)? {} typealias Iterator = GoodTupleIterator func makeIterator() -> GoodTupleIterator {} } protocol ElementProtocol {} func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) { var sum : Int var sumf : Float for i : Int in gir { sum = sum + i } for i in gir { sum = sum + i } for f : Float in gir { sum = sum + f } // expected-error{{cannot convert sequence element type 'GoodRange<Int>.Element' (aka 'Int') to expected type 'Float'}} for f : ElementProtocol in gir { } // expected-error {{sequence element type 'GoodRange<Int>.Element' (aka 'Int') does not conform to expected protocol 'ElementProtocol'}} for (i, f) : (Int, Float) in gtr { sum = sum + i } for (i, f) in gtr { sum = sum + i sumf = sumf + f sum = sum + f // expected-error {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{17-17=Int(}} {{18-18=)}} } for (i, _) : (Int, Float) in gtr { sum = sum + i } for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{cannot convert sequence element type 'GoodTupleIterator.Element' (aka '(Int, Float)') to expected type '(Int, Int)'}} for (i, f) in gtr {} } func slices(i_s: [Int], ias: [[Int]]) { var sum = 0 for i in i_s { sum = sum + i } for ia in ias { for i in ia { sum = sum + i } } } func discard_binding() { for _ in [0] {} } struct X<T> { var value: T } struct Gen<T> : IteratorProtocol { func next() -> T? { return nil } } struct Seq<T> : Sequence { func makeIterator() -> Gen<T> { return Gen() } } func getIntSeq() -> Seq<Int> { return Seq() } func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}} func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}} func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}} func getGenericSeq<T>() -> Seq<T> { return Seq() } func getXIntSeq() -> Seq<X<Int>> { return Seq() } func getXIntSeqIUO() -> Seq<X<Int>>! { return nil } func testForEachInference() { for i in getIntSeq() { } // Overloaded sequence resolved contextually for i: Int in getOvlSeq() { } for d: Double in getOvlSeq() { } // Overloaded sequence not resolved contextually for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}} // Generic sequence resolved contextually for i: Int in getGenericSeq() { } for d: Double in getGenericSeq() { } // Inference of generic arguments in the element type from the // sequence. for x: X in getXIntSeq() { let z = x.value + 1 } for x: X in getOvlSeq() { let z = x.value + 1 } // Inference with implicitly unwrapped optional for x: X in getXIntSeqIUO() { let z = x.value + 1 } // Range overloading. for i: Int8 in 0..<10 { } for i: UInt in 0...10 { } } func testMatchingPatterns() { // <rdar://problem/21428712> for case parse failure let myArray : [Int?] = [] for case .some(let x) in myArray { _ = x } // <rdar://problem/21392677> for/case/in patterns aren't parsed properly class A {} class B : A {} class C : A {} let array : [A] = [A(), B(), C()] for case (let x as B) in array { _ = x } } // <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great func testOptionalSequence() { let array : [Int]? for x in array { // expected-error {{for-in loop requires '[Int]?' to conform to 'Sequence'; did you mean to unwrap optional?}} } } // FIXME: Should this be allowed? func testExistentialSequence(s: any Sequence) { for x in s { // expected-error {{type 'any Sequence' cannot conform to 'Sequence'}} expected-note {{only concrete types such as structs, enums and classes can conform to protocols}} _ = x } } // Conditional conformance to Sequence and IteratorProtocol. protocol P { } struct RepeatedSequence<T> { var value: T var count: Int } struct RepeatedIterator<T> { var value: T var count: Int } extension RepeatedIterator: IteratorProtocol where T: P { typealias Element = T mutating func next() -> T? { if count == 0 { return nil } count = count - 1 return value } } extension RepeatedSequence: Sequence where T: P { typealias Element = T typealias Iterator = RepeatedIterator<T> typealias SubSequence = AnySequence<T> func makeIterator() -> RepeatedIterator<T> { return Iterator(value: value, count: count) } } extension Int : P { } func testRepeated(ri: RepeatedSequence<Int>) { for x in ri { _ = x } } // SR-12398: Poor pattern matching diagnostic: "for-in loop requires '[Int]' to conform to 'Sequence'" func sr_12398(arr1: [Int], arr2: [(a: Int, b: String)]) { for (x, y) in arr1 {} // expected-error@-1 {{tuple pattern cannot match values of non-tuple type 'Int'}} for (x, y, _) in arr2 {} // expected-error@-1 {{pattern cannot match values of type '(a: Int, b: String)'}} } // rdar://62339835 func testForEachWhereWithClosure(_ x: [Int]) { func foo<T>(_ fn: () -> T) -> Bool { true } for i in x where foo({ i }) {} for i in x where foo({ i.byteSwapped == 5 }) {} for i in x where x.contains(where: { $0.byteSwapped == i }) {} }
apache-2.0
a5a25a9dde646e1f48b9080b17011ced
27.0375
187
0.648982
3.491956
false
false
false
false
samritchie/BSImagePicker
Pod/Classes/Model/AssetCollectionDataSource.swift
6
2959
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Photos final class AssetCollectionDataSource : NSObject, SelectableDataSource { private var assetCollection: PHAssetCollection var selections: [PHObject] = [] var delegate: SelectableDataDelegate? var allowsMultipleSelection: Bool = false var maxNumberOfSelections: Int = 1 var selectedIndexPaths: [NSIndexPath] { get { if selections.count > 0 { return [NSIndexPath(forItem: 0, inSection: 0)] } else { return [] } } } required init(assetCollection: PHAssetCollection) { self.assetCollection = assetCollection super.init() } // MARK: SelectableDataSource var sections: Int { get { return 1 } } func numberOfObjectsInSection(section: Int) -> Int { return 1 } func objectAtIndexPath(indexPath: NSIndexPath) -> PHObject { assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row") return assetCollection } func selectObjectAtIndexPath(indexPath: NSIndexPath) { assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row") selections = [assetCollection] } func deselectObjectAtIndexPath(indexPath: NSIndexPath) { assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row") selections = [] } func isObjectAtIndexPathSelected(indexPath: NSIndexPath) -> Bool { assert(indexPath.section < 1 && indexPath.row < 1, "AssetCollectionDataSource can only contain 1 section and row") return selections.count > 0 } }
mit
e1d73580a6dccde4454badf1e5dbcf05
36.443038
122
0.682894
5.013559
false
false
false
false
oboehm/CashClock2
CashClock2/ClockCalculator.swift
1
5990
// // Copyright (c) 2015 Oliver Boehm. All rights reserved. // // This file is part of CashClock2. // // CashClock2 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. // // CashClock2 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 CashClock2. If not, see <http://www.gnu.org/licenses/>. // // (c)reated by oliver on 19.03.15 ([email protected]) import Foundation /** * This protocol is placed here in this file because otherwise I got an * strange compiler error */ protocol ClockObserver { func update(time:NSTimeInterval, money:Double) } /** * This ClockCalculator measures time and money. * * The average labor costs in Germany are about 31 Euros / hour * in general and 42,10 Euro / hour in the computer and communication * industrie. Because I think that this app will be mainly used in * this area we use about 40 Euro for initialization. * * http://www.heise.de/resale/artikel/Arbeitskosten-in-Deutschland-ueberdurchschnittlich-hoch-1830055.html * https://www.destatis.de/DE/Publikationen/StatistischesJahrbuch/VerdiensteArbeitskosten.pdf */ class ClockCalculator:NSObject, NSCoding { var numberOfPersons = 1 var costPerHour = 40 var totalCost = 0.0 var startTime:NSTimeInterval = 0 var currentTime:NSTimeInterval = 0 var elapsedTime:NSTimeInterval = 0 var timer:NSTimer? = nil var observers:[ClockObserver] = [] func addObserver(observer:ClockObserver) -> Int { self.observers.append(observer) print("ClockCalculator.\(__FUNCTION__): \(observer) is added as \(observers.count) observer.") return self.observers.count - 1 } func removeObserver(i:Int) { self.observers.removeAtIndex(i) } func startTimer() { resetTimer() continueTimer() } func stopTimer() { timer?.invalidate() timer = nil updateTimeAndMoney() print("ClockCalculator.\(__FUNCTION__): timer is stopped.") } func continueTimer() { startTime = NSDate.timeIntervalSinceReferenceDate() currentTime = startTime timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateTimeAndMoney", userInfo: nil, repeats: true) print("ClockCalculator.\(__FUNCTION__): timer is started (again).") } func resetTimer() { elapsedTime = 0 totalCost = 0.0 print("ClockCalculator.\(__FUNCTION__): timer is resetted.") } /** * This is the method where the business logic happens. The costs of the * last interval is calculated and with the result the total costs and * elapsed time is updated. */ func updateTimeAndMoney() { currentTime = NSDate.timeIntervalSinceReferenceDate() let interval = currentTime - startTime assert(interval >= 0, "invalid startTime: \(startTime)") let intervalCost = Double(interval) * Double(costPerHour * numberOfPersons) / 3600.0 totalCost += intervalCost elapsedTime += interval startTime = currentTime for obsrv in observers { obsrv.update(elapsedTime, money: totalCost) } } /** * The calculation of the total costs is now done in * updateTimeAndMoney(). */ func getTime() -> NSTimeInterval { return elapsedTime } /** * The calculation of the total costs is now done in * updateTimeAndMoney(). */ func getMoney() -> Double { return totalCost } ///// Persistence Section ////////////////////////////////////////////////// // see http://www.ioscampus.de/leicht-gemacht-daten-speichern/ /** * This is the required init protocol. * see http://nshipster.com/nscoding/ */ required convenience init?(coder decoder: NSCoder) { self.init() self.costPerHour = decoder.decodeIntegerForKey("costPerHour") self.numberOfPersons = decoder.decodeIntegerForKey("numberOfPersons") } /** * This method is needed for the NSCoding protokoll. */ func encodeWithCoder(coder:NSCoder) { coder.encodeInt(Int32(self.costPerHour), forKey: "costPerHour") coder.encodeInt(Int32(self.numberOfPersons), forKey: "numberOfPersons") } /** * Save data. * see http://nshipster.com/nscoding/ */ func save() { let data = NSKeyedArchiver.archivedDataWithRootObject(self) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "CashClock") print("ClockCalculator.\(__FUNCTION__): CostPerHour=\(costPerHour), NumberOfPersons=\(numberOfPersons) saved.") } /** * Load data. * see http://nshipster.com/nscoding/ */ func load() { let defaults = NSUserDefaults.standardUserDefaults() if let data = defaults.objectForKey("CashClock") as? NSData { if let clockData = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? ClockCalculator { self.costPerHour = clockData.costPerHour; self.numberOfPersons = clockData.numberOfPersons; print("ClockCalculator.\(__FUNCTION__): CostPerHour=\(costPerHour), NumberOfPersons=\(numberOfPersons) loaded.") } else { print("ClockCalculator.\(__FUNCTION__): no calcuator data stored - nothing loaded.") } } else { print("ClockCalculator.\(__FUNCTION__): nothing loaded - no data found.") } } }
gpl-3.0
90016223726f6dae7c91e9354abf8b58
33.039773
128
0.642905
4.44362
false
false
false
false
nuudles/AbstractView
AbstractView/Shapes/OvalShape.swift
1
1297
// // OvalShape.swift // AbstractView // // Created by Christopher Luu on 11/17/15. // Copyright © 2015 Nuudles. All rights reserved. // import Foundation public struct OvalShape: AbstractShape { // MARK: - Public constants public static let ovalShapeInitializer: ShapeInitializer = { (relativeFrame: CGRect, color: UIColor) in return OvalShape(relativeFrame: relativeFrame, color: color) } public static let circleShapeInitializer: ShapeInitializer = { (relativeFrame: CGRect, color: UIColor) in let radius = min(relativeFrame.size.width, relativeFrame.size.height) return OvalShape(relativeFrame: CGRect(x: relativeFrame.origin.x, y: relativeFrame.origin.y, width: radius, height: radius), color: color) } // MARK: - Public properties public var relativeFrame: CGRect public var color: UIColor // MARK: - Initialization methods public init(relativeFrame: CGRect, color: UIColor) { self.relativeFrame = relativeFrame self.color = color } // MARK: - AbstractShape methods public func drawInContext(context: CGContextRef, forRect rect: CGRect) { CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) CGContextFillEllipseInRect(context, rect) CGContextStrokeEllipseInRect(context, rect) } }
mit
8bca1cd77580b0f827fc4e94939be27c
27.8
140
0.762346
3.681818
false
false
false
false
jkloo/Evolution
Evolution/GameScene.swift
1
4165
// // GameScene.swift // Evolution // // Created by Jeff Kloosterman on 8/22/15. // Copyright (c) 2015 Jeff Kloosterman. All rights reserved. // import SpriteKit extension CollectionType where Index == Int { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffleInPlace() return list } } extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i swap(&self[i], &self[j]) } } } extension UIColor { static func random() -> UIColor { return UIColor(red: CGFloat.randomOne(), green: CGFloat.randomOne(), blue: CGFloat.randomOne(), alpha: 1) } func mutate() -> UIColor { var r : CGFloat = 0 var g : CGFloat = 0 var b : CGFloat = 0 var a : CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return UIColor(red: r + CGFloat.randomRange(-0.01, max: 0.01), green: g + CGFloat.randomRange(-0.01, max: 0.01), blue: b + CGFloat.randomRange(-0.01, max: 0.01), alpha: a) } func distanceToColor(color : UIColor) -> Float { var r0 : CGFloat = 0 var g0 : CGFloat = 0 var b0 : CGFloat = 0 var a0 : CGFloat = 0 self.getRed(&r0, green: &g0, blue: &b0, alpha: &a0) var r1 : CGFloat = 0 var g1 : CGFloat = 0 var b1 : CGFloat = 0 var a1 : CGFloat = 0 color.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) return Float(sqrt(pow((r0 - r1), 2) + pow((g0 - g1), 2) + pow((b0 - b1), 2))) } } extension CGFloat { static func randomOne() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UINT32_MAX) } static func randomNumber(max : CGFloat) -> CGFloat { return CGFloat.randomOne() * max } static func randomRange(min : CGFloat, max : CGFloat) -> CGFloat { return min + CGFloat.randomNumber(max - min) } } class GameScene: SKScene { var creatures : [SKShapeNode] = [] func seed(n : Int = 28) { for i in 0 ..< n { let radius = 40 let diameter = 2 * radius let x = (i * diameter + radius) % Int(self.view!.frame.width) let y = (i / (Int(self.view!.frame.width) / diameter) * diameter + radius) let creature = SKShapeNode(circleOfRadius: CGFloat(radius - 2)) creature.strokeColor = UIColor.clearColor() creature.position = CGPoint(x: x, y: y) creature.fillColor = UIColor.random() self.creatures.append(creature) } } override func didMoveToView(view: SKView) { self.backgroundColor = UIColor.random() self.seed() for creature in self.creatures { self.addChild(creature) } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ var sortedCreatures = self.creatures.sort { [unowned self] in $0.fillColor.distanceToColor(self.backgroundColor) < $1.fillColor.distanceToColor(self.backgroundColor) } if sortedCreatures.last!.fillColor.distanceToColor(self.backgroundColor) < 0.01 { self.backgroundColor = UIColor.random() } for _ in 0 ..< self.creatures.count / 20 { let removed = sortedCreatures.last! sortedCreatures.removeLast() let copy = sortedCreatures.first! removed.fillColor = copy.fillColor } for _ in 0 ..< self.creatures.count / 10 { let randomIndex = Int(arc4random_uniform(UInt32(sortedCreatures.count))) self.creatures[randomIndex].fillColor = self.creatures[randomIndex].fillColor.mutate() } } }
mit
46fe18971869eb4b716a957e4896663d
30.55303
175
0.565906
3.921846
false
false
false
false
rnystrom/GitHawk
Pods/StyledTextKit/Source/StyledTextBuilder.swift
1
5338
// // StyledTextKitBuilder.swift // StyledTextKit // // Created by Ryan Nystrom on 12/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import UIKit public final class StyledTextBuilder: Hashable, Equatable { internal var styledTexts: [StyledText] internal var savedStyles = [TextStyle]() public convenience init(styledText: StyledText) { self.init(styledTexts: [styledText]) } public convenience init(text: String) { self.init(styledText: StyledText(storage: .text(text))) } public convenience init(attributedText: NSAttributedString) { self.init(styledText: StyledText(storage: .attributedText(attributedText))) } public init(styledTexts: [StyledText]) { self.styledTexts = styledTexts } public var tipAttributes: [NSAttributedStringKey: Any]? { return styledTexts.last?.style.attributes } public var count: Int { return styledTexts.count } @discardableResult public func save() -> StyledTextBuilder { if let last = styledTexts.last?.style { savedStyles.append(last) } return self } @discardableResult public func restore() -> StyledTextBuilder { guard let last = savedStyles.last else { return self } savedStyles.removeLast() return add(styledText: StyledText(style: last)) } @discardableResult public func add(styledTexts: [StyledText]) -> StyledTextBuilder { self.styledTexts += styledTexts return self } @discardableResult public func add(styledText: StyledText) -> StyledTextBuilder { return add(styledTexts: [styledText]) } @discardableResult public func add(style: TextStyle) -> StyledTextBuilder { return add(styledText: StyledText(style: style)) } @discardableResult public func add( text: String, traits: UIFontDescriptorSymbolicTraits? = nil, attributes: [NSAttributedStringKey: Any]? = nil ) -> StyledTextBuilder { return add(storage: .text(text), traits: traits, attributes: attributes) } @discardableResult public func add( attributedText: NSAttributedString, traits: UIFontDescriptorSymbolicTraits? = nil, attributes: [NSAttributedStringKey: Any]? = nil ) -> StyledTextBuilder { return add(storage: .attributedText(attributedText), traits: traits, attributes: attributes) } @discardableResult public func add( storage: StyledText.Storage = .text(""), traits: UIFontDescriptorSymbolicTraits? = nil, attributes: [NSAttributedStringKey: Any]? = nil ) -> StyledTextBuilder { guard let tip = styledTexts.last else { return self } var nextAttributes = tip.style.attributes if let attributes = attributes { for (k, v) in attributes { nextAttributes[k] = v } } let nextStyle: TextStyle if let traits = traits { let tipFontDescriptor: UIFontDescriptor switch tip.style.font { case .descriptor(let descriptor): tipFontDescriptor = descriptor default: tipFontDescriptor = tip.style.font(contentSizeCategory: .medium).fontDescriptor } nextStyle = TextStyle( font: .descriptor(tipFontDescriptor.withSymbolicTraits(traits) ?? tipFontDescriptor), size: tip.style.size, attributes: nextAttributes, minSize: tip.style.minSize, maxSize: tip.style.maxSize ) } else { nextStyle = TextStyle( font: tip.style.font, size: tip.style.size, attributes: nextAttributes, minSize: tip.style.minSize, maxSize: tip.style.maxSize ) } return add(styledText: StyledText(storage: storage, style: nextStyle)) } @discardableResult public func add( image: UIImage, options: [StyledText.ImageFitOptions] = [.fit, .center], attributes: [NSAttributedStringKey: Any]? = nil ) -> StyledTextBuilder { return add(storage: .image(image, options), attributes: attributes) } @discardableResult public func clearText() -> StyledTextBuilder { guard let tipStyle = styledTexts.last?.style else { return self } styledTexts.removeAll() return add(styledText: StyledText(style: tipStyle)) } public func build(renderMode: StyledTextString.RenderMode = .trimWhitespaceAndNewlines) -> StyledTextString { return StyledTextString(styledTexts: styledTexts, renderMode: renderMode) } // MARK: Hashable public var hashValue: Int { guard let seed: Int = styledTexts.first?.hashValue else { return 0 } let count = styledTexts.count if count > 1 { return styledTexts[1...count].reduce(seed, { $0.combineHash(with: $1) }) } else { return seed } } // MARK: Equatable public static func ==(lhs: StyledTextBuilder, rhs: StyledTextBuilder) -> Bool { if lhs === rhs { return true } return lhs.styledTexts == rhs.styledTexts } }
mit
08cb22f63e86dedd20d63979d81ee156
29.849711
113
0.625632
4.914365
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/Items/FAQCategoryItem.swift
1
4918
// // FAQCategoryItem.swift // WebimClientLibrary // // Created by Nikita Kaberov on 07.02.19. // Copyright © 2019 Webim. 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 /** - author: Nikita Kaberov - copyright: 2019 Webim */ final class FAQCategoryItem { // MARK: - Constants // Raw values equal to field names received in responses from server. private enum JSONField: String { case id = "categoryid" case title = "title" case childs = "childs" } // MARK: - Properties private var id: String? private var title: String? private var children = [Child]() // MARK: - Initialization init(jsonDictionary: [String: Any?]) { if let id = jsonDictionary[JSONField.id.rawValue] as? Int { self.id = String(id) } if let title = jsonDictionary[JSONField.title.rawValue] as? String { self.title = title } if let childs = jsonDictionary[JSONField.childs.rawValue] as? [Any] { for child in childs { if let childValue = child as? [String: Any?] { let childItem = Child(jsonDictionary: childValue) children.append(childItem) } } } } } extension FAQCategoryItem: FAQCategory { func getID() -> String { guard let id = id else { WebimInternalLogger.shared.log(entry: "ID is nil in FAQCategoryItem.\(#function)") return String() } return id } func getTitle() -> String { guard let title = title else { WebimInternalLogger.shared.log(entry: "Title is nil in FAQCategoryItem.\(#function)") return String() } return title } func getItems() -> [FAQItem] { var items = [FAQItem]() for child in children { if child.type == .item, let data = child.data as? FAQItemItem { items.append(data) } } return items } func getSubcategories() -> [FAQCategoryInfo] { var subCategories = [FAQCategoryInfo]() for child in children { if child.type == .category, let data = child.data as? FAQCategoryInfoItem { subCategories.append(data) } } return subCategories } } // MARK: - Equatable extension FAQCategoryItem: Equatable { // MARK: - Methods static func == (lhs: FAQCategoryItem, rhs: FAQCategoryItem) -> Bool { if lhs.id == rhs.id { return true } return false } } final class Child { // MARK: - Constants // Raw values equal to field names received in responses from server. private enum JSONField: String { case type = "type" case data = "data" } // MARK: - Properties public var type: RootType? public var data: Any? // MARK: - Initialization init(jsonDictionary: [String: Any?]) { if let type = jsonDictionary[JSONField.type.rawValue] as? String { switch type { case "item": self.type = .item if let data = jsonDictionary[JSONField.data.rawValue] as? [String: Any?] { self.data = FAQItemItem(jsonDictionary: data) } break case "category": self.type = .category if let data = jsonDictionary[JSONField.data.rawValue] as? [String: Any?] { self.data = FAQCategoryInfoItem(jsonDictionary: data) } break default: self.type = .unknown } } } }
mit
c25077889c1eac2d011e8b0979be82f4
29.351852
97
0.579215
4.490411
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/TalkPageReplyFooterView.swift
3
5001
import UIKit protocol ReplyButtonFooterViewDelegate: class { func tappedReply(from view: TalkPageReplyFooterView) func composeTextDidChange(text: String?) var collectionViewFrame: CGRect { get } } class TalkPageReplyFooterView: SizeThatFitsReusableView { let composeView = TalkPageReplyComposeView(frame: .zero) weak var delegate: ReplyButtonFooterViewDelegate? private let replyButton = ActionButton(frame: .zero) let dividerView = UIView(frame: .zero) private let divComposeSpacing = CGFloat(10) var showingCompose = false { didSet { replyButton.isHidden = showingCompose composeView.isHidden = !showingCompose } } var composeButtonIsDisabled = true { didSet { replyButton.isEnabled = !composeButtonIsDisabled } } private var adjustedMargins: UIEdgeInsets { return UIEdgeInsets(top: layoutMargins.top + 25, left: layoutMargins.left + 5, bottom: layoutMargins.bottom, right: layoutMargins.right + 5) } var composeTextView: ThemeableTextView { return composeView.composeTextView } func resetCompose() { composeView.resetCompose() } override func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize { let semanticContentAttribute: UISemanticContentAttribute = traitCollection.layoutDirection == .rightToLeft ? .forceRightToLeft : .forceLeftToRight let maximumWidth = size.width - adjustedMargins.left - adjustedMargins.right let dividerHeight = CGFloat(1) if !showingCompose { let divReplySpacing = CGFloat(35) let replyButtonBottomMargin = CGFloat(65) let buttonOrigin = CGPoint(x: adjustedMargins.left, y: adjustedMargins.top + dividerHeight + divReplySpacing) var replyButtonFrame = replyButton.wmf_preferredFrame(at: buttonOrigin, maximumSize: CGSize(width: maximumWidth, height: UIView.noIntrinsicMetric), minimumSize: NoIntrinsicSize, alignedBy:semanticContentAttribute, apply: apply) //update frame to be centered if (apply) { replyButtonFrame.origin = CGPoint(x: (size.width / 2) - (replyButtonFrame.width / 2), y: replyButtonFrame.origin.y) replyButton.frame = replyButtonFrame dividerView.frame = CGRect(x: 0, y: adjustedMargins.top, width: size.width, height: dividerHeight) } let finalHeight = adjustedMargins.top + dividerHeight + divReplySpacing + replyButtonFrame.height + replyButtonBottomMargin + adjustedMargins.bottom return CGSize(width: size.width, height: finalHeight) } else { let composeViewOrigin = CGPoint(x: 0, y: adjustedMargins.top + dividerHeight + divComposeSpacing) composeView.layoutMargins = layoutMargins let composeViewSize = composeView.sizeThatFits(size, apply: apply) let composeViewFrame = CGRect(origin: composeViewOrigin, size: composeViewSize) if (apply) { composeView.frame = composeViewFrame dividerView.frame = CGRect(x: 0, y: adjustedMargins.top, width: size.width, height: dividerHeight) } let finalHeight = adjustedMargins.top + dividerHeight + divComposeSpacing + composeViewSize.height + adjustedMargins.bottom return CGSize(width: size.width, height: finalHeight) } } @objc private func tappedReply() { delegate?.tappedReply(from: self) } override func updateFonts(with traitCollection: UITraitCollection) { replyButton.updateFonts(with: traitCollection) } override func setup() { replyButton.setTitle(WMFLocalizedString("talk-pages-reply-button-title", value: "Reply to this discussion", comment: "Text displayed in a reply button for replying to a talk page topic thread."), for: .normal) replyButton.addTarget(self, action: #selector(tappedReply), for: .touchUpInside) addSubview(replyButton) addSubview(dividerView) composeView.isHidden = true composeView.delegate = self addSubview(composeView) super.setup() } } //MARK: Themeable extension TalkPageReplyFooterView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground dividerView.backgroundColor = theme.colors.border replyButton.apply(theme: theme) composeView.apply(theme: theme) } } //MARK: TalkPageReplyComposeViewDelegate extension TalkPageReplyFooterView: TalkPageReplyComposeViewDelegate { func composeTextDidChange(text: String?) { delegate?.composeTextDidChange(text: text) } var collectionViewFrame: CGRect { return delegate?.collectionViewFrame ?? .zero } }
mit
e15f19103ff6f53e228272c9d1b6668f
38.070313
239
0.663867
5.166322
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/Message/MessageTableViewController.swift
1
3470
// // MessageTableViewController.swift // CCWeibo // // Created by 徐才超 on 16/2/2. // Copyright © 2016年 徐才超. All rights reserved. // import UIKit class MessageTableViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() if !isLogin { (view as! VisitorView).setupViews(false, iconName: "visitordiscover_image_message", info: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知") } // 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. } */ }
mit
ea801063e865e189a5ec24f4da78130b
34.020619
157
0.684722
5.452648
false
false
false
false
adrfer/swift
test/SILGen/accessibility_warnings.swift
20
4368
// RUN: %target-parse-verify-swift // RUN: %target-swift-frontend -emit-silgen -o /dev/null %s // This file tests that the AST produced after fixing accessibility warnings // is valid according to SILGen and the verifiers. public struct PublicStruct { public var publicVar = 0 } internal struct InternalStruct { public var publicVar = 0 // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} public private(set) var publicVarPrivateSet = 0 // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} public public(set) var publicVarPublicSet = 0 // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} {{10-22=}} public var publicVarGetOnly: Int { return 0 } // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} public var publicVarGetSet: Int { get { return 0 } set {} } // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} } private struct PrivateStruct { public var publicVar = 0 // expected-warning {{declaring a public var for a private struct}} {{3-9=private}} } extension PublicStruct { public init(x: Int) { self.init() } public var publicVarExtension: Int { get { return 0 } set {} } } extension InternalStruct { public init(x: Int) { self.init() } // expected-warning {{declaring a public initializer for an internal struct}} {{3-9=internal}} public var publicVarExtension: Int { get { return 0 } set {} } // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} } extension PrivateStruct { public init(x: Int) { self.init() } // expected-warning {{declaring a public initializer for a private struct}} {{3-9=private}} public var publicVarExtension: Int { get { return 0 } set {} } // expected-warning {{declaring a public var for a private struct}} {{3-9=private}} } public extension PublicStruct { public func extMemberPublic() {} private func extImplPublic() {} } internal extension PublicStruct { public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } private extension PublicStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } internal extension InternalStruct { public func extMemberInternal() {} // expected-warning {{declaring a public instance method in an internal extension}} {{3-9=internal}} private func extImplInternal() {} } private extension InternalStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } private extension PrivateStruct { public func extMemberPrivate() {} // expected-warning {{declaring a public instance method in a private extension}} {{3-9=private}} private func extImplPrivate() {} } public protocol PublicReadOnlyOperations { var size: Int { get } subscript (_: Int) -> Int { get } } internal struct PrivateSettersForReadOnlyInternal : PublicReadOnlyOperations { public private(set) var size = 0 // expected-warning {{declaring a public var for an internal struct}} {{3-9=internal}} internal private(set) subscript (_: Int) -> Int { // no-warning get { return 42 } set {} } } public class PublicClass { public var publicVar = 0 } internal class InternalClass { public var publicVar = 0 // expected-warning {{declaring a public var for an internal class}} {{3-9=internal}} public private(set) var publicVarPrivateSet = 0 // expected-warning {{declaring a public var for an internal class}} {{3-9=internal}} public public(set) var publicVarPublicSet = 0 // expected-warning {{declaring a public var for an internal class}} {{3-9=internal}} public var publicVarGetOnly: Int { return 0 } // expected-warning {{declaring a public var for an internal class}} {{3-9=internal}} public var publicVarGetSet: Int { get { return 0 } set {} } // expected-warning {{declaring a public var for an internal class}} {{3-9=internal}} } private class PrivateClass { public var publicVar = 0 // expected-warning {{declaring a public var for a private class}} {{3-9=private}} }
apache-2.0
7eb08f030952068351df9c690cf8e07f
39.82243
151
0.719093
4.290766
false
false
false
false
abhayamrastogi/ChatSDKPodSpecs
rgconnectsdk/Config/RGConnectSettings.swift
1
1256
// // RGConnectSettings.swift // rgconnectsdk // // Created by Anurag Agnihotri on 21/07/16. // Copyright © 2016 RoundGlass Partners. All rights reserved. // import Foundation public struct RGConnectSettings { static var BASE_URL: String! = "https://connect.round.glass" static var METEOR_VERSION: String! = "pre2" static let METEOR_SUBSCRIPTIONS: [String] = [ "activeUsers", "subscription", "rocketchat_subscription" ] /** Method to set Base Url to initialize Connection to the Server. - parameter url: Base Url of the Server */ public static func setApiURL(url: String) { RGConnectSettings.BASE_URL = url } /** Method to set Meteor Version to establish DDP Connection to the Server. The version should be compatible with the version accepted by the Server. - parameter meteorVersion: Meteor Version String. */ public static func setMeteorVersion(meteorVersion: String) { RGConnectSettings.METEOR_VERSION = meteorVersion } }
mit
b6e766c341a89d76f12cd998ba7ea670
29.634146
150
0.566534
4.84556
false
false
false
false
dn-m/Collections
Collections/ReplaceElements.swift
1
1894
// // ReplaceElements.swift // Collections // // Created by James Bean on 12/23/16. // // /// - TODO: Move up to `Collection` extension Array { // MARK: - Replace Elements /// Replace element at given `index` with the given `element`. public mutating func replaceElement(at index: Int, with element: Element) throws { guard index >= startIndex && index < endIndex else { throw ArrayError.removalError } remove(at: index) insert(element, at: index) } /// Immutable version of `replaceElement(at:with:)` public func replacingElement(at index: Int, with element: Element) throws -> Array { var copy = self try copy.replaceElement(at: index, with: element) return copy } /// Replace the last element in `Array` with the given `element`. public mutating func replaceLast(with element: Element) throws { guard self.count > 0 else { throw ArrayError.removalError } removeLast() append(element) } /// Replace first element in Array with a new element. /// /// - throws: `ArrayError.removalError` if `self` is empty. public mutating func replaceFirst(with element: Element) throws { try removeFirst() insert(element, at: 0) } /// - returns: A new `Array` with the given `element` inserted at the given `index`, if /// possible. /// /// - throws: `ArrayError` if the given `index` is out of range. public func inserting(_ element: Element, at index: Index) throws -> Array { guard index >= startIndex && index <= endIndex else { throw ArrayError.insertionError } var copy = self copy.insert(element, at: index) return copy } // TODO: Implement immutable versions (`replacingElement(at:with:) -> Array`) }
mit
c18f3a900d6a63dd9f7936e221c87686
25.676056
91
0.608765
4.334096
false
false
false
false
javikr/FSCalendar
SwiftExample/SwiftExample/ViewController.swift
6
1146
// // ViewController.swift // SwiftExample // // Created by Wenchao Ding on 9/3/15. // Copyright (c) 2015 wenchao. All rights reserved. // import UIKit class ViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate { @IBOutlet weak var calendar: FSCalendar! @IBOutlet weak var calendarHeightConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() calendar.selectedDate = NSDate() calendar.scrollDirection = .Vertical calendar.scope = .Month } func calendar(calendar: FSCalendar!, hasEventForDate date: NSDate!) -> Bool { return date.fs_day == 5 } func calendarCurrentPageDidChange(calendar: FSCalendar!) { println("change page to \(calendar.currentPage.fs_string())") } func calendar(calendar: FSCalendar!, didSelectDate date: NSDate!) { println("calendar did select date \(date.fs_string())") } func calendarCurrentScopeWillChange(calendar: FSCalendar!, animated: Bool) { calendarHeightConstraint.constant = calendar.sizeThatFits(CGSizeZero).height } }
mit
4f5b2161fcff4b735be19be121eb305c
26.285714
84
0.679756
4.639676
false
false
false
false
hikelee/cinema
Sources/App/Controllers/HallController.swift
1
3432
import Foundation import Vapor import HTTP class HallAdminController : ChannelBasedController<Hall> { let colors = "red,green,pink,purple,orange,blue,red2,blue3,blue2,green3,red3,green2" typealias Model = Hall override var path:String {return "/admin/cinema/hall"} override func makeRouter(){ super.makeRouter() routerGroup.get("\(path)/index"){try self.index($0)} } func index(_ request: Request) throws -> ResponseRepresentable { if request.data["elements"]?.bool ?? false { return try indexElements(request) } return try renderLeaf(request,"Index",[:]) } func indexElements(_ request: Request) throws -> ResponseRepresentable { let colorArray = colors.components(separatedBy:",") let query = try Hall.query().sort("id",.ascending) let channelId = request.channelId if channelId>0 { //渠道管理员登录 try query.filter("channel_id",channelId) } let dic = try Hall.orders(channelId:channelId).reduce([Int:Order]()){ var dic = $0 if let hallId = $1.hallId?.int, hallId>0,dic[hallId] == nil { dic[hallId] = $1 } return dic } let nodes = try query.all().map {hall->Node in var node = try hall.makeLeafNode() if let id = hall.id?.int, id>0 { if let order = dic[id]{ switch order.state { case .inline: node["message"] = Node("等待播放,等待客户端请求") node["can_stop"] = Node(true) case .ongoing: var message = "正在播放 " for item in try order.items() { if item.isPlaying { if let movieId = item.movieId, let movie = try Movie.load(movieId) { message += movie.title ?? "" } } } node["message"] = Node(message) node["playing"] = Node(true) node["can_stop"] = Node(true) case .stopping: node["message"] = Node("正在停止,等待客户端反馈") default: break; } node["color"] = Node(colorArray[0]) node["order"] = try order.makeNode() node["playing"] = Node(true) }else{ node["color"] = Node(colorArray[1]) node["message"] = Node("空闲") } } return node }.makeNode() return try renderLeaf(request,"IndexElements",["nodes":nodes]) } override func additonalFormData(_ request: Request) throws ->[String:Node]{ var data:[String:Node] = [:] data["states"] = try Model.states.allNode() if let user = request.user { if user.isRoot{ data["projectors"] = try Projector.allNode() }else{ let channelId = user.channelId?.int ?? 0 data["projectors"] = try Projector.channelAllNode(channelId: channelId) } } return data } }
mit
2d0c69e9aa48302835ec60ff37fd63f1
36.730337
100
0.47975
4.703081
false
false
false
false
yonasstephen/swift-of-airbnb
airbnb-main/airbnb-main/AirbnbStar.swift
1
1511
// // AirbnbStar.swift // airbnb-main // // Created by Yonas Stephen on 14/4/17. // Copyright © 2017 Yonas Stephen. All rights reserved. // import UIKit enum AirbnbStarType { case empty, halfEmpty, full } class AirbnbStar: UIView { var type: AirbnbStarType = .empty { didSet { switch type { case .empty: starView.image = UIImage(named: "Star Empty")?.tint(with: Theme.SECONDARY_COLOR) case .halfEmpty: starView.image = UIImage(named: "Star Half Empty")?.tint(with: Theme.SECONDARY_COLOR) case .full: starView.image = UIImage(named: "Star Filled")?.tint(with: Theme.SECONDARY_COLOR) } } } var starView: UIImageView = { let view = UIImageView() view.translatesAutoresizingMaskIntoConstraints = false view.contentMode = .scaleAspectFill return view }() override init(frame: CGRect) { super.init(frame: frame) addSubview(starView) starView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true starView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true starView.heightAnchor.constraint(equalTo: heightAnchor).isActive = true starView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
97bc157424901ad4773cc2a8d4eb0027
28.607843
101
0.619205
4.617737
false
false
false
false
ambas/ColorPicker
Example/ColorPicker/ViewController.swift
1
1772
// // ViewController.swift // ColorPicker // // Created by Ambas on 12/21/2015. // Copyright (c) 2015 Ambas. All rights reserved. // import UIKit import ColorPicker class ViewController: UIViewController, ColorPickerDelegate { @IBOutlet weak var colorPicker: ColorPickerListView! @IBOutlet weak var alignmentOption: UISegmentedControl! @IBOutlet weak var colorView: UIView! @IBOutlet weak var allowDeselectSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() colorPicker.colorPickerDelegate = self } @IBAction func didChangeAlignMent(_ alignmentOption: UISegmentedControl) { switch alignmentOption.selectedSegmentIndex { case 0: colorPicker.alignment = "left" case 1: colorPicker.alignment = "center" case 2: colorPicker.alignment = "right" default: colorPicker.alignment = "left" } } @IBAction func addColor(_ sender: AnyObject) { var colors = colorPicker.colors colors.append("#5EB566") colorPicker.colors = colors } @IBAction func removeColor(_ sender: AnyObject) { var colors = colorPicker.colors colors.popLast() colorPicker.colors = colors } func colorPicker(_ colorPicker: ColorPickerListView, selectedColor: String) { colorView.backgroundColor = UIColor.colorWithHexString(selectedColor) } func colorPicker(_ colorPicker: ColorPickerListView, deselectedColor: String) { colorView.backgroundColor = UIColor.white } @IBAction func changeAllowDeselect(_ allowDeselectSwitch: UISwitch) { colorPicker.allowsDeselection = allowDeselectSwitch.isOn } }
mit
0ad9ab007025ef29ef82f1039aaeb32a
27.126984
83
0.662528
5.151163
false
false
false
false
LYM-mg/MGDS_Swift
MGDS_Swift/MGDS_Swift/Class/Music/PlayMusic/Tools/MGLrcLoadTool.swift
1
4634
// // MGLrcLoadTool.swift // MGDS_Swift // // Created by i-Techsys.com on 17/3/2. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit class MGLrcLoadTool: NSObject { // static let share = MGLrcLoadTool() class func getNetLrcModelsWithUrl(urlStr: String, finished:@escaping ((_ lrcMs: [MGLrcModel] )->())) { NetWorkTools.share.downloadData(type: .get, urlString: urlStr) { (path) in let lrc = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) guard let lrcStrs = lrc?.components(separatedBy: "\n") else { return } var lrcMs: [MGLrcModel] = [MGLrcModel]() for lrc in lrcStrs { if lrc.hasPrefix("[ti:") || lrc.hasPrefix("[ar:") || lrc.hasPrefix("[al:") || lrc.hasPrefix("[by") || lrc.hasPrefix("[offset") || lrc.hasPrefix("[ml") { continue } if lrc.contains("[") || lrc.contains("]") { /// 正常解析歌词 // 1.去掉@“[” let timeAndText = lrc.replacingOccurrences(of: "[", with: "") // 2.将时间和歌词分开 let lrcStrArray = timeAndText.components(separatedBy: "]") let time = lrcStrArray.first let lrcText = lrcStrArray.last // 3.创建一个模型 (开始时间 和 歌词) let lrcModel = MGLrcModel() if time != "" { lrcModel.beginTime = MGTimeTool.getTimeIntervalWithFormatTime(format: time!) } lrcModel.lrcText = lrcText! lrcMs.append(lrcModel) } else { // 3.创建一个模型 (开始时间 和 歌词) let lrcModel = MGLrcModel() lrcModel.lrcText = lrc lrcMs.append(lrcModel) } } // 给数据模型的结束时间赋值 for i in 0..<lrcMs.count { if (i == lrcMs.count - 1) { break; } let lrcM = lrcMs[i]; let nextlrcM = lrcMs[i + 1] lrcM.endTime = nextlrcM.beginTime } finished(lrcMs) } } class func getRowWithCurrentTime(currentTime: TimeInterval,lrcMs: [MGLrcModel]) -> Int { for i in 0..<lrcMs.count { let lrcM = lrcMs[i] if (currentTime >= lrcM.beginTime && currentTime < lrcM.endTime) { return i } } return 0 } } //[ti:0] //[ar:0] //[al:0] //[by:0] //[offset:0] //[00:00.74]刚好遇见你 //[00:03.04] //[00:04.63]作词:高进 //[00:06.17]作曲:高进 //[00:07.71]编曲:关天天 //[00:09.25]演唱:李玉刚 //[00:11.15] //[00:14.00]我们哭了 //[00:16.88]我们笑着 //[00:20.03]我们抬头望天空 //[00:22.86]星星还亮着几颗 //[00:26.04]我们唱着 //[00:29.14]时间的歌 //[00:32.20]才懂得相互拥抱 //[00:35.21]到底是为了什么 //[00:37.85] //[00:38.27]因为我刚好遇见你 //[00:41.72]留下足迹才美丽 //[00:44.81]风吹花落泪如雨 //[00:47.84]因为不想分离 //[00:50.95] //[00:51.19]因为刚好遇见你 //[00:54.10]留下十年的期许 //[00:57.08]如果再相遇 //[01:00.39]我想我会记得你 //[01:03.54] //[01:15.50]我们哭了 //[01:18.41]我们笑着 //[01:21.46]我们抬头望天空 //[01:24.36]星星还亮着几颗 //[01:27.70]我们唱着 //[01:30.64]时间的歌 //[01:33.78]才懂得相互拥抱 //[01:36.72]到底是为了什么 //[01:39.44] //[01:39.83]因为我刚好遇见你 //[01:43.25]留下足迹才美丽 //[01:46.31]风吹花落泪如雨 //[01:49.32]因为不想分离 //[01:52.23] //[01:52.57]因为刚好遇见你 //[01:55.57]留下十年的期许 //[01:58.57]如果再相遇 //[02:01.94]我想我会记得你 //[02:05.07]因为我刚好遇见你 //[02:06.82]留下足迹才美丽 //[02:09.78]风吹花落泪如雨 //[02:12.81]因为不想分离 //[02:15.70] //[02:16.03]因为刚好遇见你 //[02:19.08]留下十年的期许 //[02:22.02]如果再相遇 //[02:25.43]我想我会记得你 //[02:29.01] //[02:31.18]因为我刚好遇见你 //[02:34.44]留下足迹才美丽 //[02:37.47]风吹花落泪如雨 //[02:40.54]因为不想分离 //[02:43.35] //[02:43.81]因为刚好遇见你 //[02:46.78]留下十年的期许 //[02:49.87]如果再相遇 //[02:52.97]我想我会记得你 //[02:56.83]
mit
b79af32040c4791b95a4e46d22c23458
26.35461
169
0.508945
2.595559
false
false
false
false
kevintavog/PeachMetadata
source/PeachMetadata/ImportProgressWindowsController.swift
1
2887
// // // import AppKit import Async import RangicCore class ImportProgressWindowsController : NSWindowController, ImportProgress { @IBOutlet weak var overviewLabel: NSTextField! @IBOutlet weak var overviewDestination: NSTextField! @IBOutlet weak var stepLabel: NSTextField! @IBOutlet var detailTextView: NSTextView! @IBOutlet weak var cancelCloseButton: NSButton! var importFolder = String() var destinationFolder = String() var originalMediaData = [MediaData]() var exportedMediaData = [MediaData]() var isRunningImport = false func start(_ importFolder: String, destinationFolder: String, originalMediaData: [MediaData], exportedMediaData: [MediaData]) { self.importFolder = importFolder self.destinationFolder = destinationFolder self.originalMediaData = originalMediaData self.exportedMediaData = exportedMediaData overviewLabel.stringValue = "Importing from \(importFolder)" overviewDestination.stringValue = "to \(destinationFolder)" stepLabel.stringValue = "" detailTextView.string = "" isRunningImport = true Async.background { self.doImport() self.isRunningImport = false Async.main { self.addDetailText("\n\nDone with import", addNewLine: true) self.cancelCloseButton.title = "Close" } } NSApplication.shared.runModal(for: window!) } @IBAction func onCancel(_ sender: AnyObject) { if isRunningImport { Logger.warn("Import canceled") } close() NSApplication.shared.stopModal(withCode: NSApplication.ModalResponse(rawValue: isRunningImport ? 0 : 1)) } func doImport() { do { let importer = ImportLightroomExport(originalMediaData: originalMediaData, exportedMediaData: exportedMediaData) try importer.run(self, importFolder: importFolder, destinationFolder: destinationFolder) } catch let error { Logger.error("Failed importing: \(error)") } } func setCurrentStep(_ stepName: String) { Logger.info("Import step: \(stepName)") Async.main { self.stepLabel.stringValue = "\(stepName)" } addDetailText("\(stepName):", addNewLine: self.detailTextView.string.count > 0) } func setStepDetail(_ detail: String) { Logger.info(" --> \(detail)") addDetailText("\(detail)", addNewLine: true) } func addDetailText(_ text: String, addNewLine: Bool) { Async.main { if addNewLine { self.detailTextView.string += "\n\(text)" } else { self.detailTextView.string += "\(text)" } self.detailTextView.scrollToEndOfDocument(self) } } }
mit
d41e5626ae45acc6e7c1c9e89b14f7e2
28.161616
129
0.627641
4.935043
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/AssociationParallelRowScopesTests.swift
1
153695
import XCTest import GRDB // A -> B <- C // A -> D private struct A: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "a" static let defaultB = belongsTo(B.self) static let defaultD = belongsTo(D.self) static let customB = belongsTo(B.self, key: "customB") static let customD = belongsTo(D.self, key: "customD") var id: Int64 var bid: Int64? var did: Int64? var name: String } private struct B: Codable, FetchableRecord, PersistableRecord { static let defaultA = hasOne(A.self) static let defaultC = hasOne(C.self) static let customA = hasOne(A.self, key: "customA") static let customC = hasOne(C.self, key: "customC") static let databaseTableName = "b" var id: Int64 var name: String } private struct C: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "c" var id: Int64 var bid: Int64? var name: String } private struct D: Codable, FetchableRecord, PersistableRecord { static let defaultA = hasOne(A.self) static let customA = hasOne(A.self, key: "customA") static let databaseTableName = "d" var id: Int64 var name: String } /// Test row scopes class AssociationParallelRowScopesTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "b") { t in t.column("id", .integer).primaryKey() t.column("name", .text) } try db.create(table: "d") { t in t.column("id", .integer).primaryKey() t.column("name", .text) } try db.create(table: "a") { t in t.column("id", .integer).primaryKey() t.column("bid", .integer).references("b") t.column("did", .integer).references("d") t.column("name", .text) } try db.create(table: "c") { t in t.column("id", .integer).primaryKey() t.column("bid", .integer).references("b") t.column("name", .text) } try B(id: 1, name: "b1").insert(db) try B(id: 2, name: "b2").insert(db) try B(id: 3, name: "b3").insert(db) try D(id: 1, name: "d1").insert(db) try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) try C(id: 1, bid: 1, name: "c1").insert(db) } } func testDefaultScopeParallelTwoIncludingIncluding() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) } do { let request = A.including(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) } do { let request = A.including(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) } do { let request = A.including(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["b", "d"]) XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["b", "d"]) XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.including(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) } do { let request = B.including(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.including(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["a", "c"]) XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) } } func testDefaultScopeParallelTwoIncludingIncludingSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.defaultB).including(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.defaultB).including(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.defaultB).including(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.defaultB).including(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.defaultA).including(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(required: B.defaultA).including(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.defaultA).including(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.defaultA).including(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testDefaultScopeParallelTwoIncludingJoining() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) } do { let request = A.including(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) } do { let request = B.including(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) } do { let request = B.including(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testDefaultScopeParallelTwoIncludingJoiningSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.defaultB).joining(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.defaultB).joining(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.defaultB).joining(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.defaultB).joining(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.defaultA).joining(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(required: B.defaultA).joining(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.defaultA).joining(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.defaultA).joining(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testDefaultScopeParallelTwoJoiningIncluding() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) } do { let request = A.joining(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) } do { let request = A.joining(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) } do { let request = A.joining(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["d"]) XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["d"]) XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) } do { let request = B.joining(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.joining(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) } do { let request = B.joining(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.joining(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["c"]) XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) } } func testDefaultScopeParallelTwoJoiningIncludingSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.defaultB).including(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(required: A.defaultB).including(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(optional: A.defaultB).including(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(optional: A.defaultB).including(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) } do { let request = B.joining(required: B.defaultA).including(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(required: B.defaultA).including(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(optional: B.defaultA).including(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(optional: B.defaultA).including(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testDefaultScopeParallelTwoJoiningJoining() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = A.joining(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) } do { let request = A.joining(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertTrue(rows[5].scopes.names.isEmpty) } do { let request = B.joining(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = B.joining(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = B.joining(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) } } func testDefaultScopeParallelTwoJoiningJoiningSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.defaultB).joining(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(required: A.defaultB).joining(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.defaultB).joining(required: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.defaultB).joining(optional: A.defaultB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertTrue(rows[5].scopes.names.isEmpty) } do { let request = B.joining(required: B.defaultA).joining(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(required: B.defaultA).joining(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.defaultA).joining(required: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.defaultA).joining(optional: B.defaultA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) } } func testCustomScopeParallelTwoIncludingIncluding() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) } do { let request = A.including(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) } do { let request = A.including(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) } do { let request = A.including(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customB", "customD"]) XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.including(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) } do { let request = B.including(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.including(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customA", "customC"]) XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) } } func testCustomScopeParallelTwoIncludingIncludingSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.customB).including(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.customB).including(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.customB).including(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.customB).including(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.customA).including(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(required: B.customA).including(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.customA).including(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.customA).including(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testCustomScopeParallelTwoIncludingJoining() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) } do { let request = A.including(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) } do { let request = B.including(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) } do { let request = B.including(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testCustomScopeParallelTwoIncludingJoiningSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.including(required: A.customB).joining(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(required: A.customB).joining(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.customB).joining(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.including(optional: A.customB).joining(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) } do { let request = B.including(required: B.customA).joining(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(required: B.customA).joining(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.customA).joining(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.including(optional: B.customA).joining(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testCustomScopeParallelTwoJoiningIncluding() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) } do { let request = A.joining(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) } do { let request = A.joining(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) } do { let request = A.joining(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customD"]) XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customD"]) XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) } do { let request = B.joining(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.joining(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) } do { let request = B.joining(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) } do { let request = B.joining(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customC"]) XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) } } func testCustomScopeParallelTwoJoiningIncludingSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.customB).including(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(required: A.customB).including(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(optional: A.customB).including(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) } do { let request = A.joining(optional: A.customB).including(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) } do { let request = B.joining(required: B.customA).including(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(required: B.customA).including(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(optional: B.customA).including(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) } do { let request = B.joining(optional: B.customA).including(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) } } func testCustomScopeParallelTwoJoiningJoining() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = A.joining(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) } do { let request = A.joining(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertTrue(rows[5].scopes.names.isEmpty) } do { let request = B.joining(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = B.joining(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) } do { let request = B.joining(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) } } func testCustomScopeParallelTwoJoiningJoiningSameAssociation() throws { let dbQueue = try makeDatabaseQueue() do { let request = A.joining(required: A.customB).joining(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(required: A.customB).joining(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.customB).joining(required: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = A.joining(optional: A.customB).joining(optional: A.customB).order(sql: "a.id, b.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 6) XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) XCTAssertTrue(rows[5].scopes.names.isEmpty) } do { let request = B.joining(required: B.customA).joining(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(required: B.customA).joining(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.customA).joining(required: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 4) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) } do { let request = B.joining(optional: B.customA).joining(optional: B.customA).order(sql: "b.id, a.id") let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) } XCTAssertEqual(rows.count, 5) XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[0].scopes.names.isEmpty) XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) XCTAssertTrue(rows[1].scopes.names.isEmpty) XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[2].scopes.names.isEmpty) XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) XCTAssertTrue(rows[3].scopes.names.isEmpty) XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) XCTAssertTrue(rows[4].scopes.names.isEmpty) } } }
mit
f93cac212956445c89b0844a49386a52
52.73951
122
0.520186
3.560309
false
false
false
false
apple/swift-tools-support-core
Sources/TSCBasic/Tuple.swift
4
690
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Returns true if these arrays of tuple contains the same elements. public func ==<A: Equatable, B: Equatable>( lhs: [(A, B)], rhs: [(A, B)] ) -> Bool { guard lhs.count == rhs.count else { return false } for (idx, lElement) in lhs.enumerated() { guard lElement == rhs[idx] else { return false } } return true }
apache-2.0
f6e62867f05d0a51a555bad40ec71cd5
30.363636
69
0.669565
3.965517
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Nodes/Effects/Distortion/Bit Crusher/AKBitCrusher.swift
1
4609
// // AKBitCrusher.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This will digitally degrade a signal. /// /// - Parameters: /// - input: Input node to process /// - bitDepth: The bit depth of signal output. Typically in range (1-24). Non-integer values are OK. /// - sampleRate: The sample rate of signal output. /// public class AKBitCrusher: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKBitCrusherAudioUnit? internal var token: AUParameterObserverToken? private var bitDepthParameter: AUParameter? private var sampleRateParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The bit depth of signal output. Typically in range (1-24). Non-integer values are OK. public var bitDepth: Double = 8 { willSet { if bitDepth != newValue { if internalAU!.isSetUp() { bitDepthParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.bitDepth = Float(newValue) } } } } /// The sample rate of signal output. public var sampleRate: Double = 10000 { willSet { if sampleRate != newValue { if internalAU!.isSetUp() { sampleRateParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.sampleRate = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this bitcrusher node /// /// - Parameters: /// - input: Input node to process /// - bitDepth: The bit depth of signal output. Typically in range (1-24). Non-integer values are OK. /// - sampleRate: The sample rate of signal output. /// public init( _ input: AKNode, bitDepth: Double = 8, sampleRate: Double = 10000) { self.bitDepth = bitDepth self.sampleRate = sampleRate var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = fourCC("btcr") description.componentManufacturer = fourCC("AuKt") description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKBitCrusherAudioUnit.self, asComponentDescription: description, name: "Local AKBitCrusher", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKBitCrusherAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } bitDepthParameter = tree.valueForKey("bitDepth") as? AUParameter sampleRateParameter = tree.valueForKey("sampleRate") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.bitDepthParameter!.address { self.bitDepth = Double(value) } else if address == self.sampleRateParameter!.address { self.sampleRate = Double(value) } } } internalAU?.bitDepth = Float(bitDepth) internalAU?.sampleRate = Float(sampleRate) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
f050275c45932244e99e3daffc7467c0
31.230769
107
0.600781
5.225624
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/Host.swift
1
12619
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // @_implementationOnly import CoreFoundation #if os(Android) // Android Glibc differs a little with respect to the Linux Glibc. // IFF_LOOPBACK is part of the enumeration net_device_flags, which needs to // convert to UInt32. private extension UInt32 { init(_ value: net_device_flags) { self.init(value.rawValue) } } // getnameinfo uses size_t for its 4th and 6th arguments. private func getnameinfo(_ addr: UnsafePointer<sockaddr>?, _ addrlen: socklen_t, _ host: UnsafeMutablePointer<Int8>?, _ hostlen: socklen_t, _ serv: UnsafeMutablePointer<Int8>?, _ servlen: socklen_t, _ flags: Int32) -> Int32 { return Glibc.getnameinfo(addr, addrlen, host, Int(hostlen), serv, Int(servlen), flags) } // getifaddrs and freeifaddrs are not available in Android 6.0 or earlier, so call these functions dynamically. // This only happens during the initial lookup of the addresses and then the results are cached and _resolved is marked true. // If this API changes so these functions are called more frequently, it might be beneficial to cache the function pointers. private typealias GetIfAddrsFunc = @convention(c) (UnsafeMutablePointer<UnsafeMutablePointer<ifaddrs>?>) -> Int32 private func getifaddrs(_ ifap: UnsafeMutablePointer<UnsafeMutablePointer<ifaddrs>?>) -> Int32 { var result: Int32 = -1 if let handle = dlopen("libc.so", RTLD_NOLOAD) { if let entry = dlsym(handle, "getifaddrs") { result = unsafeBitCast(entry, to: GetIfAddrsFunc.self)(ifap) } dlclose(handle) } return result } private typealias FreeIfAddrsFunc = @convention(c) (UnsafeMutablePointer<ifaddrs>?) -> Void private func freeifaddrs(_ ifa: UnsafeMutablePointer<ifaddrs>?) { if let handle = dlopen("libc.so", RTLD_NOLOAD) { if let entry = dlsym(handle, "freeifaddrs") { unsafeBitCast(entry, to: FreeIfAddrsFunc.self)(ifa) } dlclose(handle) } } #endif open class Host: NSObject { enum ResolveType { case name case address case current } internal var _info: String? internal var _type: ResolveType internal var _resolved = false internal var _names = [String]() internal var _addresses = [String]() static internal let _current = Host(currentHostName(), .current) internal init(_ info: String?, _ type: ResolveType) { _info = info _type = type } static internal func currentHostName() -> String { #if os(Windows) var dwLength: DWORD = 0 GetComputerNameExA(ComputerNameDnsHostname, nil, &dwLength) guard dwLength > 0 else { return "localhost" } guard let hostname: UnsafeMutablePointer<Int8> = UnsafeMutableBufferPointer<Int8> .allocate(capacity: Int(dwLength + 1)) .baseAddress else { return "localhost" } defer { hostname.deallocate() } guard GetComputerNameExA(ComputerNameDnsHostname, hostname, &dwLength) else { return "localhost" } return String(cString: hostname) #else let hname = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST)) defer { hname.deallocate() } let r = gethostname(hname, Int(NI_MAXHOST)) if r < 0 || hname[0] == 0 { return "localhost" } return String(cString: hname) #endif } open class func current() -> Host { return _current } public convenience init(name: String?) { self.init(name, .name) } public convenience init(address: String) { self.init(address, .address) } open func isEqual(to aHost: Host) -> Bool { if self === aHost { return true } return addresses.firstIndex { aHost.addresses.contains($0) } != nil } internal func _resolveCurrent(withInfo info: String) { #if os(Windows) var szAddress: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(NI_MAXHOST)) var ulSize: ULONG = 0 var ulResult: ULONG = GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, nil, &ulSize) var arAdapters: UnsafeMutableRawPointer = UnsafeMutableRawPointer.allocate(byteCount: Int(ulSize), alignment: 1) defer { arAdapters.deallocate() } ulResult = GetAdaptersAddresses(ULONG(AF_UNSPEC), 0, nil, arAdapters.assumingMemoryBound(to: IP_ADAPTER_ADDRESSES.self), &ulSize) guard ulResult == ERROR_SUCCESS else { return } var pAdapter: UnsafeMutablePointer<IP_ADAPTER_ADDRESSES>? = arAdapters.assumingMemoryBound(to: IP_ADAPTER_ADDRESSES.self) while pAdapter != nil { // print("Adapter: \(String(cString: pAdapter!.pointee.AdapterName))") var arAddresses: UnsafeMutablePointer<IP_ADAPTER_UNICAST_ADDRESS> = pAdapter!.pointee.FirstUnicastAddress var pAddress: UnsafeMutablePointer<IP_ADAPTER_UNICAST_ADDRESS>? = arAddresses while pAddress != nil { switch pAddress!.pointee.Address.lpSockaddr.pointee.sa_family { case ADDRESS_FAMILY(AF_INET), ADDRESS_FAMILY(AF_INET6): if GetNameInfoW(pAddress!.pointee.Address.lpSockaddr, pAddress!.pointee.Address.iSockaddrLength, &szAddress, DWORD(szAddress.capacity), nil, 0, NI_NUMERICHOST) == 0 { // print("\tIP Address: \(String(decodingCString: &szAddress, as: UTF16.self))") _addresses.append(String(decodingCString: &szAddress, as: UTF16.self)) } default: break } pAddress = pAddress!.pointee.Next } pAdapter = pAdapter!.pointee.Next } _names = [info] _resolved = true #else var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil if getifaddrs(&ifaddr) != 0 { return } var ifa: UnsafeMutablePointer<ifaddrs>? = ifaddr let address = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST)) defer { freeifaddrs(ifaddr) address.deallocate() } while let ifaValue = ifa?.pointee { if let ifa_addr = ifaValue.ifa_addr, ifaValue.ifa_flags & UInt32(IFF_LOOPBACK) == 0 { let family = ifa_addr.pointee.sa_family if family == sa_family_t(AF_INET) || family == sa_family_t(AF_INET6) { let sa_len: socklen_t = socklen_t((family == sa_family_t(AF_INET6)) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size) #if os(OpenBSD) let hostlen = size_t(NI_MAXHOST) #else let hostlen = socklen_t(NI_MAXHOST) #endif if getnameinfo(ifa_addr, sa_len, address, hostlen, nil, 0, NI_NUMERICHOST) == 0 { _addresses.append(String(cString: address)) } } } ifa = ifaValue.ifa_next } _names = [info] _resolved = true #endif } internal func _resolve() { guard _resolved == false else { return } #if os(Windows) if let info = _info { if _type == .current { return _resolveCurrent(withInfo: info) } var hints: ADDRINFOW = ADDRINFOW() memset(&hints, 0, MemoryLayout<ADDRINFOW>.size) switch (_type) { case .name: hints.ai_flags = AI_PASSIVE | AI_CANONNAME case .address: hints.ai_flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST case .current: break } hints.ai_family = AF_UNSPEC hints.ai_socktype = SOCK_STREAM hints.ai_protocol = IPPROTO_TCP.rawValue var aiResult: UnsafeMutablePointer<ADDRINFOW>? var bSucceeded: Bool = false info.withCString(encodedAs: UTF16.self) { if GetAddrInfoW($0, nil, &hints, &aiResult) == 0 { bSucceeded = true } } guard bSucceeded == true else { return } defer { FreeAddrInfoW(aiResult) } var wszHostName: [WCHAR] = Array<WCHAR>(repeating: 0, count: Int(NI_MAXHOST)) while aiResult != nil { let aiInfo: ADDRINFOW = aiResult!.pointee var sa_len: socklen_t = 0 switch aiInfo.ai_family { case AF_INET: sa_len = socklen_t(MemoryLayout<sockaddr_in>.size) case AF_INET6: sa_len = socklen_t(MemoryLayout<sockaddr_in6>.size) default: aiResult = aiInfo.ai_next continue } let lookup = { (content: inout [String], flags: Int32) in if GetNameInfoW(aiInfo.ai_addr, sa_len, &wszHostName, DWORD(NI_MAXHOST), nil, 0, flags) == 0 { content.append(String(decodingCString: &wszHostName, as: UTF16.self)) } } lookup(&_addresses, NI_NUMERICHOST) lookup(&_names, NI_NAMEREQD) lookup(&_names, NI_NOFQDN | NI_NAMEREQD) aiResult = aiInfo.ai_next } _resolved = true } #else if let info = _info { var flags: Int32 = 0 switch (_type) { case .name: flags = AI_PASSIVE | AI_CANONNAME case .address: flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST case .current: _resolveCurrent(withInfo: info) return } var hints = addrinfo() hints.ai_family = PF_UNSPEC #if os(macOS) || os(iOS) || os(Android) || os(OpenBSD) hints.ai_socktype = SOCK_STREAM #else hints.ai_socktype = Int32(SOCK_STREAM.rawValue) #endif hints.ai_flags = flags var res0: UnsafeMutablePointer<addrinfo>? = nil let r = getaddrinfo(info, nil, &hints, &res0) defer { freeaddrinfo(res0) } if r != 0 { return } var res: UnsafeMutablePointer<addrinfo>? = res0 let host = UnsafeMutablePointer<Int8>.allocate(capacity: Int(NI_MAXHOST)) defer { host.deallocate() } while res != nil { let info = res!.pointee let family = info.ai_family if family != AF_INET && family != AF_INET6 { res = info.ai_next continue } let sa_len: socklen_t = socklen_t((family == AF_INET6) ? MemoryLayout<sockaddr_in6>.size : MemoryLayout<sockaddr_in>.size) let lookupInfo = { (content: inout [String], flags: Int32) in #if os(OpenBSD) let hostlen = size_t(NI_MAXHOST) #else let hostlen = socklen_t(NI_MAXHOST) #endif if getnameinfo(info.ai_addr, sa_len, host, hostlen, nil, 0, flags) == 0 { content.append(String(cString: host)) } } lookupInfo(&_addresses, NI_NUMERICHOST) lookupInfo(&_names, NI_NAMEREQD) lookupInfo(&_names, NI_NOFQDN|NI_NAMEREQD) res = info.ai_next } _resolved = true } #endif } open var name: String? { return names.first } open var names: [String] { _resolve() return _names } open var address: String? { return addresses.first } open var addresses: [String] { _resolve() return _addresses } open var localizedName: String? { return nil } }
apache-2.0
663883d676573c5cc3e1417cdbf4e1d2
34.951567
229
0.554244
4.378557
false
false
false
false
modocache/swift
test/SILGen/objc_bridging_any.swift
3
30620
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_generics protocol P {} protocol CP: class {} struct KnownUnbridged {} // CHECK-LABEL: sil hidden @_TF17objc_bridging_any11passingToId func passingToId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optionalA: String?, optionalB: NSString?, optionalC: Any?) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: [[STRING:%.*]] : $String // CHECK: [[NSSTRING:%.*]] : $NSString // CHECK: [[OBJECT:%.*]] : $AnyObject // CHECK: [[CLASS_GENERIC:%.*]] : $T // CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: [[GENERIC:%.*]] : $*U // CHECK: [[EXISTENTIAL:%.*]] : $*P // CHECK: [[ERROR:%.*]] : $Error // CHECK: [[ANY:%.*]] : $*Any // CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged // CHECK: [[OPT_STRING:%.*]] : $Optional<String> // CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveC // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[STRING]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(string) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING]] : $NSString : $NSString, $AnyObject // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(nsString) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC]] : $T : $T, $AnyObject // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(classGeneric) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: apply [[METHOD]]([[OBJECT]], [[SELF]]) receiver.takesId(object) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(classExistential) // These cases perform a universal bridging conversion. // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U // CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK-NEXT: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesId(generic) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P // CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesId(existential) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: strong_retain [[ERROR]] : $Error // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_TFs27_bridgeAnythingToObjectiveCurFxPs9AnyObject_ // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR]], [[SELF]]) // CHECK-NEXT: strong_release [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: strong_release [[ERROR]] : $Error receiver.takesId(error) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesId(any) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(knownUnbridged) // These cases bridge using Optional's _ObjectiveCBridgeable conformance. // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_ // CHECK: [[TMP:%.*]] = alloc_stack $Optional<String> // CHECK: store [[OPT_STRING]] to [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalA) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_ // CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString> // CHECK: store [[OPT_NSSTRING]] to [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalB) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any> // CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_ // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]]) receiver.takesId(optionalC) // TODO: Property and subscript setters } // CHECK-LABEL: sil hidden @_TF17objc_bridging_any19passingToNullableId func passingToNullableId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optString: String?, optNSString: NSString?, optObject: AnyObject?, optClassGeneric: T?, optClassExistential: CP?, optGeneric: U?, optExistential: P?, optAny: Any?, optKnownUnbridged: KnownUnbridged?, optOptA: String??, optOptB: NSString??, optOptC: Any??) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: [[STRING:%.*]] : $String, // CHECK: [[NSSTRING:%.*]] : $NSString // CHECK: [[OBJECT:%.*]] : $AnyObject // CHECK: [[CLASS_GENERIC:%.*]] : $T // CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: [[GENERIC:%.*]] : $*U // CHECK: [[EXISTENTIAL:%.*]] : $*P // CHECK: [[ERROR:%.*]] : $Error // CHECK: [[ANY:%.*]] : $*Any, // CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged, // CHECK: [[OPT_STRING:%.*]] : $Optional<String>, // CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject> // CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T> // CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP> // CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U> // CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P> // CHECK: [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged> // CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>> // CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>> // CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>> // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveC // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[STRING]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(string) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(nsString) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(object) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC]] : $T : $T, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(classGeneric) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(classExistential) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U // CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesNullableId(generic) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P // CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesNullableId(existential) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: strong_retain [[ERROR]] : $Error // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_TFs27_bridgeAnythingToObjectiveCurFxPs9AnyObject_ // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[SELF]]) // CHECK-NEXT: strong_release [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: strong_release [[ERROR]] : $Error receiver.takesNullableId(error) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) // CHECK-NEXT: strong_release [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] receiver.takesNullableId(any) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[SELF]]) receiver.takesNullableId(knownUnbridged) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] // CHECK: select_enum [[OPT_STRING]] // CHECK: cond_br // CHECK: [[STRING_DATA:%.*]] = unchecked_enum_data [[OPT_STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveC // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[STRING_DATA]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]] // CHECK: [[JOIN]]([[PHI:%.*]] : $Optional<AnyObject>): // CHECK: apply [[METHOD]]([[PHI]], [[SELF]]) receiver.takesNullableId(optString) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] receiver.takesNullableId(optNSString) // CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] // CHECK: apply [[METHOD]]([[OPT_OBJECT]], [[SELF]]) receiver.takesNullableId(optObject) receiver.takesNullableId(optClassGeneric) receiver.takesNullableId(optClassExistential) receiver.takesNullableId(optGeneric) receiver.takesNullableId(optExistential) receiver.takesNullableId(optAny) receiver.takesNullableId(optKnownUnbridged) receiver.takesNullableId(optOptA) receiver.takesNullableId(optOptB) receiver.takesNullableId(optOptC) } protocol Anyable { init(any: Any) init(anyMaybe: Any?) var anyProperty: Any { get } var maybeAnyProperty: Any? { get } } // Make sure we generate correct bridging thunks class SwiftIdLover : NSObject, Anyable { func methodReturningAny() -> Any {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover18methodReturningAnyfT_P_ : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any // CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any // CHECK: [[NATIVE_IMP:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover18methodReturningAny // CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], %0) // CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr [[NATIVE_RESULT]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC // CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[OPEN_RESULT]]) // CHECK: return [[OBJC_RESULT]] func methodReturningOptionalAny() -> Any? {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover26methodReturningOptionalAny // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover26methodReturningOptionalAny // CHECK: function_ref @_TFs27_bridgeAnythingToObjectiveC func methodTakingAny(a: Any) {} // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover15methodTakingAnyfT1aP__T_ : $@convention(objc_method) (AnyObject, SwiftIdLover) -> () // CHECK: bb0(%0 : $AnyObject, %1 : $SwiftIdLover): // CHECK-NEXT: strong_retain %0 // CHECK-NEXT: strong_retain %1 // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast %0 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover15methodTakingAnyfT1aP__T_ // CHECK-NEXT: apply [[METHOD]]([[RESULT]], %1) // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return func methodTakingOptionalAny(a: Any?) {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover23methodTakingOptionalAny // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover23methodTakingOptionalAny // CHECK: function_ref [[BRIDGE_TO_ANY_FUNC]] // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover26methodTakingBlockTakingAnyfFP_T_T_ : $@convention(method) (@owned @callee_owned (@in Any) -> (), @guaranteed SwiftIdLover) -> () // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover26methodTakingBlockTakingAnyfFP_T_T_ : $@convention(objc_method) (@convention(block) (AnyObject) -> (), SwiftIdLover) -> () // CHECK: bb0(%0 : $@convention(block) (AnyObject) -> (), %1 : $SwiftIdLover): // CHECK-NEXT: [[BLOCK:%.*]] = copy_block %0 // CHECK-NEXT: strong_retain %1 // CHECK: [[THUNK_FN:%.*]] = function_ref @_TTRXFdCb_dPs9AnyObject___XFo_iP___ // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK]]) // CHECK: [[METHOD:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover26methodTakingBlockTakingAnyfFP_T_T_ // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], %1) // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb_dPs9AnyObject___XFo_iP___ // CHECK: bb0(%0 : $*Any, %1 : $@convention(block) (AnyObject) -> ()): // CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr %0 : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED]]) // CHECK-NEXT: apply %1([[BRIDGED]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: strong_release %1 // CHECK-NEXT: strong_release [[BRIDGED]] // CHECK-NEXT: deinit_existential_addr %0 // CHECK-NEXT: return [[VOID]] func methodTakingBlockTakingAny(_: (Any) -> ()) {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover29methodReturningBlockTakingAnyfT_FP_T_ : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned (@in Any) -> () // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover29methodReturningBlockTakingAnyfT_FP_T_ : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> () // CHECK: bb0(%0 : $SwiftIdLover): // CHECK-NEXT: strong_retain %0 // CHECK: [[METHOD:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover29methodReturningBlockTakingAnyfT_FP_T_ // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]](%0) // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned (@in Any) -> () // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[RESULT:%.*]] to [[BLOCK_STORAGE_ADDR]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_TTRXFo_iP___XFdCb_dPs9AnyObject___ // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned (@in Any) -> (), invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: strong_release [[RESULT]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP___XFdCb_dPs9AnyObject___ : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> () // CHECK: bb0(%0 : $*@block_storage @callee_owned (@in Any) -> (), %1 : $AnyObject): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0 // CHECK-NEXT: [[FUNCTION:%.*]] = load [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: strong_retain [[FUNCTION]] // CHECK-NEXT: strong_retain %1 // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast %1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[VOID]] : $() func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) {} func methodReturningBlockTakingAny() -> ((Any) -> ()) {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover29methodTakingBlockReturningAnyfFT_P_T_ : $@convention(method) (@owned @callee_owned () -> @out Any, @guaranteed SwiftIdLover) -> () { // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover29methodTakingBlockReturningAnyfFT_P_T_ : $@convention(objc_method) (@convention(block) () -> @autoreleased AnyObject, SwiftIdLover) -> () // CHECK: bb0(%0 : $@convention(block) () -> @autoreleased AnyObject, %1 : $SwiftIdLover): // CHECK-NEXT: [[BLOCK:%.*]] = copy_block %0 // CHECK-NEXT: strong_retain %1 // CHECK: [[THUNK_FN:%.*]] = function_ref @_TTRXFdCb__aPs9AnyObject__XFo__iP__ // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK]]) // CHECK: [[METHOD:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover29methodTakingBlockReturningAnyfFT_P_T_ // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], %1) // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb__aPs9AnyObject__XFo__iP__ : $@convention(thin) (@owned @convention(block) () -> @autoreleased AnyObject) -> @out Any // CHECK: bb0(%0 : $*Any, %1 : $@convention(block) () -> @autoreleased AnyObject): // CHECK-NEXT: [[BRIDGED:%.*]] = apply %1() // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // TODO: Should elide the copy // CHECK-NEXT: copy_addr [take] [[RESULT]] to [initialization] %0 // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: strong_release %1 // CHECK-NEXT: return [[EMPTY]] func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) {} func methodTakingBlockReturningAny(_: () -> Any) {} // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any12SwiftIdLover32methodReturningBlockReturningAnyfT_FT_P_ : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned () -> @out Any // CHECK-LABEL: sil hidden [thunk] @_TToFC17objc_bridging_any12SwiftIdLover32methodReturningBlockReturningAnyfT_FT_P_ : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject // CHECK: bb0(%0 : $SwiftIdLover): // CHECK-NEXT: strong_retain %0 // CHECK: [[METHOD:%.*]] = function_ref @_TFC17objc_bridging_any12SwiftIdLover32methodReturningBlockReturningAnyfT_FT_P_ // CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]](%0) // CHECK-NEXT: strong_release %0 // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> @out Any // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[FUNCTION]] to [[BLOCK_STORAGE_ADDR]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_TTRXFo__iP__XFdCb__aPs9AnyObject__ // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned () -> @out Any, invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: strong_release [[FUNCTION]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__iP__XFdCb__aPs9AnyObject__ : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject // CHECK: bb0(%0 : $*@block_storage @callee_owned () -> @out Any): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0 // CHECK-NEXT: [[FUNCTION:%.*]] = load [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: strong_retain [[FUNCTION]] // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED]]) // CHECK-NEXT: deinit_existential_addr [[RESULT]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[BRIDGED]] func methodTakingBlockReturningOptionalAny(_: () -> Any?) {} func methodReturningBlockReturningAny() -> (() -> Any) {} func methodReturningBlockReturningOptionalAny() -> (() -> Any?) {} // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__iGSqP___XFdCb__aGSqPs9AnyObject___ // CHECK: function_ref @_TFs27_bridgeAnythingToObjectiveC override init() { super.init() } dynamic required convenience init(any: Any) { self.init() } dynamic required convenience init(anyMaybe: Any?) { self.init() } dynamic var anyProperty: Any dynamic var maybeAnyProperty: Any? subscript(_: IndexForAnySubscript) -> Any { get {} set {} } func methodReturningAnyOrError() throws -> Any {} } class IndexForAnySubscript {} func dynamicLookup(x: AnyObject) { _ = x.anyProperty _ = x[IndexForAnySubscript()] } extension GenericClass { // CHECK-LABEL: sil hidden @_TFE17objc_bridging_anyCSo12GenericClass23pseudogenericAnyErasurefT1xx_P_ func pseudogenericAnyErasure(x: T) -> Any { // CHECK: [[ANY_BUF:%.*]] = init_existential_addr %0 : $*Any, $AnyObject // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref %1 : $T : $T, $AnyObject // CHECK: store [[ANYOBJECT]] to [[ANY_BUF]] return x } } // Make sure AnyHashable erasure marks Hashable conformance as used class AnyHashableClass : NSObject { // CHECK-LABEL: sil hidden @_TFC17objc_bridging_any16AnyHashableClass18returnsAnyHashablefT_Vs11AnyHashable // CHECK: [[FN:%.*]] = function_ref @_swift_convertToAnyHashable // CHECK: apply [[FN]]<GenericOption>({{.*}}) func returnsAnyHashable() -> AnyHashable { return GenericOption.multithreaded } } // CHECK-LABEL: sil_witness_table shared [fragile] GenericOption: Hashable module objc_generics { // CHECK-NEXT: base_protocol _Hashable: GenericOption: _Hashable module objc_generics // CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics // CHECK-NEXT: method #Hashable.hashValue!getter.1: @_TTWVSC13GenericOptions8Hashable13objc_genericsFS0_g9hashValueSi // CHECK-NEXT: }
apache-2.0
78391c6d71a3241559dc0906b93d27b4
53.387211
228
0.61241
3.671023
false
false
false
false
royhsu/chocolate-touch
Source/CHCache.swift
1
4924
// // CHCache.swift // Chocolate // // Created by 許郁棋 on 2016/7/9. // Copyright © 2016年 Tiny World. All rights reserved. // import CHFoundation import CoreData import PromiseKit public class CHCache { private struct Constant { static let filename = "Cache" } // MARK: Property public static let `default` = CHCache() public private(set) lazy var stack: CoreDataStack = { /// Reference: http://stackoverflow.com/questions/25088367/how-to-use-core-datas-managedobjectmodel-inside-a-framework let bundle = Bundle(for: type(of: self)) guard let modelURLString = bundle.path(forResource: Constant.filename, ofType: "momd"), let modelURL = URL(string: modelURLString), let model = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Can't find core data model for cache.") } return CoreDataStack(model: model) }() private var defaultStoreURL: URL { return URL.fileURL( filename: Constant.filename, withExtension: "sqlite", in: .document(domainMask: .userDomainMask) ) } public func loadStore(type: CoreDataStack.StoreType? = nil) -> Promise<CoreDataStack> { let storeType = type ?? .local(defaultStoreURL) return stack.loadStore( type: storeType, options: [ NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true ] ) } // MARK: Action /** Insert a new cache in background. If you want to keep the changes, make sure to call save method. - Parameter identifier: A identifier for cache. - Parameter section: The section index for cache. - Parameter row: The row index for cache. - Parameter jsonOject: A valid json object that will be converted into string for storing. - Returns: A promise with inserted managed object id. */ public func insert(identifier: String, section: Int, row: Int, jsonObject: Any) -> Promise<NSManagedObjectID> { return Promise { fulfill, reject in let _ = self.stack.performBackgroundTask { backgroundContext in let cache = CHCacheEntity.insert(into: backgroundContext) do { let jsonObjectString = try String(jsonObject: jsonObject) cache.identifier = identifier cache.section = Int16(section) cache.row = Int16(row) cache.data = jsonObjectString try backgroundContext.save() fulfill(cache.objectID) } catch { reject(error) } } } } /// Save all changes happened on the view context. public func save() -> Promise<NSManagedObjectContext> { return Promise { fulfill, reject in let viewContext = self.stack.viewContext viewContext.perform { do { try viewContext.save() fulfill(viewContext) } catch { reject(error) } } } } /// Delete all caches related to the given identifier. public func deleteCache(with identifier: String) -> Promise<[NSManagedObjectID]> { return Promise { fulfill, reject in let _ = self.stack.performBackgroundTask { backgroundContext in let fetchRequest = CHCacheEntity.fetchRequest fetchRequest.predicate = NSPredicate(format: "identifier==%@", identifier) fetchRequest.sortDescriptors = [] do { let fetchedObjects = try backgroundContext.fetch(fetchRequest) fetchedObjects.forEach { backgroundContext.delete($0) } try backgroundContext.save() let deletedObjectIDs = fetchedObjects.map { $0.objectID } fulfill(deletedObjectIDs) } catch { reject(error) } } } } }
mit
ea5dd6d2c955e85d2c4898972540c6bb
27.74269
126
0.494608
6.205808
false
false
false
false
ccabanero/MidpointSlider
Pod/Classes/MidpointSliderTrackLayer.swift
1
1345
// // MidpointSliderTrackLayer.swift // Pods // // Created by Clint Cabanero on 1/28/16. // // import UIKit import QuartzCore class MidpointSliderTrackLayer: CALayer { weak var midpointSlider: MidpointSlider? // draw the track override func drawInContext(ctx: CGContext) { if let slider = midpointSlider { // Clip the track let cornerRadius = bounds.height * slider.curvaceousness / 2.0 let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) CGContextAddPath(ctx, path.CGPath) // Fill the track CGContextSetFillColorWithColor(ctx, slider.trackBackgroundColor.CGColor) CGContextAddPath(ctx, path.CGPath) CGContextFillPath(ctx) // Fill the highlighted range CGContextSetFillColorWithColor(ctx, slider.trackTintColor.CGColor) let lowerValuePosition = CGFloat(slider.positionForValue((slider.maximumValue + slider.minimumValue) / 2)) let upperValuePosition = CGFloat(slider.positionForValue(slider.currentValue)) let rect = CGRect(x: lowerValuePosition, y: 0.0, width: upperValuePosition - lowerValuePosition, height: bounds.height) CGContextFillRect(ctx, rect) } } }
mit
00c1b49b0c76cf682c511b2e375ee4de
33.487179
131
0.64461
5.094697
false
false
false
false