hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
185d884d726a078037b58a4eab48444d410ea8a3
296
// // Book.swift // CURD+CoreData // // Created by Muhammad Abdullah Al Mamun on 2/7/20. // Copyright © 2020 Muhammad Abdullah Al Mamun. All rights reserved. // import Foundation struct BookModel { var bookName, bookAuthor : String? var bookImage: Data? let bookID: UUID }
17.411765
69
0.672297
d5e000b98c2d2d5763dee49d93477c2b47fc25e3
872
// // UIStoryboard+Loader.swift // MyiOSApp // // Created by Soufiane SALOUF on 20-06-08. // Copyright © 2020 Soufiane SALOUF. All rights reserved. // import UIKit // MARK: - Storyboards enum Storyboard : String { case authentication = "Authentication" case home = "Home" } // MARK: - Loader Methods extension UIStoryboard { /// Load a View Controller from a specific Storyboard /// /// - Parameters: /// - storyboard: Storyboard /// - viewController: View Controller Type to load /// - Returns: View Controller static func load(from storyboard: Storyboard, viewController: UIViewController.Type) -> UIViewController { let uiStoryboard = UIStoryboard(name: storyboard.rawValue, bundle: nil) return uiStoryboard.instantiateViewController(withIdentifier: String(describing: viewController.self)) } }
26.424242
110
0.690367
f5c768dba50b847d9a903659052d174b34e1b278
873
import XCTest @testable import TODOer class TODOerTests: XCTestCase { override func setUpWithError() throws { try super.setUpWithError() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { try super.tearDownWithError() // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
31.178571
111
0.664376
ff0bd4122cc43cb72cb39199dbf60225ccec1884
967
// // NotificationCenterController.swift // Air Pollution // // Created by Artur on 04/04/2017. // Copyright © 2017 Artur. All rights reserved. // import Foundation import CoreLocation class NotificationCenterController { static let shared = NotificationCenterController() private init() {} private static let notificationCenter = NotificationCenter.default private static let authURLSchema = Notification.Name(rawValue: "authURLSchema") class func observeAuthURLSchema(notificationHandler handler: @escaping (Notification) -> Void) { notificationCenter.addObserver(forName: authURLSchema, object: nil, queue: nil, using: handler) } class func stopObserveAuthURLSchema(observer: Any) { notificationCenter.removeObserver(observer, name: authURLSchema, object: nil) } class func authURLSchemaReceived(url: URL){ notificationCenter.post(name:authURLSchema, object: url) } }
29.30303
103
0.724922
f7c2ffa14201057e50571c4de4109bd252f7202c
825
// // TaskReminderSetupRouter.swift // Taskem // // Created by Wilson on 09/03/2018. // Copyright © 2018 Wilson. All rights reserved. // import Foundation import TaskemFoundation import PainlessInjection class ReminderManualStandardRouter: ReminderManualRouter { weak var controller: ReminderManualViewController! init(remindermanualController: ReminderManualViewController) { self.controller = remindermanualController } func dismiss() { controller.dismiss(animated: true, completion: nil) } func alert(title: String, message: String, completion: @escaping (() -> Void)) { let confirmAction = UIAlertAction(title: "OK", style: .default) { _ in completion() } Alert.displayAlertIn(self.controller, actions: [confirmAction], title: title, message: nil) } }
28.448276
99
0.715152
d5531166088d1965e803e3be26f8f97e1625c852
1,349
// // AppDelegate.swift // WSwiftPractice // // Created by Apple on 2020/12/30. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.459459
179
0.746479
fe291214ca0e07d9feaa44e4dada3fa0a6ef47f2
245
import blob; import io; (blob sum) b(blob v) "b" "0.0" [ "set <<sum>> [ b::b_tcl <<v>> ]" ]; file data = input_file("input.data"); blob v = blob_read(data); blob s = b(v); float sum[] = floats_from_blob(s); printf("sum (swift): %f", sum[0]);
18.846154
37
0.583673
d63c40f60945909971a71fa279c24d2d3f4dddec
2,182
// // AppDelegate.swift // GlowingTextField // // Created by farukTheDev on 01/31/2022. // Copyright (c) 2022 farukTheDev. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.425532
285
0.755729
337178e70f501188e3cdffb98a1d3f2a1086885f
763
import XCTest @testable import NopeYep final class NopeYepTests: XCTestCase { func testTrues() { ["yep","1","0 but true","👍","👍🏻","👍🏼","👍🏽","👍🏾","👍🏿"].forEach { subject in XCTAssertTrue(subject) } } func testFalses() { ["nope","","0","nan","👎","👎🏻","👎🏼","👎🏽","👎🏾","👎🏿"].forEach { subject in XCTAssertFalse(subject) } } func testTruesTrim() { [" yep "," 1 "," 0 but true "," 👍 "," 👍🏻 "," 👍🏼 "," 👍🏽 "," 👍🏾 "," 👍🏿 "].forEach { subject in XCTAssertTrue(subject) } } func testFalsesTrim() { [" nope "," "," 0 "," nan "," 👎 "," 👎🏻 "," 👎🏼 "," 👎🏽 "," 👎🏾 "," 👎🏿 "].forEach { subject in XCTAssertFalse(subject) } } }
26.310345
100
0.410223
f5fc0065fc2c9d6f8852993f02b4885a92960910
4,507
// // AddCourseFromWebViewController.swift // Course // // Created by Archie Yu on 2017/1/13. // Copyright © 2017年 Archie Yu. All rights reserved. // import UIKit import CourseModel class AddCourseFromWebViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var userLabel: UITextField! @IBOutlet weak var passLabel: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var fetchingIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() userLabel.delegate = self passLabel.delegate = self } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cancel(_ sender: UIBarButtonItem) { self.presentingViewController?.dismiss(animated: true, completion: nil) } func textFieldDidEndEditing(_ textField: UITextField) { if userLabel.text != "" && passLabel.text != "" { loginButton.alpha = 1 loginButton.isEnabled = true } else { loginButton.alpha = 0.5 loginButton.isEnabled = false } } func GetRequest() { fetchingIndicator.startAnimating() // 创建请求对象 let username = userLabel.text! let password = passLabel.text! let urlStr = "http://115.159.208.82/username=\(username)&password=\(password)" let url = URL(string: urlStr) var request = URLRequest(url: url!) request.httpMethod = "GET" // 发送请求 let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if error != nil { sleep(1) let alertController = UIAlertController(title: "错误", message: "连接至服务器失败", preferredStyle: .alert) let confirmAction = UIAlertAction(title: "确定", style: .default, handler: nil) alertController.addAction(confirmAction) self.present(alertController, animated: true, completion: nil) DispatchQueue.main.async(execute: { self.fetchingIndicator.stopAnimating() }) } else if let d = data { let dataStr = String(data: d, encoding: .utf8) let offset = dataStr?.range(of: "[")?.lowerBound let rawData = dataStr?.substring(from: offset!).data(using: .utf8) let courseJsonArr = try! JSONSerialization.jsonObject( with: rawData!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String: Any]] for courseJson in courseJsonArr { let course = courseJson["course"] as! String let teacher = courseJson["teacher"] as! String let newCourse = Course(course: course, teacher: teacher) var newLessons: [Lesson] = [] let lessonJsonArr = courseJson["lessons"] as! [[String: Any]] for lessonJson in lessonJsonArr { let room = lessonJson["room"] as! String let weekday = lessonJson["weekday"] as! Int let firstClass = lessonJson["first_class"] as! Int let lastClass = lessonJson["last_class"] as! Int let firstWeek = lessonJson["first_week"] as! Int let lastWeek = lessonJson["last_week"] as! Int let alternate = lessonJson["alternate"] as! Int newLessons.append(Lesson(course: course, inRoom: room, fromWeek: firstWeek, toWeek: lastWeek, alternate: alternate, on: weekday, fromClass: firstClass, toClass: lastClass)) } courseFromWebList.append(newCourse) lessonFromWebList.append(newLessons) } DispatchQueue.main.async(execute: { self.fetchingIndicator.stopAnimating() self.performSegue(withIdentifier: "ShowCourseFromWeb", sender: self) }) } } task.resume() } @IBAction func login(_ sender: UIButton) { GetRequest() } }
39.191304
196
0.574218
21327a8e47d1a0fc58900649330bab59295d26c3
375
// // AppDefine.swift // StreetFlow // // Created by Alex on 3/11/20. // Copyright © 2020 ClubA. All rights reserved. // import UIKit let parse_url = "https://parseapi.back4app.com" let parse_applicationId = "a5IHVb3pfBeNm3DX4U0B1kM6IuudbiwwV3dCdBeg" let parse_clientKey = "XOX3BeqLK59CUPyKDmjSZZA17cxxhdx522ZHzmJo" class AppDefine: NSObject { }
20.833333
69
0.714667
bb8906346d1f4def838232bd155d51e5265c9c1c
6,138
// // PriceField.swift // Shlist // // Created by Pavel Lyskov on 10.04.2020. // Copyright © 2020 Pavel Lyskov. All rights reserved. // import RxBiBinding import RxCocoa import RxSwift // import RxSwiftExt import UIKit //@IBDesignable public final class NumberTextField: UITextField { lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.allowsFloats = true formatter.maximumFractionDigits = 2 formatter.minimumFractionDigits = 2 formatter.decimalSeparator = "." return formatter }() public private(set) var disposedBag = DisposeBag() public struct Settings { let borderColor: UIColor let borderColorHighlighted: UIColor let cornerRadius: CGFloat let minValue: Double let maxValue: Double static let defaultSettings = Settings(borderColor: 0x767680.color.withAlphaComponent(0.24), borderColorHighlighted: 0x767680.color, cornerRadius: 12.0, minValue: 0, maxValue: Double.greatestFiniteMagnitude) } var settings = Settings.defaultSettings { didSet { layer.borderColor = settings.borderColor.cgColor layer.borderWidth = 1 layer.cornerRadius = settings.cornerRadius layer.cornerCurve = .continuous minValue = settings.minValue maxValue = settings.maxValue } } // @IBInspectable public var minValue: Double = 0 { didSet { stepper.minimumValue = minValue doubleRelay.accept(minValue) } } // @IBInspectable public var maxValue = Double.greatestFiniteMagnitude { didSet { stepper.maximumValue = maxValue } } private lazy var textRelay: BehaviorRelay<String?> = .init(value: "\(self.minValue)") public lazy var doubleRelay: BehaviorRelay<Double> = .init(value: self.minValue) public var doubleDriver: Driver<Double> { return doubleRelay.asDriver() } public func hideStepper(hide: Bool) { stepper.isHidden = hide } public var numberValue: Double { get { return doubleRelay.value } set { doubleRelay.accept(newValue) } } private lazy var stepper = UIStepper() var stepperWidth: CGFloat { if stepper.isHidden { return 0 } else { return NumberTextField.stepperBounds.width } } private var textInsets: UIEdgeInsets { let rightInset: CGFloat = 8 + stepperWidth + 8 return .init(top: 2, left: 12, bottom: 2, right: rightInset) } static let stepperBounds = CGRect(x: 0, y: 0, width: 94, height: 32) override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup(with: nil) } // public func setup(with settings: Settings?) { rightView = stepper rightViewMode = .always if let newSettings = settings { self.settings = newSettings } else { self.settings = Settings.defaultSettings } // keyboardType = .numberPad } // public override func awakeFromNib() { super.awakeFromNib() disposedBag = DisposeBag() setup(with: nil) (rx.text <-> textRelay).disposed(by: disposedBag) (stepper.rx.valueDouble <-> doubleRelay).disposed(by: disposedBag) (textRelay <~> doubleRelay).disposed(by: disposedBag) } // @available(*, unavailable) required init?(coder: NSCoder) { super.init(coder: coder) } //// override public func placeholderRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: textInsets) } override public func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: textInsets) } override public func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: textInsets) } override public func rightViewRect(forBounds bounds: CGRect) -> CGRect { return NumberTextField.getStepperFrame(for: bounds) } static func getStepperFrame(for textFieldBounds: CGRect) -> CGRect { let stepperX: CGFloat = textFieldBounds.width - 6 - stepperBounds.width let stepperY: CGFloat = (textFieldBounds.height - stepperBounds.height) / 2 return CGRect(x: stepperX, y: stepperY, width: stepperBounds.width, height: stepperBounds.height) } // static func newWithBounds(_ width: CGFloat, settings: Settings = Settings.defaultSettings) -> NumberTextField { // let bounds = CGRect(x: 0, y: 0, width: width, height: 40) // // let textField = NumberTextField(frame: bounds) // // textField.setup(with: settings) // // textField.settings = settings // // return textField // } } public extension Reactive where Base: NumberTextField { var currentValue: ControlProperty<Double> { return value } var value: ControlProperty<Double> { return base.rx.controlProperty(editingEvents: .valueChanged, getter: { textField in textField.numberValue }, setter: { textField, value in textField.numberValue = value }) } } public extension Reactive where Base: UIStepper { var currentValueInt: ControlProperty<Int> { return valueInt } var valueInt: ControlProperty<Int> { return base.rx.controlProperty(editingEvents: .valueChanged, getter: { stepper in stepper.value.asInt }, setter: { stepper, value in stepper.value = value.asDouble }) } var currentValueDouble: ControlProperty<Double> { return valueDouble } var valueDouble: ControlProperty<Double> { return base.rx.controlProperty(editingEvents: .valueChanged, getter: { stepper in stepper.value }, setter: { stepper, value in stepper.value = value }) } }
28.285714
214
0.623167
efa1f93cdad66db337429e39a0a7529a287c34c6
1,385
import VueFlux public struct Binder<Value> { private let addDisposable: (Disposable) -> Void private let binding: (Value) -> Void /// Create the Binder with target object and binding function. /// /// - Parameters: /// - target: Target object. /// - binding: A function to bind values. public init<Target: AnyObject>(target: Target, binding: @escaping (Target, Value) -> Void) { self.addDisposable = { [weak target] disposable in guard let target = target else { return disposable.dispose() } DisposableScope.associated(with: target).add(disposable: disposable) } self.binding = { [weak target] value in guard let target = target else { return } binding(target, value) } } /// Binds the values, updating the target's value to the latest value of signal until target deinitialized. /// /// - Parameters: /// - signal: A signal that updating the target's value to its latest value. /// - executor: A executor to forward events to binding on. /// /// - Returns: A disposable to unbind from signal. public func bind(signal: Signal<Value>, on executor: Executor) -> Disposable { let disposable = signal.observe(on: executor).observe(binding) addDisposable(disposable) return disposable } }
37.432432
111
0.627437
72dce4b54d1122042a1f942c0de6009a48a12c1c
1,101
// // Cache.swift // Chat // // Created by Mahyar Zhiani on 10/1/1397 AP. // Copyright © 1397 Mahyar Zhiani. All rights reserved. // import Foundation import CoreData import FanapPodAsyncSDK public class Cache { var coreDataStack: CoreDataStack = CoreDataStack() public let context: NSManagedObjectContext public init() { context = coreDataStack.persistentContainer.viewContext // print("context of the cache created") } func saveContext(subject: String) { do { try context.save() log.verbose("\(subject), has Saved Successfully on CoreData Cache", context: "Cache on ChatSDK") } catch { log.error("\(subject), Error to save data on CoreData Cache", context: "Cache on ChatSDK") fatalError("\(subject), Error to save data on CoreData Cache") } } func deleteAndSave(object: NSManagedObject, withMessage message: String) { print("object deleted: \(message)") context.delete(object) saveContext(subject: message) } }
24.466667
108
0.627611
67ab8978cd2f872b45206b989ba7bd26c9853b7f
6,380
// // AndesCard.swift // AndesUI // // Created by Martin Victory on 13/07/2020. // import UIKit @objc public class AndesCard: UIView { internal var contentView: AndesCardView! // MARK: - User properties /// Sets the internal card view of the AndesCard public var cardView: UIView = UIView() { didSet { self.updateContentView() } } /// Sets the title of the AndesCard @IBInspectable public var title: String? { didSet { self.updateContentView() } } /// Sets the padding of the AndesCard @objc public var padding: AndesCardPadding = .none { didSet { self.updateContentView() } } /// Sets the hierarchy of the AndesCard @objc public var hierarchy: AndesCardHierarchy = .primary { didSet { self.reDrawContentViewIfNeededThenUpdate() } } /// Sets the style of the AndesCard @objc public var style: AndesCardStyle = .elevated { didSet { self.updateContentView() } } /// Sets the type of AndesCard @objc public var type: AndesCardType = .none { didSet { self.updateContentView() } } internal var linkText: String? @objc public var actionLinkTitle: String? { self.linkText } // closure triggered when user presses the link private var onLinkActionPressed: ((_ card: AndesCard) -> Void)? // closure triggered when user presses the full card private var onCardActionPressed: ((_ card: AndesCard) -> Void)? // MARK: - Initialization public required init?(coder: NSCoder) { super.init(coder: coder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } @objc public init(cardView: UIView, title: String? = nil, padding: AndesCardPadding = .none, hierarchy: AndesCardHierarchy = .primary, style: AndesCardStyle = .elevated, type: AndesCardType = .none) { super.init(frame: .zero) self.cardView = cardView self.title = title self.padding = padding self.hierarchy = hierarchy self.style = style self.type = type setup() } // MARK: - Content View Setup private func setup() { translatesAutoresizingMaskIntoConstraints = false self.backgroundColor = .clear drawContentView(with: provideView()) } /// Should return a view depending on which card variant is selected private func provideView() -> AndesCardView { let config = AndesCardViewConfigFactory.provideConfig(for: self) if let linkText = linkText, !linkText.isEmpty && self.onLinkActionPressed != nil && self.hierarchy == .primary { return AndesCardWithLinkView(withConfig: config) } return AndesCardDefaultView(withConfig: config) } private func drawContentView(with newView: AndesCardView) { self.contentView = newView contentView.delegate = self addSubview(contentView) contentView.pinToSuperview() } // MARK: - Conent View Update /// Check if view needs to be redrawn, and then update it. This method should be called on all modifiers that may need to change which internal view should be rendered private func reDrawContentViewIfNeededThenUpdate() { let newView = provideView() if Swift.type(of: newView) !== Swift.type(of: contentView) { contentView.removeFromSuperview() drawContentView(with: newView) } updateContentView() } private func updateContentView() { let config = AndesCardViewConfigFactory.provideConfig(for: self) contentView.update(withConfig: config) } // MARK: - Actions /// Link action, when defined a link button will appear /// - Parameters: /// - title: Link text /// - handler: handler to trigger on link tap @objc public func setLinkAction(_ title: String, handler: @escaping ((_ card: AndesCard) -> Void)) { self.linkText = title self.onLinkActionPressed = handler reDrawContentViewIfNeededThenUpdate() } /// Remove link action if present @objc public func removeLinkAction() { self.linkText = nil self.onLinkActionPressed = nil reDrawContentViewIfNeededThenUpdate() } /// Card action, transforms the card into a button /// - Parameters: /// - handler: handler to trigger on link tap @objc public func setCardAction(handler: @escaping ((_ card: AndesCard) -> Void)) { self.onCardActionPressed = handler } /// Remove card action if present @objc public func removeCardAction() { self.onCardActionPressed = nil } } // MARK: - AndesCardViewDelegate extension AndesCard: AndesCardViewDelegate { internal func onLinkTouchUp() { self.onLinkActionPressed?(self) } internal func onCardTouchUp() { self.onCardActionPressed?(self) } } // MARK: - IB Interface public extension AndesCard { @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'padding' instead.") @IBInspectable var ibPadding: String { set(val) { self.padding = AndesCardPadding.checkValidEnum(property: "IB padding", key: val) } get { return self.type.toString() } } @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'style' instead.") @IBInspectable var ibStyle: String { set(val) { self.style = AndesCardStyle.checkValidEnum(property: "IB style", key: val) } get { return self.type.toString() } } @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'type' instead.") @IBInspectable var ibType: String { set(val) { self.type = AndesCardType.checkValidEnum(property: "IB type", key: val) } get { return self.type.toString() } } @available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'hierarchy' instead.") @IBInspectable var ibHierarchy: String { set(val) { self.hierarchy = AndesCardHierarchy.checkValidEnum(property: "IB hierarchy", key: val) } get { return self.type.toString() } } }
30.970874
204
0.639655
bf4493d09a9641efd5db386f31d1a248a05946a7
594
// // Copyright © 2020 NHSX. All rights reserved. // import Combine import Foundation public protocol NetworkingDelegate { func response(for request: URLRequest) -> AnyPublisher<(response: HTTPURLResponse, data: Data), URLError> } extension URLSession: NetworkingDelegate { public func response(for request: URLRequest) -> AnyPublisher<(response: HTTPURLResponse, data: Data), URLError> { dataTaskPublisher(for: request) .map { data, response in (response as! HTTPURLResponse, data) }.eraseToAnyPublisher() } }
24.75
118
0.666667
29ff9da4fab972d1ff379528d0e476c17c5567ed
740
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SoundManager", platforms: [ .iOS(.v12), .watchOS(.v2), .macOS(.v10_10), .tvOS(.v12) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "SoundManager", targets: ["SoundManager"]), ], targets: [ .target( name: "SoundManager", dependencies: []), .testTarget( name: "SoundManagerTests", dependencies: ["SoundManager"]), ] )
25.517241
117
0.582432
0a2766299a4e9c81c33f5d3f8cbde3aeb446ec72
8,106
// // BackendErrorTests.swift // AptoSDK // // Created by Ivan Oliver Martínez on 20/03/2017. // // import XCTest import SwiftyJSON @testable import AptoSDK class BackendErrorTest: XCTestCase { func testInitWithCoderThrowsException() { // Given let aCoder = NSCoder() // Then expectFatalError("Not implemented") { let _ = BackendError(coder: aCoder) } } func testErrorDomain () { // Given let errorCode = BackendError.ErrorCodes.serviceUnavailable // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.domain == kBackendErrorDomain) } func testInitWithErrorCode() { // Given let errorCode = BackendError.ErrorCodes.serviceUnavailable // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.code == errorCode.rawValue) } func testInitWithReason() { // Given let errorCode = BackendError.ErrorCodes.incorrectParameters let reason = "My Error Reason" // When let serviceError = BackendError(code: errorCode, reason: reason) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedFailureReasonErrorKey]! as! String == reason) } func testInitWithReasonSetsLocalizedDescription() { // Given let errorCode = BackendError.ErrorCodes.undefinedError let description = "Something went wrong." // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedDescriptionKey]! as! String == description) } func testInitWithReasonSetsLocalizedDescription1() { // Given let errorCode = BackendError.ErrorCodes.serviceUnavailable let description = "Something went wrong." // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedDescriptionKey]! as! String == description) } func testInitWithReasonSetsLocalizedDescription2() { // Given let errorCode = BackendError.ErrorCodes.incorrectParameters let description = "Something went wrong." // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedDescriptionKey]! as! String == description) } func testInitWithReasonSetsLocalizedDescription3() { // Given let errorCode = BackendError.ErrorCodes.invalidSession let description = "For your security, your session has timed out due to inactivity." // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedDescriptionKey]! as! String == description) } func testInitWithReasonSetsLocalizedDescription4() { // Given let errorCode = BackendError.ErrorCodes.other let description = "Something went wrong." // When let serviceError = BackendError(code: errorCode) // Then XCTAssertTrue(serviceError.userInfo[NSLocalizedDescriptionKey]! as! String == description) } func testInvalidSessionError() { // Given let errorCode = BackendError.ErrorCodes.invalidSession let serviceError = BackendError(code: errorCode) // When let isInvalidSessionError = serviceError.invalidSessionError() // Then XCTAssertTrue(isInvalidSessionError) } func testInvalidSessionErrorFalse1() { // Given let errorCode = BackendError.ErrorCodes.undefinedError let serviceError = BackendError(code: errorCode) // When let isInvalidSessionError = serviceError.invalidSessionError() // Then XCTAssertFalse(isInvalidSessionError) } func testInvalidSessionErrorFalse2() { // Given let errorCode = BackendError.ErrorCodes.serviceUnavailable let serviceError = BackendError(code: errorCode) // When let isInvalidSessionError = serviceError.invalidSessionError() // Then XCTAssertFalse(isInvalidSessionError) } func testInvalidSessionErrorFalse3() { // Given let errorCode = BackendError.ErrorCodes.incorrectParameters let serviceError = BackendError(code: errorCode) // When let isInvalidSessionError = serviceError.invalidSessionError() // Then XCTAssertFalse(isInvalidSessionError) } func testInvalidSessionErrorFalse4() { // Given let errorCode = BackendError.ErrorCodes.other let serviceError = BackendError(code: errorCode) // When let isInvalidSessionError = serviceError.invalidSessionError() // Then XCTAssertFalse(isInvalidSessionError) } func testJSONParsingNoErrorCodeReturnsNil() { // Given let json: JSON = ["message": "My Message"] // When let backendError = json.backendError // Then XCTAssertNil(backendError) } func testJSONParsingInvalidCodeWithMessageReturnsUndefinedErrorWithReason() { // Given let json: JSON = ["code": 45, "message": "My Message"] // When let backendError = json.backendError // Then XCTAssertNotNil(backendError) XCTAssertEqual(backendError?.code, BackendError.ErrorCodes.undefinedError.rawValue) XCTAssertEqual(backendError?.rawCode, 45) XCTAssertTrue(backendError?.userInfo[NSLocalizedFailureReasonErrorKey]! as! String == "My Message") } func testJSONParsingInvalidCodeReturnsUndefinedError() { // Given let json: JSON = ["code": 45] // When let backendError = json.backendError // Then XCTAssertNotNil(backendError) XCTAssertEqual(backendError?.code, BackendError.ErrorCodes.undefinedError.rawValue) XCTAssertEqual(backendError?.rawCode, 45) XCTAssertNil(backendError?.userInfo[NSLocalizedFailureReasonErrorKey] as? String) } func testJSONParsingCorrectJSONReturnsBackendError() { // Given let json: JSON = ["code": 1, "message": "My Message"] // When let backendError = json.backendError // Then XCTAssertNotNil(backendError) } func testServerMaintenanceErrorServerMaintenanceReturnTrue() { // Given let error = BackendError(code: .serverMaintenance) // When let isServerMaintenance = error.serverMaintenance() // Then XCTAssertTrue(isServerMaintenance) } func testOtherErrorServerMaintenanceReturnFalse() { // Given let error = BackendError(code: .invalidSession) // When let isServerMaintenance = error.serverMaintenance() // Then XCTAssertFalse(isServerMaintenance) } func testNetworkNotAvailableNetworkNotAvailableReturnTrue() { // Given let error = BackendError(code: .networkNotAvailable) // When let isNetworkNotAvailable = error.networkNotAvailable() // Then XCTAssertTrue(isNetworkNotAvailable) } func testOtherErrorNetworkNotAvailableReturnFalse() { // Given let error = BackendError(code: .invalidSession) // When let isNetworkNotAvailable = error.networkNotAvailable() // Then XCTAssertFalse(isNetworkNotAvailable) } func testErrorInfoReturnsCodeAndDescription() { // Given let error = BackendError(code: .addressInvalid) // When let errorInfo = error.eventInfo // Then XCTAssertNotNil(errorInfo["code"]) XCTAssertNotNil(errorInfo["message"]) XCTAssertNil(errorInfo["reason"]) XCTAssertNil(errorInfo["raw_code"]) } func testErrorWithReasonErrorInfoReturnsCodeDescriptionAndReason() { // Given let error = BackendError(code: .addressInvalid, reason: "reason") // When let errorInfo = error.eventInfo // Then XCTAssertNotNil(errorInfo["code"]) XCTAssertNotNil(errorInfo["message"]) XCTAssertNotNil(errorInfo["reason"]) XCTAssertNil(errorInfo["raw_code"]) } func testErrorWithRawCodeErrorInfoReturnsCodeDescriptionAndRawCode() { // Given let error = BackendError(code: .addressInvalid, rawCode: 1234, reason: "reason") // When let errorInfo = error.eventInfo // Then XCTAssertNotNil(errorInfo["code"]) XCTAssertNotNil(errorInfo["message"]) XCTAssertNotNil(errorInfo["reason"]) XCTAssertNotNil(errorInfo["raw_code"]) } }
26.064309
103
0.713916
035faa4c032802c6d74672722c39677e0ecbebca
432
import XCTest #if os(Linux) public func allTests() -> [XCTestCaseEntry] { return [ testCase(DateTimeTests.allTests), testCase(SchedulesTests.allTests), testCase(TaskHubTests.allTests), testCase(TaskTests.allTests), testCase(AtomicTests.allTests), testCase(BucketTests.allTests), testCase(CalendarTests.allTests), testCase(ExtensionsTests.allTests) ] } #endif
25.411765
45
0.673611
ebc215de0491798c5a5876717d011165b922d81b
2,161
// // RangeTest.swift // // Created by Giles Payne on 2020/01/31. // import XCTest import OpenCV class RangeTest: OpenCVTestCase { let r1 = Range(start: 1, end: 11) let r2 = Range(start: 1, end: 1) func testAll() { let range = Range.all() XCTAssertEqual(Int32.min, range.start) XCTAssertEqual(Int32.max, range.end) } func testClone() { let dstRange = r1.clone() XCTAssertEqual(r1, dstRange) } func testEmpty() { var flag = r1.empty() XCTAssertFalse(flag) flag = r2.empty() XCTAssert(flag) } func testEqualsObject() { XCTAssertFalse(r2 == r1) let range = r1.clone() XCTAssert(r1 == range) } func testHashCode() { XCTAssertEqual(r1.hash(), r1.hash()) } func testIntersection() { let range = r1.intersection(r2) XCTAssertEqual(r2, range) } func testRange() { let range = Range() XCTAssertNotNil(range) XCTAssertEqual(0, range.start) XCTAssertEqual(0, range.end) } func testRangeDoubleArray() { let vals:[Double] = [2, 4] let r = Range(vals: vals as [NSNumber]) XCTAssert(2 == r.start); XCTAssert(4 == r.end); } func testRangeIntInt() { let r1 = Range(start: 12, end: 13) XCTAssertNotNil(r1); XCTAssertEqual(12, r1.start); XCTAssertEqual(13, r1.end); } func testSet() { let vals1:[Double] = [] r1.set(vals: vals1 as [NSNumber]) XCTAssertEqual(0, r1.start) XCTAssertEqual(0, r1.end) let vals2 = [6, 10] r2.set(vals: vals2 as [NSNumber]) XCTAssertEqual(6, r2.start) XCTAssertEqual(10, r2.end) } func testShift() { let delta:Int32 = 1 let range = Range().shift(delta) XCTAssertEqual(r2, range) } func testSize() { XCTAssertEqual(10, r1.size()) XCTAssertEqual(0, r2.size()) } func testToString() { let actual = "\(r1)" let expected = "Range {1, 11}" XCTAssertEqual(expected, actual) } }
20.580952
47
0.54882
23d07fc021978b4a95abeb7027a7889b6a619e08
15,705
/* * -------------------------------------------------------------------------------- * <copyright company="Aspose" file="ApiInvoker.swift"> * Copyright (c) 2021 Aspose.Words for Cloud * </copyright> * <summary> * 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. * </summary> * -------------------------------------------------------------------------------- */ import Foundation // Utility class for executing and processing requests to Cloud API @available(macOS 10.12, iOS 10.3, watchOS 3.3, tvOS 12.0, *) public class ApiInvoker { // An object containing the configuration for executing API requests private let configuration : Configuration; // RSA key for password encryption #if os(Linux) // Encryption of passwords in query params not supported on linux #else private var encryptionKey : SecKey?; #endif // Cached value of oauth2 authorization tokeт. // It is filled after the first call to the API. // Mutex is used to synchronize updates in a multi-threaded environment. private let mutex : NSLock; private var accessTokenCache : String?; // Maximum size of printing body content in debug mode private let maxDebugPrintingContentSize = 1024 * 1024; // 1Mb // Status codes for HTTP request private let httpStatusCodeOK = 200; private let httpStatusCodeBadRequest = 400; private let httpStatusCodeUnauthorized = 401; private let httpStatusCodeTimeout = 408; // Initialize ApiInvoker object with specific configuration public init(configuration : Configuration) { self.configuration = configuration; self.mutex = NSLock(); self.accessTokenCache = nil; #if os(Linux) // Encryption of passwords in query params not supported on linux #else self.encryptionKey = nil; #endif } // Internal class for represent API response private class InvokeResponse { public var data : Data?; public var errorCode : Int; public var errorMessage : String?; public init(errorCode : Int) { self.errorCode = errorCode; } } // Internal struct for represent oauth2 authorization response private struct AccessTokenResult : Decodable { public var access_token : String?; } // Invoke request to the API with the specified set of arguments and execute callback after the request is completed public func invoke(apiRequestData : WordsApiRequestData, callback: @escaping (_ response: Data?, _ error: Error?) -> () ) { // Create URL request object var request = URLRequest(url: apiRequestData.getURL()); request.httpMethod = apiRequestData.getMethod(); request.timeoutInterval = self.configuration.getTimeout(); // Fill headers for (key, value) in apiRequestData.getHeaders() { request.setValue(value, forHTTPHeaderField: key); } // Process the request body if (apiRequestData.getBody() != nil) { request.httpBody = apiRequestData.getBody(); } // Request or get from cache authorization token invokeAuthToken(forceTokenRequest: false, callback: { accessToken, statusCode in if (statusCode == self.httpStatusCodeOK) { // When authorization is completed - invoke API request self.invokeRequest(urlRequest: &request, accessToken: accessToken, callback: { response in if (response.errorCode == self.httpStatusCodeUnauthorized) { // Update request token when API request returns 401 error self.invokeAuthToken(forceTokenRequest: true, callback: { accessToken, statusCode in if (statusCode == self.httpStatusCodeOK) { // Retry API request with new authorization token self.invokeRequest(urlRequest: &request, accessToken: accessToken, callback: { response in if (response.errorCode == self.httpStatusCodeOK) { // Api request success callback(response.data, nil); } else { callback(nil, WordsApiError.requestError(errorCode: response.errorCode, message: response.errorMessage)); } }); } else { callback(nil, WordsApiError.requestError(errorCode: statusCode, message: "Authorization failed.")); } }); } else if (response.errorCode == self.httpStatusCodeOK) { // Api request success callback(response.data, nil); } else { callback(nil, WordsApiError.requestError(errorCode: response.errorCode, message: response.errorMessage)); } }); } else { callback(nil, WordsApiError.requestError(errorCode: statusCode, message: "Authorization failed.")); } }); } // Invokes prepared request to the API. Callback returns a response from the API call private func invokeRequest(urlRequest : inout URLRequest, accessToken : String?, callback : @escaping (_ response: InvokeResponse) -> ()) { // Set access token to request headers if (accessToken != nil) { urlRequest.setValue(accessToken!, forHTTPHeaderField: "Authorization"); } // Set statistic headers urlRequest.setValue(self.configuration.getSdkName(), forHTTPHeaderField: "x-aspose-client"); urlRequest.setValue(self.configuration.getSdkVersion(), forHTTPHeaderField: "x-aspose-client-version"); // Print request when debug mode is enabled if (configuration.isDebugMode()) { print("REQUEST BEGIN"); if (urlRequest.url?.absoluteString != nil) { print("URL: \(String(describing: urlRequest.url!.absoluteString))"); } if (urlRequest.allHTTPHeaderFields != nil) { print("HEADERS: \(String(describing: urlRequest.allHTTPHeaderFields!))"); } if (urlRequest.httpBody != nil) { if (urlRequest.httpBody!.count > maxDebugPrintingContentSize) { print("BODY: Response data too long for debug printing. Size: \(urlRequest.httpBody!.count)"); } else { let bodyStr = String(data: urlRequest.httpBody!, encoding: .utf8); if (bodyStr != nil) { print("BODY: \(bodyStr!)"); } else { let chars = urlRequest.httpBody!.map { Character(UnicodeScalar($0)) }; print("BODY: \(String(Array(chars)))"); } } } print("REQUEST END"); } // Execute request let result = URLSession.shared.dataTask(with: urlRequest, completionHandler: { d, r, e in let rawResponse = r as? HTTPURLResponse; let invokeResponse = InvokeResponse(errorCode: self.httpStatusCodeTimeout); invokeResponse.data = d; if (rawResponse != nil) { invokeResponse.errorCode = rawResponse!.statusCode; invokeResponse.errorMessage = rawResponse!.description; } else { invokeResponse.errorCode = self.httpStatusCodeBadRequest; } // Print response when debug mode is enabled if (self.configuration.isDebugMode()) { print("RESPONSE BEGIN"); print("\tSTATUS CODE: \(invokeResponse.errorCode)"); if (invokeResponse.errorMessage != nil) { print("MESSAGE: \(invokeResponse.errorMessage!)"); } if (invokeResponse.data != nil) { if (invokeResponse.data!.count > self.maxDebugPrintingContentSize) { print("BODY: Response data too long for debug printing. Size: \(invokeResponse.data!.count)"); } else { let bodyStr = String(data: invokeResponse.data!, encoding: .utf8); if (bodyStr != nil) { print("BODY: \(bodyStr!)"); } else { let chars = invokeResponse.data!.map { Character(UnicodeScalar($0)) }; print("BODY: \(String(Array(chars)))"); } } } print("RESPONSE END"); } callback(invokeResponse); }); result.resume(); } // Requests authorization token from server. After the first call, the token is cached and the cached value is used for future calls. private func invokeAuthToken(forceTokenRequest: Bool, callback : @escaping (_ accessToken: String?, _ statusCode: Int) -> ()) { var accessToken : String? = nil; if (!forceTokenRequest) { mutex.lock(); if (self.accessTokenCache != nil) { accessToken = String(self.accessTokenCache!); } mutex.unlock(); } if (accessToken == nil) { let urlPath = URL(string: self.configuration.getBaseUrl())!.appendingPathComponent("connect/token"); var request = URLRequest(url: urlPath); request.httpMethod = "POST"; request.timeoutInterval = self.configuration.getTimeout(); request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type"); request.httpBody = "grant_type=client_credentials&client_id=\(configuration.getClientId())&client_secret=\(configuration.getClientSecret())".data(using: .utf8); invokeRequest(urlRequest: &request, accessToken: nil, callback: { response in var newAccessToken : String? = nil; if (response.errorCode == self.httpStatusCodeOK) { do { let result = try ObjectSerializer.deserialize(type: AccessTokenResult.self, from: response.data!); if (result.access_token != nil) { newAccessToken = "Bearer " + result.access_token!; } } catch { // Do nothing } } if (newAccessToken != nil) { self.mutex.lock(); self.accessTokenCache = newAccessToken; self.mutex.unlock(); } callback(newAccessToken, response.errorCode); }); } else { callback(accessToken, self.httpStatusCodeOK); } } private func lengthField(of valueField: [UInt8]) -> [UInt8] { var count = valueField.count; if (count < 128) { return [ UInt8(count) ]; } // The number of bytes needed to encode count. let lengthBytesCount = Int((log2(Double(count)) / 8) + 1); // The first byte in the length field encoding the number of remaining bytes. let firstLengthFieldByte = UInt8(128 + lengthBytesCount); var lengthField: [UInt8] = [] for _ in 0..<lengthBytesCount { // Take the last 8 bits of count. let lengthByte = UInt8(count & 0xff); // Add them to the length field. lengthField.insert(lengthByte, at: 0); // Delete the last 8 bits of count. count = count >> 8; } // Include the first byte. lengthField.insert(firstLengthFieldByte, at: 0); return lengthField; } public func setEncryptionData(data : PublicKeyResponse) throws { #if os(Linux) // Encryption of passwords in query params not supported on linux #else let exponent = Data(base64Encoded: data.getExponent()!)!; let modulus = Data(base64Encoded: data.getModulus()!)!; let exponentBytes = [UInt8](exponent); var modulusBytes = [UInt8](modulus); modulusBytes.insert(0x00, at: 0); var modulusEncoded: [UInt8] = []; modulusEncoded.append(0x02); modulusEncoded.append(contentsOf: lengthField(of: modulusBytes)); modulusEncoded.append(contentsOf: modulusBytes); var exponentEncoded: [UInt8] = []; exponentEncoded.append(0x02); exponentEncoded.append(contentsOf: lengthField(of: exponentBytes)); exponentEncoded.append(contentsOf: exponentBytes); var sequenceEncoded: [UInt8] = []; sequenceEncoded.append(0x30); sequenceEncoded.append(contentsOf: lengthField(of: (modulusEncoded + exponentEncoded))); sequenceEncoded.append(contentsOf: (modulusEncoded + exponentEncoded)); let keyData = Data(bytes: sequenceEncoded); let keySize = (modulusBytes.count * 8); let attributes: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPublic, kSecAttrKeySizeInBits as String: keySize ]; encryptionKey = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, nil); #endif } public func encryptString(value : String) throws -> String { #if os(Linux) // Encryption of passwords in query params not supported on linux return value; #else let buffer = value.data(using: .utf8)!; var error: Unmanaged<CFError>? = nil; // Encrypto should less than key length let secData = SecKeyCreateEncryptedData(encryptionKey!, .rsaEncryptionPKCS1, buffer as CFData, &error)!; var secBuffer = [UInt8](repeating: 0, count: CFDataGetLength(secData)); CFDataGetBytes(secData, CFRangeMake(0, CFDataGetLength(secData)), &secBuffer); return Data(bytes: secBuffer).base64EncodedString().replacingOccurrences(of: "+", with: "%2B").replacingOccurrences(of: "/", with: "%2F"); #endif } public func isEncryptionAllowed() -> Bool { #if os(Linux) return false; #else return true; #endif } }
43.504155
172
0.581535
75480c2c4dda69c7fae4fc155405d267e34caad2
2,618
import Foundation import UIKit import ThemeKit import EthereumKit import CoinKit struct SendEvmData { let transactionData: TransactionData let additionalInfo: AdditionInfo? enum AdditionInfo { case send(info: SendInfo) case uniswap(info: SwapInfo) case oneInchSwap(info: OneInchSwapInfo) var sendInfo: SendInfo? { if case .send(let info) = self { return info } else { return nil } } var swapInfo: SwapInfo? { if case .uniswap(let info) = self { return info } else { return nil } } var oneInchSwapInfo: OneInchSwapInfo? { if case .oneInchSwap(let info) = self { return info } else { return nil } } } struct SendInfo { let domain: String? } struct SwapInfo { let estimatedOut: Decimal let estimatedIn: Decimal let slippage: String? let deadline: String? let recipientDomain: String? let price: String? let priceImpact: String? } struct OneInchSwapInfo { let coinTo: Coin let estimatedAmountTo: Decimal let slippage: String? let recipientDomain: String? } } struct SendEvmConfirmationModule { static func viewController(evmKit: EthereumKit.Kit, sendData: SendEvmData) -> UIViewController? { let feeCoin: Coin? switch evmKit.networkType { case .ethMainNet, .ropsten, .rinkeby, .kovan, .goerli: feeCoin = App.shared.coinKit.coin(type: .ethereum) case .bscMainNet: feeCoin = App.shared.coinKit.coin(type: .binanceSmartChain) } guard let coin = feeCoin, let feeRateProvider = App.shared.feeRateProviderFactory.provider(coinType: coin.type) else { return nil } let coinServiceFactory = EvmCoinServiceFactory(baseCoin: coin, coinKit: App.shared.coinKit, currencyKit: App.shared.currencyKit, rateManager: App.shared.rateManager) let transactionService = EvmTransactionService(evmKit: evmKit, feeRateProvider: feeRateProvider) let service = SendEvmTransactionService(sendData: sendData, evmKit: evmKit, transactionService: transactionService, activateCoinManager: App.shared.activateCoinManager) let transactionViewModel = SendEvmTransactionViewModel(service: service, coinServiceFactory: coinServiceFactory) let feeViewModel = EthereumFeeViewModel(service: transactionService, coinService: coinServiceFactory.baseCoinService) return SendEvmConfirmationViewController(transactionViewModel: transactionViewModel, feeViewModel: feeViewModel) } }
34
176
0.689076
393634447aea4b3d989dc2a949fa5142b9c205db
337
// // LocationsViewControllerDelegate.swift // Photo Map // // Created by Ibukun on 5/8/18. // Copyright © 2018 Timothy Lee. All rights reserved. // import Foundation protocol LocationsViewControllerDelegate : class { func locationsPickedLocation(controller: LocationsViewController, latitude: NSNumber, longitude: NSNumber) }
24.071429
110
0.765579
1c81b6d3a58526d52a1579406c4ba63cd483ee25
606
// // SourceTableViewCell.swift // Go RSS // // Created by Roger on 7/22/15. // Copyright (c) 2015 Roger. All rights reserved. // import UIKit class SourceTableViewCell: UITableViewCell { var object: RSSSource? { didSet { updateUI() } } func updateUI(){ } 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 } }
17.823529
63
0.59571
ff953dce2d03f12ff1d1b47491b8b2c83b6cb7f3
16,932
@testable import Danger import XCTest // swiftlint:disable type_body_length function_body_length line_length final class GitDiffTests: XCTestCase { func testParsesDiff() { let diffParser = DiffParser() XCTAssertEqual(diffParser.parse(testDiff), [ FileDiff(parsedHeader: .init( filePath: ".swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata", change: .created ), hunks: [ .init(oldLineStart: 0, oldLineSpan: 0, newLineStart: 1, newLineSpan: 7, lines: [ FileDiff.Line(text: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", changeType: .added), FileDiff.Line(text: "<Workspace", changeType: .added), FileDiff.Line(text: " version = \"1.0\">", changeType: .added), FileDiff.Line(text: " <FileRef", changeType: .added), FileDiff.Line(text: " location = \"self:\">", changeType: .added), FileDiff.Line(text: " </FileRef>", changeType: .added), FileDiff.Line(text: "</Workspace>", changeType: .added), ]), ]), FileDiff(parsedHeader: .init( filePath: ".swiftpm/xcode/package.xcworkspace/xcuserdata/franco.xcuserdatad/UserInterfaceState.xcuserstate", change: .created ), hunks: []), FileDiff(parsedHeader: .init(filePath: "Gemfile", change: .deleted), hunks: [ .init(oldLineStart: 1, oldLineSpan: 7, newLineStart: 0, newLineSpan: 0, lines: [ FileDiff.Line(text: "# frozen_string_literal: true", changeType: .removed), FileDiff.Line(text: "", changeType: .removed), FileDiff.Line(text: "source \"https://rubygems.org\"", changeType: .removed), FileDiff.Line(text: "", changeType: .removed), FileDiff.Line(text: "git_source(:github) {|repo_name| \"https://github.com/#{repo_name}\" }", changeType: .removed), FileDiff.Line(text: "", changeType: .removed), FileDiff.Line(text: "gem \"xcpretty-json-formatter\"", changeType: .removed), ]), ]), FileDiff(parsedHeader: .init( filePath: "Sources/DangerSwiftCoverage/Models/Report.swift", change: .modified ), hunks: [ .init(oldLineStart: 20, oldLineSpan: 7, newLineStart: 20, newLineSpan: 8, lines: [ FileDiff.Line(text: "extension ReportSection {", changeType: .unchanged), FileDiff.Line(text: " init(fromSPM spm: SPMCoverage, fileManager: FileManager) {", changeType: .unchanged), FileDiff.Line(text: " titleText = nil", changeType: .unchanged), FileDiff.Line(text: " items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + \"/\"), coverage: $0.summary.percent) } }", changeType: .removed), FileDiff.Line(text: " items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + \"/\"), coverage: $0.summary.percent)", changeType: .added), FileDiff.Line(text: " } }", changeType: .added), FileDiff.Line(text: " }", changeType: .unchanged), FileDiff.Line(text: "}", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), ]), ]), FileDiff(parsedHeader: .init( filePath: "Sources/DangerSwiftCoverage/SPM/SPMCoverageParser.swift", change: .modified ), hunks: [ .init(oldLineStart: 1, oldLineSpan: 8, newLineStart: 1, newLineSpan: 11, lines: [ FileDiff.Line(text: "import Foundation", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "protocol SPMCoverageParsing {", changeType: .unchanged), FileDiff.Line(text: " static func coverage(spmCoverageFolder: String, files: [String]) throws -> Report", changeType: .removed), FileDiff.Line(text: "}", changeType: .removed), FileDiff.Line(text: " static func coverage(spmCoverageFolder: String, files: [String]) throws -> Re", changeType: .added), FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "enum SPMCoverageParser: SPMCoverageParsing {", changeType: .unchanged), FileDiff.Line(text: " enum Errors: Error {", changeType: .unchanged), ]), .init(oldLineStart: 22, oldLineSpan: 6, newLineStart: 25, newLineSpan: 10, lines: [ FileDiff.Line(text: " let coverage = try JSONDecoder().decode(SPMCoverage.self, from: data)", changeType: .unchanged), FileDiff.Line(text: " let filteredCoverage = coverage.filteringFiles(notOn: files)", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: " return Report(messages: [], sections: [ReportSection(fromSPM: filteredCoverage, fileManager: fileManager)])", changeType: .removed), FileDiff.Line(text: " if filteredCoverage.data.contains(where: { !$0.files.isEmpty }) {", changeType: .added), FileDiff.Line(text: " return Report(messages: [], sections: [ReportSection(fromSPM: filteredCoverage, fileManager: fileManager)])", changeType: .added), FileDiff.Line(text: " } else {", changeType: .added), FileDiff.Line(text: " return Report(messages: [], sections: [])", changeType: .added), FileDiff.Line(text: " }", changeType: .added), FileDiff.Line(text: " }", changeType: .unchanged), FileDiff.Line(text: "}", changeType: .unchanged), ]), ]), FileDiff(parsedHeader: .init( filePath: "Sources/DangerSwiftCoverage/ShellOutExecutor1.swift", change: .renamed(oldPath: "Sources/DangerSwiftCoverage/ShellOutExecutor.swift") ), hunks: [ .init(oldLineStart: 3, oldLineSpan: 6, newLineStart: 3, newLineSpan: 8, lines: [ FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "protocol ShellOutExecuting {", changeType: .unchanged), FileDiff.Line(text: " func execute(command: String) throws -> Data", changeType: .unchanged), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "}", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "struct ShellOutExecutor: ShellOutExecuting {", changeType: .unchanged), ]), ]), ]) } func testChangeTypeForCreated() { XCTAssertEqual(DiffParser().parse(testDiff)[0].changes, .created(addedLines: [ #"<?xml version="1.0" encoding="UTF-8"?>"#, "<Workspace", #" version = "1.0">"#, " <FileRef", #" location = "self:">"#, " </FileRef>", "</Workspace>", ])) } func testChangeTypeForDeleted() { XCTAssertEqual(DiffParser().parse(testDiff)[2].changes, .deleted(deletedLines: [ "# frozen_string_literal: true", "", #"source "https://rubygems.org""#, "", #"git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }"#, "", #"gem "xcpretty-json-formatter""#, ])) } func testChangeTypeForModified() { XCTAssertEqual(DiffParser().parse(testDiff)[3].changes, .modified(hunks: [ .init(oldLineStart: 20, oldLineSpan: 7, newLineStart: 20, newLineSpan: 8, lines: [ FileDiff.Line(text: "extension ReportSection {", changeType: .unchanged), FileDiff.Line(text: " init(fromSPM spm: SPMCoverage, fileManager: FileManager) {", changeType: .unchanged), FileDiff.Line(text: " titleText = nil", changeType: .unchanged), FileDiff.Line(text: " items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + \"/\"), coverage: $0.summary.percent) } }", changeType: .removed), FileDiff.Line(text: " items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + \"/\"), coverage: $0.summary.percent)", changeType: .added), FileDiff.Line(text: " } }", changeType: .added), FileDiff.Line(text: " }", changeType: .unchanged), FileDiff.Line(text: "}", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), ]), ])) } func testChangeTypeForRenamed() { XCTAssertEqual(DiffParser().parse(testDiff)[5].changes, .renamed(oldPath: "Sources/DangerSwiftCoverage/ShellOutExecutor.swift", hunks: [ .init(oldLineStart: 3, oldLineSpan: 6, newLineStart: 3, newLineSpan: 8, lines: [ FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "protocol ShellOutExecuting {", changeType: .unchanged), FileDiff.Line(text: " func execute(command: String) throws -> Data", changeType: .unchanged), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "", changeType: .added), FileDiff.Line(text: "}", changeType: .unchanged), FileDiff.Line(text: "", changeType: .unchanged), FileDiff.Line(text: "struct ShellOutExecutor: ShellOutExecuting {", changeType: .unchanged), ]), ])) } // swiftformat:disable all var testDiff: String { """ diff --git a/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Workspace + version = "1.0"> + <FileRef + location = "self:"> + </FileRef> +</Workspace> diff --git a/.swiftpm/xcode/package.xcworkspace/xcuserdata/franco.xcuserdatad/UserInterfaceState.xcuserstate b/.swiftpm/xcode/package.xcworkspace/xcuserdata/franco.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..70bdf2c Binary files /dev/null and b/.swiftpm/xcode/package.xcworkspace/xcuserdata/franco.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Gemfile b/Gemfile deleted file mode 100644 index d7ba66f..0000000 --- a/Gemfile +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true - -source "https://rubygems.org" - -git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } - -gem "xcpretty-json-formatter" diff --git a/Sources/DangerSwiftCoverage/Models/Report.swift b/Sources/DangerSwiftCoverage/Models/Report.swift index 4866851..23ea2be 100644 --- a/Sources/DangerSwiftCoverage/Models/Report.swift +++ b/Sources/DangerSwiftCoverage/Models/Report.swift @@ -20,7 +20,8 @@ extension ReportSection { extension ReportSection { init(fromSPM spm: SPMCoverage, fileManager: FileManager) { titleText = nil - items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + "/"), coverage: $0.summary.percent) } } + items = spm.data.flatMap { $0.files.map { ReportFile(fileName: $0.filename.deletingPrefix(fileManager.currentDirectoryPath + "/"), coverage: $0.summary.percent) + } } } } diff --git a/Sources/DangerSwiftCoverage/SPM/SPMCoverageParser.swift b/Sources/DangerSwiftCoverage/SPM/SPMCoverageParser.swift index 7b22444..1e7d9ff 100644 --- a/Sources/DangerSwiftCoverage/SPM/SPMCoverageParser.swift +++ b/Sources/DangerSwiftCoverage/SPM/SPMCoverageParser.swift @@ -1,8 +1,11 @@ import Foundation + + + + protocol SPMCoverageParsing { - static func coverage(spmCoverageFolder: String, files: [String]) throws -> Report -} + static func coverage(spmCoverageFolder: String, files: [String]) throws -> Re enum SPMCoverageParser: SPMCoverageParsing { enum Errors: Error { @@ -22,6 +25,10 @@ enum SPMCoverageParser: SPMCoverageParsing { let coverage = try JSONDecoder().decode(SPMCoverage.self, from: data) let filteredCoverage = coverage.filteringFiles(notOn: files) - return Report(messages: [], sections: [ReportSection(fromSPM: filteredCoverage, fileManager: fileManager)]) + if filteredCoverage.data.contains(where: { !$0.files.isEmpty }) { + return Report(messages: [], sections: [ReportSection(fromSPM: filteredCoverage, fileManager: fileManager)]) + } else { + return Report(messages: [], sections: []) + } } } diff --git a/Sources/DangerSwiftCoverage/ShellOutExecutor.swift b/Sources/DangerSwiftCoverage/ShellOutExecutor1.swift similarity index 99% rename from Sources/DangerSwiftCoverage/ShellOutExecutor.swift rename to Sources/DangerSwiftCoverage/ShellOutExecutor1.swift index 2716c0f..eaa54b1 100644 --- a/Sources/DangerSwiftCoverage/ShellOutExecutor.swift +++ b/Sources/DangerSwiftCoverage/ShellOutExecutor1.swift @@ -3,6 +3,8 @@ import Foundation protocol ShellOutExecuting { func execute(command: String) throws -> Data + + } struct ShellOutExecutor: ShellOutExecuting { """ } }
62.944238
236
0.515001
f443f652be265998353789eb3707cec3e4876508
12,264
// // TagsEventViewController.swift // Revels-20 // // Created by Rohit Kuber on 27/09/20. // Copyright © 2020 Naman Jain. All rights reserved. import UIKit import AudioToolbox struct taggedEvents: Decodable{ let name: String let tags: [String] } class TagsEventsViewController: UIViewController, TagsControllerDelegate, UITableViewDelegate, UITableViewDataSource{ let slideInTransitioningDelegate = SlideInPresentationManager(from: UIViewController(), to: UIViewController()) var events = [Event]() var tags = [String]() var filteredEvents: [Event]?{ didSet{ guard filteredEvents != nil else { return } // self.eventsTableView.reloadData(with: .automatic) UIView.transition(with: eventsTableView, duration: 0.3, options: .transitionCrossDissolve, animations: { self.eventsTableView.reloadData() }) } } func didTapTag(indexPath: IndexPath) { print(tags[indexPath.row]) let tag = tags[indexPath.row] if tag == "All"{ self.filteredEvents = self.events return } self.filteredEvents = self.events.filter({ (event) -> Bool in event.tags!.contains(tag) }) // print(self.filteredEvents) } lazy var eventsTableView: UITableView = { let tableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.register(CategoryTableViewCell.self, forCellReuseIdentifier: cellId) tableView.backgroundColor = UIColor.CustomColors.Black.background tableView.separatorStyle = .none tableView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 8, right: 0) return tableView }() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } fileprivate let tagsController = TagsController(collectionViewLayout: UICollectionViewFlowLayout()) fileprivate let cellId = "cellId" fileprivate let menuCellId = "menuCellId" override func viewDidLoad() { super.viewDidLoad() navigationItem.largeTitleDisplayMode = .never self.events = Caching.sharedInstance.getEventsFromCache() // print(events) self.tags = Caching.sharedInstance.getTagsFromCache() setupTagsController() setupLayout() setupNavigationBar() self.filteredEvents = self.events } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) updateStatusBar() } private var themedStatusBarStyle: UIStatusBarStyle? func updateStatusBar(){ themedStatusBarStyle = .lightContent setNeedsStatusBarAppearanceUpdate() } fileprivate func setupNavigationBar(){ self.navigationItem.title = "Events" } fileprivate func setupTagsController() { tagsController.delegate = self tagsController.tags = self.tags tagsController.markerBar.backgroundColor = UIColor.CustomColors.Purple.accent tagsController.specialColor = UIColor.CustomColors.Purple.accent// Setting special colour here tagsController.menuBar.backgroundColor = UIColor.CustomColors.Black.background tagsController.collectionView.backgroundColor = UIColor.CustomColors.Black.background tagsController.shadowBar.backgroundColor = UIColor.CustomColors.Black.background } fileprivate func setupLayout() { let tagsView = tagsController.view! tagsView.backgroundColor = .white view.addSubview(tagsView) _ = tagsView.anchor(top: view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 50) tagsController.collectionView.selectItem(at: [0, 0], animated: true, scrollPosition: .centeredHorizontally) view.backgroundColor = UIColor.CustomColors.Black.background view.addSubview(eventsTableView) eventsTableView.anchor(top: tagsView.bottomAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredEvents?.count ?? 0 // return } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! CategoryTableViewCell cell.titleLabel.text = filteredEvents?[indexPath.row].name ?? "" var desc = filteredEvents?[indexPath.row].description ?? "" if desc == "" { desc = filteredEvents?[indexPath.row].description ?? "" } cell.descriptionLabel.text = desc return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let event = filteredEvents?[indexPath.row]{ self.handleEventTap(withEvent: event) } } func handleEventTap(withEvent event: Event){ AudioServicesPlaySystemSound(1519) let eventViewController = EventsViewController() slideInTransitioningDelegate.categoryName = "" //"\(event.description)" eventViewController.modalPresentationStyle = .custom eventViewController.transitioningDelegate = slideInTransitioningDelegate eventViewController.event = event eventViewController.schedule = nil eventViewController.tagsEventController = self eventViewController.fromTags = true present(eventViewController, animated: true, completion: nil) // print(event.eventID) // print(event.name) } } protocol TagsControllerDelegate { func didTapTag(indexPath: IndexPath) } class TagsController: UICollectionViewController, UICollectionViewDelegateFlowLayout { fileprivate let cellId = "cellId" var tags: [String]?{ didSet{ collectionView.reloadData() collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .centeredHorizontally) } } var specialColor: UIColor? var delegate: TagsControllerDelegate? let menuBar: UIView = { let v = UIView() v.backgroundColor = .white return v }() lazy var markerBar: UIView = { let v = UIView() v.backgroundColor = .black v.translatesAutoresizingMaskIntoConstraints = false return v }() let shadowBar: UIView = { let v = UIView() v.backgroundColor = .lightGray return v }() override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true) delegate?.didTapTag(indexPath: indexPath) } override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .white collectionView.register(TagCell.self, forCellWithReuseIdentifier: cellId) if let layout = collectionViewLayout as? UICollectionViewFlowLayout { layout.scrollDirection = .horizontal layout.minimumLineSpacing = -8 layout.minimumInteritemSpacing = -8 } collectionView.showsHorizontalScrollIndicator = false } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tags?.count ?? 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TagCell cell.label.text = tags?[indexPath.item] ?? "" if let color = specialColor{ cell.color = color } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //UIFont.systemFont(ofSize: 16, weight: .regular) let tag = self.tags?[indexPath.item] ?? "" let width: CGFloat! if isSmalliPhone(){ width = tag.width(withConstrainedHeight: 35, font: UIFont.systemFont(ofSize: 13, weight: .regular)) + 40 }else{ width = tag.width(withConstrainedHeight: 35, font: UIFont.systemFont(ofSize: 16, weight: .regular)) + 48 } return .init(width: width, height: 40) } } extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil) return ceil(boundingBox.height) } func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil) return ceil(boundingBox.width) } } class TagCell: UICollectionViewCell { var color: UIColor?{ didSet { if isSelected{ label.textColor = color backgroundCardView.layer.borderColor = color?.cgColor } } } let backgroundCardView: UIView = { let view = UIView() view.backgroundColor = #colorLiteral(red: 0.0628238342, green: 0.0628238342, blue: 0.0628238342, alpha: 1) view.layer.cornerRadius = 5 view.layer.borderWidth = 0.15 view.layer.borderColor = UIColor.lightGray.cgColor return view }() let label: UILabel = { let l = UILabel() l.text = "Tag" l.textAlignment = .center l.textColor = .lightGray l.font = UIFont.systemFont(ofSize: 14, weight: .regular) return l }() override var isSelected: Bool { didSet { label.textColor = isSelected ? color ?? .black : .lightGray if UIViewController().isSmalliPhone(){ label.font = isSelected ? UIFont.systemFont(ofSize: 12, weight: .medium) : UIFont.systemFont(ofSize: 12, weight: .regular) }else{ label.font = isSelected ? UIFont.systemFont(ofSize: 14, weight: .medium) : UIFont.systemFont(ofSize: 14, weight: .regular) } backgroundCardView.layer.borderColor = isSelected ? color?.cgColor : UIColor.lightGray.cgColor backgroundCardView.layer.borderWidth = isSelected ? 0.7 : 0.15 } } override init(frame: CGRect) { super.init(frame: frame) if UIViewController().isSmalliPhone(){ label.font = UIFont.systemFont(ofSize: 12, weight: .regular) } addSubview(backgroundCardView) backgroundCardView.anchorWithConstants(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8) backgroundCardView.addSubview(label) label.anchorWithConstants(top: backgroundCardView.topAnchor, left: backgroundCardView.leftAnchor, bottom: backgroundCardView.bottomAnchor, right: backgroundCardView.rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 8) } required init?(coder aDecoder: NSCoder) { fatalError() } }
36.939759
255
0.661774
56f983ed7182af629a88be61d8b1dbe18a97a595
457
import Basic import Foundation import xcodeproj func fixturesPath() -> AbsolutePath { return AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory.parentDirectory.appending(component: "Fixtures") } func iosProjectDictionary() -> (AbsolutePath, Dictionary<String, Any>) { let iosProject = fixturesPath().appending(RelativePath("iOS/Project.xcodeproj/project.pbxproj")) return (iosProject, loadPlist(path: iosProject.asString)!) }
35.153846
127
0.785558
2240958db57541d4a1d5c48a39e9213033adeb3d
2,764
// // PostsDataViewDelegate.swift // Basem Emara // // Created by Basem Emara on 2018-06-21. // Copyright © 2018 Zamzam Inc. All rights reserved. // #if os(iOS) import Foundation import UIKit import ZamzamCore import ZamzamUI public protocol PostsDataViewDelegate: AnyObject { func postsDataView(didSelect model: PostsDataViewModel, at indexPath: IndexPath, from dataView: DataViewable) func postsDataView(toggleFavorite model: PostsDataViewModel) func postsDataViewNumberOfSections(in dataView: DataViewable) -> Int func postsDataViewDidReloadData() func postsDataView(leadingSwipeActionsFor model: PostsDataViewModel, at indexPath: IndexPath, from tableView: UITableView) -> UISwipeActionsConfiguration? func postsDataView(trailingSwipeActionsFor model: PostsDataViewModel, at indexPath: IndexPath, from tableView: UITableView) -> UISwipeActionsConfiguration? @available(iOS 13, *) func postsDataView(contextMenuConfigurationFor model: PostsDataViewModel, at indexPath: IndexPath, point: CGPoint, from dataView: DataViewable) -> UIContextMenuConfiguration? @available(iOS 13, *) func postsDataView(didPerformPreviewActionFor model: PostsDataViewModel, from dataView: DataViewable) func postsDataViewWillBeginDragging(_ scrollView: UIScrollView) func postsDataViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) } // Optional conformance public extension PostsDataViewDelegate { func postsDataView(toggleFavorite model: PostsDataViewModel) {} func postsDataViewNumberOfSections(in dataView: DataViewable) -> Int { return 1 } func postsDataViewDidReloadData() {} func postsDataView(leadingSwipeActionsFor model: PostsDataViewModel, at indexPath: IndexPath, from tableView: UITableView) -> UISwipeActionsConfiguration? { UISwipeActionsConfiguration() } func postsDataView(trailingSwipeActionsFor model: PostsDataViewModel, at indexPath: IndexPath, from tableView: UITableView) -> UISwipeActionsConfiguration? { UISwipeActionsConfiguration() } @available(iOS 13, *) func postsDataView(contextMenuConfigurationFor model: PostsDataViewModel, at indexPath: IndexPath, point: CGPoint, from dataView: DataViewable) -> UIContextMenuConfiguration? { nil } @available(iOS 13, *) func postsDataView(didPerformPreviewActionFor model: PostsDataViewModel, from dataView: DataViewable) {} func postsDataViewWillBeginDragging(_ scrollView: UIScrollView) {} func postsDataViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {} } #endif
45.311475
180
0.77822
20d419ec5f712342ac6f10667f101997572de945
730
// // PublicView.swift // LayoutPlaygroundFramework // // Created by Yuki Nagai on 3/5/16. // Copyright © 2016 uny. All rights reserved. // import UIKit import SnapKit public final class PublicView: UIView { private let label = UILabel() public init() { let frame = CGRect(x: 0, y: 0, width: 240, height: 240) super.init(frame: frame) self.backgroundColor = .whiteColor() self.addSubview(self.label) self.label.text = "LayoutPlayground" self.label.snp_makeConstraints { make in make.center.equalTo(self) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
23.548387
63
0.620548
9bd25a56b6a84893b89343b057111476a4e800e6
3,089
// // Transaction.swift // src // // Created by Anil Kumar BP on 11/17/15. // Copyright (c) 2015 Anil Kumar BP. All rights reserved. // import Foundation public class ApiResponse { // ApiResponse Constants internal var jsonAsArray = [String: AnyObject]() internal var jsonAsObject: AnyObject? = AnyObject?() internal var multipartTransactions: AnyObject? = AnyObject?() internal var request: NSMutableURLRequest? internal var raw: AnyObject? = AnyObject?() internal var jsonAsString: String = "" // Data Response Error Initialization private var data: NSData? private var response: NSURLResponse? private var error: NSError? private var dict: NSDictionary? /// Constructor for the ApiResponse /// /// @param: request NSMutableURLRequest /// @param: data Instance of NSData /// @param: response Instance of NSURLResponse /// @param: error Instance of NSError init(request: NSMutableURLRequest, status: Int = 200, data: NSData?, response: NSURLResponse?, error: NSError?) { self.request = request self.data = data self.response = response self.error = error } public func getText() -> String { if let check = data { return check.description } else { return "No data." } } public func getRaw() -> Any { return raw } public func getJson() -> [String: AnyObject] { return jsonAsArray } public func getJsonAsString() -> String { return jsonAsString } public func getMultipart() -> AnyObject? { return self.multipartTransactions } public func isOK() -> Bool { return (self.response as! NSHTTPURLResponse).statusCode / 100 == 2 } public func getError() -> NSError? { return error } public func getData() -> NSData? { return self.data } public func getDict() -> Dictionary<String,NSObject> { var errors: NSError? self.dict = NSJSONSerialization.JSONObjectWithData(self.data!, options: nil, error: &errors) as? NSDictionary return self.dict as! Dictionary<String, NSObject> } public func getRequest() -> NSMutableURLRequest? { return request } public func getResponse() -> NSURLResponse? { return response } func isContentType(type: String) -> Bool { return false } func getContentType() { } public func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } } return "" } }
28.601852
117
0.605374
9c29b5c8092563cad19c4cccdd3a42e39efd8502
23,477
/* * Copyright 2019 Google LLC. 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 AVFoundation import Photos import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialPalettes import MaterialComponents.MaterialTypography protocol PermissionsGuideDelegate: class { /// Informs the delegate the guide was completed and should be closed. func permissionsGuideDidComplete(_ viewController: PermissionsGuideViewController) } // swiftlint:disable type_body_length /// An animated, multi-step guide to walk the user through granting Science Journal all the various /// permissions needed. class PermissionsGuideViewController: OnboardingViewController { enum Metrics { static let headerTopPaddingNarrow: CGFloat = 34.0 static let headerTopPaddingNarrowSmallScreen: CGFloat = 80.0 static let headerTopPaddingWide: CGFloat = 40.0 static let headerTopPaddingWideSmallScreen: CGFloat = 20.0 static let individualMessageTopPaddingNarrow: CGFloat = 80.0 static let individualMessageTopPaddingNarrowSmallScreen: CGFloat = 60.0 static let individualMessageTopPaddingWide: CGFloat = 40.0 static let individualMessageTopPaddingWideSmallScreen: CGFloat = 20.0 static let checkPadding: CGFloat = 6.0 static let doneYOffset: CGFloat = 10.0 static let continueYOffset: CGFloat = 10.0 static let arduinoLogoBottomPadding: CGFloat = 30.0 static let buttonHeight: CGFloat = 44.0 static let buttonWidth: CGFloat = 220.0 } // MARK: - Properties private weak var delegate: PermissionsGuideDelegate? private let headerTitle = UILabel() private let initialMessage = UILabel() private let finalMessage = UILabel() private let notificationsMessage = UILabel() private let microphoneMessage = UILabel() private let cameraMessage = UILabel() private let photoLibraryMessage = UILabel() private let completeButton = UIButton(type: .system) private let continueButton = UIButton(type: .system) private let startButton = UIButton(type: .system) private let logoImageView = UIImageView(image: UIImage(named: "arduino_education_logo")) private let stepsImageView = UIImageView() private let stepHeader = UIStackView() private let stepIcon = UIImageView() private let stepTitle = UILabel() private let devicePreferenceManager: DevicePreferenceManager // Used to store label constrains that will be modified on rotation. private var labelLeadingConstraints = [NSLayoutConstraint]() private var labelTrailingConstraints = [NSLayoutConstraint]() private var headerTopConstraint: NSLayoutConstraint? private var continueTopConstraint: NSLayoutConstraint? // The duration to animate the permission check button in. private var permissionCheckDuration: TimeInterval { return UIAccessibility.isVoiceOverRunning ? 0.3 : 0 } // The interval to wait before moving to the next step. private var nextStepDelayInterval: TimeInterval { return UIAccessibility.isVoiceOverRunning ? 0.8 : 0.5 } // Steps in order. private var steps = [stepNotifications, stepMicrophone, stepCamera, stepPhotoLibrary] private let showWelcomeView: Bool // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - delegate: The permissions guide delegate. /// - analyticsReporter: The analytics reporter. /// - devicePreferenceManager: The device preference manager. /// - showWelcomeView: Whether to show the welcome view first. init(delegate: PermissionsGuideDelegate, analyticsReporter: AnalyticsReporter, devicePreferenceManager: DevicePreferenceManager, showWelcomeView: Bool) { self.delegate = delegate self.devicePreferenceManager = devicePreferenceManager self.showWelcomeView = showWelcomeView super.init(analyticsReporter: analyticsReporter) NotificationCenter.default.addObserver( self, selector: #selector(notificationRegistrationComplete), name: LocalNotificationManager.PushNotificationRegistrationComplete, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() configureView() if showWelcomeView { stepWelcome() } else { performNextStep() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateConstraintsForSize(view.bounds.size) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // If a user sees this VC, we consider them to have completed the permissions guide. This // is because there are certain types of permissions we cannot check the state of without // popping, which means it would be difficult to show/hide only the permissions they need. // Therefore, we mark them complete once they start, and we ask for permissions in key places // of the app just in case. devicePreferenceManager.hasAUserCompletedPermissionsGuide = true } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (_) in self.updateConstraintsForSize(size) self.view.layoutIfNeeded() }) } // MARK: - Private override func configureView() { super.configureView() configureHeaderImagePinnedToTop() // Arduino logo. configureArduinoLogo() // Step header. configureStepHeader() // Header label. wrappingView.addSubview(headerTitle) headerTitle.translatesAutoresizingMaskIntoConstraints = false headerTopConstraint = headerTitle.topAnchor.constraint(equalTo: headerImage.bottomAnchor, constant: Metrics.headerTopPaddingNarrow) headerTopConstraint?.priority = .defaultHigh headerTopConstraint?.isActive = true headerTitle.textColor = ArduinoColorPalette.goldPalette.tint400 headerTitle.font = ArduinoTypography.boldFont(forSize: 28) headerTitle.textAlignment = .center headerTitle.text = String.permissionsGuideWelcomeTitle.localizedUppercase headerTitle.numberOfLines = 0 headerTitle.leadingAnchor.constraint(equalTo: wrappingView.readableContentGuide.leadingAnchor).isActive = true headerTitle.trailingAnchor.constraint(equalTo: wrappingView.readableContentGuide.trailingAnchor).isActive = true headerTitle.topAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: headerImage.bottomAnchor, multiplier: 1).isActive = true // Shared label config. [initialMessage, finalMessage, notificationsMessage, microphoneMessage, cameraMessage, photoLibraryMessage].forEach { wrappingView.addSubview($0) $0.translatesAutoresizingMaskIntoConstraints = false labelLeadingConstraints.append( $0.leadingAnchor.constraint(equalTo: wrappingView.readableContentGuide.leadingAnchor)) labelTrailingConstraints.append( $0.trailingAnchor.constraint(equalTo: wrappingView.readableContentGuide.trailingAnchor)) $0.font = Metrics.bodyFont $0.textColor = ArduinoColorPalette.grayPalette.tint800 $0.alpha = 0 $0.numberOfLines = 0 $0.textAlignment = .natural $0.setContentCompressionResistancePriority(.defaultHigh + 1, for: .vertical) } initialMessage.textAlignment = .center NSLayoutConstraint.activate(labelLeadingConstraints) NSLayoutConstraint.activate(labelTrailingConstraints) // Initial into message and final message. initialMessage.alpha = 1 initialMessage.text = String.permissionsGuideMessageIntro initialMessage.topAnchor.constraint(equalTo: headerTitle.bottomAnchor, constant: Metrics.innerSpacing).isActive = true finalMessage.text = String.permissionsGuideAllDoneMessage finalMessage.topAnchor.constraint(equalToSystemSpacingBelow: stepHeader.bottomAnchor, multiplier: 1).isActive = true // Individual messages. notificationsMessage.text = String.permissionsGuideNotificationsInfo microphoneMessage.text = String.permissionsGuideMicrophoneInfo cameraMessage.text = String.permissionsGuideCameraInfo photoLibraryMessage.text = String.permissionsGuidePhotoLibraryInfo // Shared individual message config. var labelTopConstraints = [NSLayoutConstraint]() [notificationsMessage, microphoneMessage, cameraMessage, photoLibraryMessage].forEach { labelTopConstraints.append($0.topAnchor.constraint(equalToSystemSpacingBelow: stepHeader.bottomAnchor, multiplier: 1)) } NSLayoutConstraint.activate(labelTopConstraints) // Shared button config. [startButton, completeButton, continueButton].forEach { $0.contentEdgeInsets = UIEdgeInsets(top: 0, left: Metrics.buttonHeight/2.0, bottom: 0, right: Metrics.buttonHeight/2.0) wrappingView.addSubview($0) $0.translatesAutoresizingMaskIntoConstraints = false $0.centerXAnchor.constraint(equalTo: wrappingView.centerXAnchor).isActive = true $0.heightAnchor.constraint(equalToConstant: Metrics.buttonHeight).isActive = true $0.widthAnchor.constraint(greaterThanOrEqualToConstant: Metrics.buttonWidth).isActive = true $0.setBackgroundImage(UIImage(named: "rounded_button_background"), for: .normal) $0.titleLabel?.font = ArduinoTypography.boldFont(forSize: 16) $0.setTitleColor(view.backgroundColor, for: .normal) $0.isHidden = true } // Start button. startButton.isHidden = false startButton.setTitle(String.permissionsGuideStartButtonTitle.uppercased(), for: .normal) let startButtonTopAnchor = startButton.topAnchor.constraint(equalTo: initialMessage.bottomAnchor, constant: Metrics.buttonSpacing) startButtonTopAnchor.priority = .defaultHigh startButtonTopAnchor.isActive = true logoImageView.topAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: startButton.bottomAnchor, multiplier: 1.0).isActive = true startButton.addTarget(self, action: #selector(startGuideButtonPressed), for: .touchUpInside) // Complete button. completeButton.setTitle(String.permissionsGuideFinishButtonTitle.uppercased(), for: .normal) completeButton.topAnchor.constraint(equalTo: finalMessage.bottomAnchor, constant: Metrics.buttonSpacing).isActive = true completeButton.addTarget(self, action: #selector(completeGuideButtonPressed), for: .touchUpInside) // The continue button, to start each step's system prompt after a user has read the message. continueButton.setTitle(String.permissionsGuideContinueButtonTitle.uppercased(), for: .normal) continueButton.centerXAnchor.constraint(equalTo: wrappingView.centerXAnchor).isActive = true continueTopConstraint = continueButton.topAnchor.constraint(equalTo: notificationsMessage.bottomAnchor, constant: Metrics.buttonSpacing) continueTopConstraint?.priority = .defaultHigh-1 continueTopConstraint?.isActive = true startButton.topAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: initialMessage.bottomAnchor, multiplier: 1).isActive = true // Step counter configureStepsImageView() } private func configureArduinoLogo() { logoImageView.translatesAutoresizingMaskIntoConstraints = false logoImageView.contentMode = .scaleAspectFit wrappingView.addSubview(logoImageView) logoImageView.centerXAnchor.constraint(equalTo: wrappingView.centerXAnchor).isActive = true logoImageView.bottomAnchor.constraint(equalTo: wrappingView.safeAreaLayoutGuide.bottomAnchor, constant: -Metrics.arduinoLogoBottomPadding).isActive = true } private func configureStepHeader() { stepIcon.setContentHuggingPriority(.required, for: .horizontal) stepTitle.font = ArduinoTypography.boldFont(forSize: 16) stepTitle.textColor = ArduinoColorPalette.grayPalette.tint600 stepHeader.axis = .horizontal stepHeader.alignment = .center stepHeader.spacing = 10 stepHeader.addArrangedSubview(stepIcon) stepHeader.addArrangedSubview(stepTitle) stepHeader.translatesAutoresizingMaskIntoConstraints = false wrappingView.addSubview(stepHeader) let leadingAnchor = stepHeader.leadingAnchor.constraint(equalTo: wrappingView.readableContentGuide.leadingAnchor) let trailingAnchor = stepHeader.trailingAnchor.constraint(equalTo: wrappingView.readableContentGuide.trailingAnchor) labelLeadingConstraints.append(leadingAnchor) labelTrailingConstraints.append(trailingAnchor) NSLayoutConstraint.activate([ leadingAnchor, trailingAnchor, stepHeader.topAnchor.constraint(equalTo: headerImage.bottomAnchor, constant: Metrics.headerTopPaddingNarrow) ]) stepHeader.isHidden = true } private func configureStepsImageView() { stepsImageView.isHidden = true stepsImageView.translatesAutoresizingMaskIntoConstraints = false stepsImageView.setContentCompressionResistancePriority(.required, for: .vertical) wrappingView.addSubview(stepsImageView) stepsImageView.centerXAnchor.constraint(equalTo: wrappingView.centerXAnchor).isActive = true stepsImageView.bottomAnchor.constraint(equalTo: wrappingView.safeAreaLayoutGuide.bottomAnchor, constant: -Metrics.arduinoLogoBottomPadding).isActive = true stepsImageView.topAnchor.constraint(greaterThanOrEqualToSystemSpacingBelow: continueButton.bottomAnchor, multiplier: 1.0).isActive = true } // Updates constraints for labels. Used in rotation to ensure the best fit for various screen // sizes. private func updateConstraintsForSize(_ size: CGSize) { guard UIDevice.current.userInterfaceIdiom != .pad else { return } var headerTopPadding: CGFloat if size.isWiderThanTall { if size.width <= 568 { headerTopPadding = Metrics.headerTopPaddingWideSmallScreen } else { headerTopPadding = Metrics.headerTopPaddingWide } } else { if size.width <= 320 { headerTopPadding = Metrics.headerTopPaddingNarrowSmallScreen } else { headerTopPadding = Metrics.headerTopPaddingNarrow } } headerTopConstraint?.constant = headerTopPadding labelLeadingConstraints.forEach { $0.constant = size.isWiderThanTall ? Metrics.outerPaddingWide : Metrics.outerPaddingNarrow } labelTrailingConstraints.forEach { $0.constant = size.isWiderThanTall ? -Metrics.outerPaddingWide : -Metrics.outerPaddingNarrow } } // Animates to a step and fires a completion once done. private func animateToStep(animations: @escaping () -> Void, completion: (() -> Void)? = nil) { animations() completion?() } // MARK: - Steps // Displays the done notice and then, after a delay, performs the next step. private func markStepDoneAndPerformNext() { performNextStep() } // Performs the next step in the guide or, if none are left, shows the conclusion. private func performNextStep() { guard steps.count > 0 else { stepsDone() return } let nextStep = steps.remove(at: 0) nextStep(self)() } // MARK: Welcome private func stepWelcome() { headerTitle.alpha = 1 initialMessage.alpha = 1 } // MARK: Push notifications // Ask for push notification permissions. private func stepNotifications() { updateContinueButtonConstraint(forLabel: notificationsMessage) continueButton.removeTarget(nil, action: nil, for: .allEvents) continueButton.addTarget(self, action: #selector(checkForNotificationPermissions), for: .touchUpInside) let showNotificationsState = { self.headerTitle.alpha = 0 self.initialMessage.alpha = 0 self.startButton.isHidden = true self.continueButton.isHidden = false self.continueButton.isEnabled = true self.notificationsMessage.alpha = 1 self.logoImageView.isHidden = true self.stepsImageView.isHidden = false self.stepsImageView.image = UIImage(named: "permissions_step_1") self.stepHeader.isHidden = false self.stepIcon.image = UIImage(named: "permissions_step_notifications_icon") self.stepTitle.text = String.permissionsGuideNotificationsTitle.localizedUppercase } animateToStep(animations: showNotificationsState) { UIAccessibility.post(notification: .layoutChanged, argument: self.notificationsMessage) } } @objc private func checkForNotificationPermissions() { UIView.animate(withDuration: permissionCheckDuration, animations: { self.continueButton.isEnabled = false }) { (_) in LocalNotificationManager.shared.registerUserNotifications() } } // Listen for step 1 completion before moving to step 2. @objc private func notificationRegistrationComplete() { self.markStepDoneAndPerformNext() } // MARK: Microphone // Ask for microphone permissions. private func stepMicrophone() { updateContinueButtonConstraint(forLabel: microphoneMessage) continueButton.removeTarget(nil, action: nil, for: .allEvents) continueButton.addTarget(self, action: #selector(checkForMicrophonePermissions), for: .touchUpInside) let showNotificationsState = { self.continueButton.isEnabled = true self.notificationsMessage.alpha = 0 self.microphoneMessage.alpha = 1 self.stepsImageView.image = UIImage(named: "permissions_step_2") self.stepIcon.image = UIImage(named: "permissions_step_microphone_icon") self.stepTitle.text = String.permissionsGuideMicrophoneTitle.localizedUppercase } animateToStep(animations: showNotificationsState) { UIAccessibility.post(notification: .layoutChanged, argument: self.microphoneMessage) } } @objc private func checkForMicrophonePermissions() { UIView.animate(withDuration: permissionCheckDuration, animations: { self.continueButton.isEnabled = false }) { (_) in AVAudioSession.sharedInstance().requestRecordPermission { _ in DispatchQueue.main.async { self.markStepDoneAndPerformNext() } } } } // MARK: Camera // Ask for camera permissions. private func stepCamera() { updateContinueButtonConstraint(forLabel: cameraMessage) continueButton.removeTarget(nil, action: nil, for: .allEvents) continueButton.addTarget(self, action: #selector(checkForCameraPermissions), for: .touchUpInside) animateToStep(animations: { self.continueButton.isEnabled = true self.microphoneMessage.alpha = 0 self.cameraMessage.alpha = 1 self.stepsImageView.image = UIImage(named: "permissions_step_3") self.stepIcon.image = UIImage(named: "permissions_step_camera_icon") self.stepTitle.text = String.permissionsGuideCameraTitle.localizedUppercase }) { UIAccessibility.post(notification: .layoutChanged, argument: self.cameraMessage) } } @objc private func checkForCameraPermissions() { UIView.animate(withDuration: permissionCheckDuration, animations: { self.continueButton.isEnabled = false }) { (_) in let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video) switch cameraAuthorizationStatus { case .authorized, .denied, .restricted: self.markStepDoneAndPerformNext() case .notDetermined: AVCaptureDevice.requestAccess(for: .video) { _ in DispatchQueue.main.sync { self.markStepDoneAndPerformNext() } } @unknown default: break } } } // MARK: Photo library // Ask for photo library permissions. private func stepPhotoLibrary() { updateContinueButtonConstraint(forLabel: photoLibraryMessage) continueButton.removeTarget(nil, action: nil, for: .allEvents) continueButton.addTarget(self, action: #selector(checkForPhotoLibraryPermissions), for: .touchUpInside) animateToStep(animations: { self.continueButton.isEnabled = true self.cameraMessage.alpha = 0 self.photoLibraryMessage.alpha = 1 self.stepsImageView.image = UIImage(named: "permissions_step_4") self.stepIcon.image = UIImage(named: "permissions_step_photos_icon") self.stepTitle.text = String.permissionsGuidePhotosTitle.localizedUppercase }) { UIAccessibility.post(notification: .layoutChanged, argument: self.photoLibraryMessage) } } @objc private func checkForPhotoLibraryPermissions() { UIView.animate(withDuration: permissionCheckDuration, animations: { self.continueButton.isEnabled = false }) { (_) in PHPhotoLibrary.requestAuthorization { _ in DispatchQueue.main.sync { self.markStepDoneAndPerformNext() } } } } // MARK: All steps complete // Thank the user and add a completion button which dismisses the guide. private func stepsDone() { animateToStep(animations: { self.stepHeader.isHidden = true self.continueButton.isHidden = true self.photoLibraryMessage.alpha = 0 self.finalMessage.alpha = 1 self.completeButton.isHidden = false self.stepsImageView.isHidden = true }) { UIAccessibility.post(notification: .layoutChanged, argument: self.finalMessage) } } // MARK: - Helpers private func updateContinueButtonConstraint(forLabel label: UILabel) { continueTopConstraint?.isActive = false continueTopConstraint = continueButton.topAnchor.constraint(equalTo: label.bottomAnchor, constant: Metrics.buttonSpacing) continueTopConstraint?.priority = .defaultHigh-1 continueTopConstraint?.isActive = true continueButton.layoutIfNeeded() } // MARK: - User actions @objc private func startGuideButtonPressed() { performNextStep() } @objc private func completeGuideButtonPressed() { delegate?.permissionsGuideDidComplete(self) } } // swiftlint:enable type_body_length
39.457143
124
0.719342
fce623f494976890cb1fbc573c2f26353f481d62
1,490
// // CurrencyCell.swift // Commun // // Created by Chung Tran on 1/20/20. // Copyright © 2020 Commun Limited. All rights reserved. // import Foundation protocol CurrencyCellDelegate: class {} class CurrencyCell: MyTableViewCell, ListItemCellType { // MARK: - Properties weak var delegate: CurrencyCellDelegate? var item: ResponseAPIGetCurrency? // MARK: - Subviews lazy var avatarImageView = MyAvatarImageView(size: 50) lazy var contentLabel = UILabel.with(textSize: 15, weight: .medium, numberOfLines: 2) // MARK: - Methods override func setUpViews() { super.setUpViews() contentView.addSubview(avatarImageView) avatarImageView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(inset: 16), excludingEdge: .trailing) contentView.addSubview(contentLabel) contentLabel.autoPinEdge(.leading, to: .trailing, of: avatarImageView, withOffset: 10) contentLabel.autoAlignAxis(toSuperviewAxis: .horizontal) contentLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 16) } func setUp(with item: ResponseAPIGetCurrency) { self.item = item avatarImageView.setAvatar(urlString: item.image) contentLabel.attributedText = NSMutableAttributedString() .text(item.name.uppercased(), size: 15, weight: .medium) .normal("\n") .text(item.fullName ?? "", size: 12, weight: .medium, color: .appGrayColor) } }
33.863636
109
0.678523
09417dc03f9565fd215ab2022b55d481d528c8c5
2,572
// // MenuViewController.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-24. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit class MenuViewController : UIViewController, Trackable { //MARK: - Public var didTapSecurity: (() -> Void)? var didTapSupport: (() -> Void)? var didTapSettings: (() -> Void)? var didTapLock: (() -> Void)? var didTapBuy: (() -> Void)? //MARK: - Private fileprivate let buttonHeight: CGFloat = 72.0 fileprivate let buttons: [MenuButton] = { let types: [MenuButtonType] = [.security, .support, .settings, .lock] return types.flatMap { return MenuButton(type: $0) } }() fileprivate let bottomPadding: CGFloat = 32.0 override func viewDidLoad() { var previousButton: UIView? buttons.forEach { button in button.addTarget(self, action: #selector(MenuViewController.didTapButton(button:)), for: .touchUpInside) view.addSubview(button) var topConstraint: NSLayoutConstraint? if let viewAbove = previousButton { topConstraint = button.constraint(toBottom: viewAbove, constant: 0.0) } else { topConstraint = button.constraint(.top, toView: view, constant: 0.0) } button.constrain([ topConstraint, button.constraint(.leading, toView: view, constant: 0.0), button.constraint(.trailing, toView: view, constant: 0.0), button.constraint(.height, constant: buttonHeight) ]) previousButton = button } previousButton?.constrain([ previousButton?.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -C.padding[2]) ]) view.backgroundColor = .grayBackground if BRAPIClient.featureEnabled(.buyBitcoin) { saveEvent("menu.buyBitcoinIsVisible") } } @objc private func didTapButton(button: MenuButton) { switch button.type { case .security: didTapSecurity?() case .support: didTapSupport?() case .settings: didTapSettings?() case .lock: didTapLock?() case .buy: saveEvent("menu.didTapBuyBitcoin") didTapBuy?() } } } extension MenuViewController : ModalDisplayable { var faqArticleId: String? { return nil } var modalTitle: String { return S.MenuViewController.modalTitle } }
29.906977
116
0.594868
26f4b04d8d967ba2520088805840798920725b73
813
// // WaypointType.swift // SkateBudapest // // Created by Horváth Balázs on 2020. 04. 13.. // Copyright © 2020. Horváth Balázs. All rights reserved. // import UIKit enum WaypointType: String, CaseIterable, Codable { case skatepark, skateshop, streetspot var pinIcon: UIImage { switch self { case .skatepark: return Theme.Icon.skateparkPin case .skateshop: return Theme.Icon.skateshopPin case .streetspot: return Theme.Icon.streetSpotPin } } var backgroundColor: UIColor { switch self { case .skatepark: return Theme.Color.skatepark case .streetspot: return Theme.Color.streetSpot case .skateshop: return Theme.Color.skateshop } } }
22.583333
58
0.601476
5d8b7a1fa10c01eefbd44c72e6d3a08dccbaa713
1,414
//---------------------------------------------------- // // Generated by www.easywsdl.com // Version: 5.7.0.0 // // Created by Quasar Development // //--------------------------------------------------- import Foundation /** * specDomain: S10813 (C-0-T10774-A10775-S10801-S10810-S10811-S10812-S10813-cpt) */ public enum EPA_FdV_AUTHZ_DataTypeHistoryOfAddress:Int,CustomStringConvertible { case HIST_x003C_AD_x003E_ static func createWithXml(node:DDXMLNode) -> EPA_FdV_AUTHZ_DataTypeHistoryOfAddress? { return createWithString(value: node.stringValue!) } static func createWithString(value:String) -> EPA_FdV_AUTHZ_DataTypeHistoryOfAddress? { var i = 0 while let item = EPA_FdV_AUTHZ_DataTypeHistoryOfAddress(rawValue: i) { if String(describing: item) == value { return item } i += 1 } return nil } public var stringValue : String { return description } public var description : String { switch self { case .HIST_x003C_AD_x003E_: return "HIST<AD>" } } public func getValue() -> Int { return rawValue } func serialize(__parent:DDXMLNode) { __parent.stringValue = stringValue } }
21.424242
90
0.531825
d92a9b02ff23d4706001cf97fd0631aab93dded4
1,674
// // AppDelegate.swift // StatefulCollectionDemo // // Created by Yousef Hamza on 10/4/20. // Copyright © 2020 YousefHamza. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UIViewController.rootViewController window?.makeKeyAndVisible() return true } // MARK: UISceneSession Lifecycle @available(iOS 13.0, *) func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } @available(iOS 13.0, *) func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
38.930233
179
0.738949
dd03b2b850869d6d591143c6b2e65a7ccd2502b5
4,498
// // File.swift // // // Created by Vitali Kurlovich on 4/14/20. // import Foundation // CandlesDecoder public struct TicksCollection: TicksSequence { public let range: Range<Date> internal var ticks: [DukascopyTick] public var bounds: Range<Date> { guard let first = ticks.first, let last = ticks.last else { return range.lowerBound ..< range.lowerBound } let date = range.lowerBound return tick(date: date, first).date ..< tick(date: date, last).date } } extension TicksCollection { mutating func append(_ tick: DukascopyTick) { ticks.append(tick) } mutating func append<S: Sequence>(contentsOf: S) where S.Element == DukascopyTick { ticks.append(contentsOf: contentsOf) } mutating func append(_ collection: TicksCollection) { let delta = collection.range.lowerBound.timeIntervalSince(range.lowerBound) let increment = Int32(round(delta * 1000)) if increment == 0 { append(contentsOf: collection.ticks) } else { let ticks = collection.ticks.lazy.map { (tick) -> DukascopyTick in .init(time: tick.time + increment, askp: tick.askp, bidp: tick.bidp, askv: tick.askv, bidv: tick.bidv) } append(contentsOf: ticks) } } mutating func append(_ collection: SliceTicksCollection) { let delta = collection.range.lowerBound.timeIntervalSince(range.lowerBound) let increment = Int32(round(delta * 1000)) if increment == 0 { append(contentsOf: collection.ticks) } else { let ticks = collection.ticks.lazy.map { (tick) -> DukascopyTick in .init(time: tick.time + increment, askp: tick.askp, bidp: tick.bidp, askv: tick.askv, bidv: tick.bidv) } append(contentsOf: ticks) } } } extension TicksCollection: Equatable {} extension TicksCollection: BidirectionalCollection { public typealias Element = Tick public typealias Index = Int public typealias SubSequence = SliceTicksCollection public subscript(position: Int) -> Self.Element { let block = ticks[position] let date = range.lowerBound return tick(date: date, block) } public subscript(bounds: Range<Self.Index>) -> Self.SubSequence { // let date = range.lowerBound let slice = ticks[bounds] return SubSequence(range: range, ticks: slice) } public func index(before i: Int) -> Int { ticks.index(before: i) } public func index(after i: Int) -> Int { ticks.index(after: i) } public var startIndex: Int { ticks.startIndex } public var endIndex: Int { ticks.endIndex } } public struct SliceTicksCollection: TicksSequence { public let range: Range<Date> internal let ticks: ArraySlice<DukascopyTick> public var bounds: Range<Date> { guard let first = ticks.first, let last = ticks.last else { return range.lowerBound ..< range.lowerBound } return tick(date: range.lowerBound, first).date ..< tick(date: range.lowerBound, last).date } } extension SliceTicksCollection: Equatable {} extension SliceTicksCollection: BidirectionalCollection { public typealias Element = Tick public typealias Index = Int public typealias SubSequence = SliceTicksCollection public subscript(position: Int) -> Self.Element { let item = ticks[position] return tick(date: range.lowerBound, item) } public subscript(bounds: Range<Self.Index>) -> Self.SubSequence { let slice = ticks[bounds] return SubSequence(range: range, ticks: slice) } public func index(before i: Int) -> Int { ticks.index(before: i) } public func index(after i: Int) -> Int { ticks.index(after: i) } public var startIndex: Int { ticks.startIndex } public var endIndex: Int { ticks.endIndex } } private func tick(date: Date, _ block: DukascopyTick) -> Tick { let deltaTime = TimeInterval(block.time) / 1000 let date = date.addingTimeInterval(deltaTime) let price = Price(ask: block.askp, bid: block.bidp) let volume = Volume(ask: block.askv, bid: block.bidv) return Tick(date: date, price: price, volume: volume) }
25.412429
99
0.619831
18f078c29730ec5523224d9bcff73dddd91e4216
75
// This is needed because of https://github.com/opencv/opencv/issues/19645
37.5
74
0.773333
ef3077d8ecc2424acf6327141dd5229da8d42bde
1,822
public typealias ErrorMessage = String public protocol InputValidatorType { func validate(arguments: [String]) -> Validation<ErrorMessage, ValidInput> } enum ValidationErrorMessage { static let generic: ErrorMessage = """ Expected arguments: - RGB base image absolute path - RGB hole mask image absolute path (hole represented by black pixels) - default weighting function 'z' parameter - default weighting function 'epsilon' parameter - pixel connectivity ("4" or "8") - output image absolute path 🖼 Supported image formats: bmp, gif, jpeg, jpeg2000, png, tiff ℹ️ E.g.: $> ./HoleFilling \\ "/Users/<username>/Documents/base.png" \\ "/Users/<username>/Documents/holeMask.jpg" \\ 2 \\ 0.0001 \\ 4 \\ "/Users/<username>/Downloads/holeFilled.tiff" """ static let emptyAbsolutePath: ErrorMessage = "RGB base image absolute path can't be empty\n\n\(generic)" static let invalidZ: ErrorMessage = "Z must be a floating point number\n\n\(generic)" static let invalidEpsilon: ErrorMessage = "epsilon must be a floating point number > 0\n\n\(generic)" static let invalidPixelConnectivity: ErrorMessage = "Pixel connectivity must be '4' or '8'\n\n\(generic)" } public func buildInputValidatorType() -> InputValidatorType { return InputValidator( genericErrorMessage: ValidationErrorMessage.generic, emptyAbsolutePathMessage: ValidationErrorMessage.emptyAbsolutePath, invalidZMessage: ValidationErrorMessage.invalidZ, invalidEpsilonMessage: ValidationErrorMessage.invalidEpsilon, invalidPixelConnectivityMessage: ValidationErrorMessage.invalidPixelConnectivity ) }
38.765957
88
0.672338
468d83873b0cd7930ee049c4dcd51229af53bc61
146
import Foundation protocol ___VARIABLE_MODULENAME___Interactor { var presenter: ___VARIABLE_MODULENAME___Presenter? { get set } }
16.222222
66
0.760274
ac683df0cd21613a4837126af69a18b2b4e374a0
4,052
/// Copyright (c) 2020 Razeware LLC /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// 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 SwiftUI struct WelcomeView: View { @StateObject var flightInfo = FlightData() @State var showNextFlight = false @StateObject var appEnvironment = AppEnvironment() var body: some View { NavigationView { ZStack(alignment: .topLeading) { Image("welcome-background") .resizable() .aspectRatio(contentMode: .fill) .frame(height: 250) if let id = appEnvironment.lastFlightId, let lastFlight = flightInfo.getFlightById(id) { NavigationLink( destination: FlightDetails(flight: lastFlight), isActive: $showNextFlight ) { } } ScrollView { LazyVGrid( columns: [ GridItem(.fixed(160)), GridItem(.fixed(160)) ], spacing: 15 ) { NavigationLink( destination: FlightStatusBoard( flights: flightInfo.getDaysFlights(Date())) ) { FlightStatusButton() } NavigationLink( destination: SearchFlights( flightData: flightInfo.flights ) ) { SearchFlightsButton() } NavigationLink( destination: AwardsView() ) { AwardsButton() } if let id = appEnvironment.lastFlightId, let lastFlight = flightInfo.getFlightById(id) { // swiftlint:disable multiple_closures_with_trailing_closure Button( action: { showNextFlight = true } ) { LastViewedButton(name: lastFlight.flightName) } } Spacer() }.font(.title) .foregroundColor(.white) .padding() } }.navigationTitle("Mountain Airport") // End Navigation View }.navigationViewStyle(StackNavigationViewStyle()) .environmentObject(appEnvironment) } } struct WelcomeView_Previews: PreviewProvider { static var previews: some View { WelcomeView() } }
37.174312
83
0.633021
8a0da3a396649f77bd4d970e51ccae53bb5d4703
363
// // 🦠 Corona-Warn-App // import Foundation import HealthCertificateToolkit struct DCCWalletCertificate: Codable { // MARK: - Internal struct DCCWalletCertificateCose: Codable { let kid: String } let barcodeData: String let cose: DCCWalletCertificateCose let cwt: CBORWebTokenHeader let hcert: DigitalCovidCertificate let validityState: String }
16.5
43
0.774105
09ca94e66c1e6b9ecaa65a1c3dd88ef392093b99
4,881
// // ContentDetailViewController.swift // Anywhere Reader // // Created by Conner on 11/6/18. // Copyright © 2018 Samantha Gatt. All rights reserved. // import UIKit import Kingfisher class ContentDetailViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() updateViews() NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: UserDefaults.didChangeNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateTheme() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { [unowned self] _ in self.gradientLayer.frame = self.imageView.bounds }) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() gradientLayer.frame = imageView.bounds } // MARK: - Private properties private let themeHelper = ThemeHelper.shared private let gradientLayer = CAGradientLayer() // MARK: - Public properties public var article: Article? { didSet { updateViews() } } // MARK: - IBOutlets @IBOutlet weak var contentView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentBodyLabel: UILabel! @IBOutlet var imageView: UIImageView! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var tagLabelOne: UILabel! @IBOutlet weak var tagLabelTwo: UILabel! @IBOutlet weak var tagLabelThree: UILabel! @IBOutlet weak var tagLabelFour: UILabel! @IBOutlet weak var tagLabelFive: UILabel! // MARK: - Actions @IBAction func presentPreferences(_ sender: Any) { let storyboard = UIStoryboard(name: "Preferences", bundle: nil) guard let preferencesVC = storyboard.instantiateInitialViewController() else { return } preferencesVC.providesPresentationContextTransitionStyle = true preferencesVC.definesPresentationContext = true preferencesVC.modalPresentationStyle = .overCurrentContext preferencesVC.modalTransitionStyle = .crossDissolve self.present(preferencesVC, animated: true, completion: nil) } // MARK: - Private private func updateViews() { guard let article = article, let coverImage = article.coverImage else { return } titleLabel.text = article.title contentBodyLabel.text = article.text authorLabel.text = article.author let cache = ImageCache.default cache.retrieveImageInDiskCache(forKey: coverImage + "original") { (result) in switch result { case .success(let image): DispatchQueue.main.async { self.imageView.image = image } case .failure(let error): print(error) } } dateLabel.text = "Saved on \(DateHelper.shared.ISODateToNormalDate(date: article.dateSaved ?? ""))" } @objc private func updateTheme() { let backgroundColor = themeHelper.getBackgroundColor() view.backgroundColor = backgroundColor contentView.backgroundColor = backgroundColor navigationController?.navigationBar.barTintColor = backgroundColor navigationController?.navigationBar.tintColor = themeHelper.getTextColor() [contentBodyLabel, titleLabel, authorLabel, dateLabel] .forEach { $0.textColor = themeHelper.getTextColor() } [contentBodyLabel, authorLabel, dateLabel] .forEach { $0.font = themeHelper.getBodyFont() } let titleFont = themeHelper.getTitleFont() titleLabel.font = titleFont // Gradient Layer for top image gradientLayer.frame = imageView.bounds // Colors for gradient gradientLayer.colors = [ UIColor.white.withAlphaComponent(1).cgColor, UIColor.white.withAlphaComponent(0).cgColor] // Direction of gradient gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.70) gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0) imageView.layer.mask = gradientLayer } override var preferredStatusBarStyle : UIStatusBarStyle { if themeHelper.isNightMode || themeHelper.getLastStoredTheme() == .lightGray { return .lightContent } else { return .default } } }
31.694805
141
0.653759
e05626b4d0bc148f96a5778ff626249f87c85129
454
// // GoogleAuthenticationServer+Objc.swift // TogglDesktop // // Created by Nghia Tran on 9/17/19. // Copyright © 2019 Alari. All rights reserved. // import Foundation @objc class GoogleAuthenticationServerHelper: NSObject { @objc class func authorize(_ complete: @escaping (String?, Error?) -> Void) { GoogleAuthenticationServer.shared.authenticate { (user, error) in complete(user?.accessToken, error) } } }
23.894737
81
0.680617
e87dab45eb544c4fbaf77cd2c95b9a2b568aec7b
2,246
// // NSPreferencePanelWindowController.swift // devMod // // Created by Paolo Tagliani on 10/25/14. // Copyright (c) 2014 Paolo Tagliani. All rights reserved. // import Cocoa import Quartz class NSPreferencePanelWindowController: NSWindowController { @IBOutlet weak var launchAtStartupButton: NSButton! @IBOutlet weak var darkModeDatePicker: NSDatePicker! @IBOutlet weak var lightModeDatePicker: NSDatePicker! override func windowDidLoad() { super.windowDidLoad() self.window?.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark) self.window?.titleVisibility = NSWindow.TitleVisibility.hidden; //Set login item state launchAtStartupButton.state = PALoginItemUtility.isCurrentApplicatonInLoginItems() ? NSControl.StateValue.on : NSControl.StateValue.off //Set darkDate if let darkDate = UserDefaults.standard.object(forKey: "DarkTime") as? NSDate { darkModeDatePicker.dateValue = darkDate as Date } //Set light date if let lightDate = UserDefaults.standard.object(forKey: "LightTime") as? NSDate{ lightModeDatePicker.dateValue = lightDate as Date } } @IBAction func launchLoginPressed(sender: NSButton) { if sender.state == NSControl.StateValue.on{ PALoginItemUtility.addCurrentApplicatonToLoginItems() } else{ PALoginItemUtility.removeCurrentApplicatonToLoginItems() } } @IBAction func darkTimeChange(sender: NSDatePicker) { let appDelegate = NSApplication.shared.delegate as! AppDelegate appDelegate.darkTime = sender.dateValue as NSDate let userDefaults = UserDefaults.standard userDefaults.setValue(sender.dateValue, forKey: "DarkTime") userDefaults.synchronize() } @IBAction func lightTimeChange(sender: NSDatePicker) { let appDelegate = NSApplication.shared.delegate as! AppDelegate appDelegate.lightTime = sender.dateValue as NSDate let userDefaults = UserDefaults.standard UserDefaults.standard.setValue(sender.dateValue, forKey: "LightTime") userDefaults.synchronize() } }
34.553846
143
0.689671
f9ed04cbd31afab312e6643ae91ce3c79118d582
2,106
import MockoloFramework let overload2 = """ /// \(String.mockAnnotation) public protocol Foo: Bar { func tell(status: Int, msg: String) -> Double } """ let overloadParent2 = """ public class BarMock: Bar { public init() { } public var tellCallCount = 0 public var tellHandler: (([String: String], ClientProtocol) -> (Observable<EncryptedData>))? public func tell(data: [String: String], for client: ClientProtocol) -> Observable<EncryptedData> { tellCallCount += 1 if let tellHandler = tellHandler { return tellHandler(data, client) } return Observable.empty() } public var tellKeyCallCount = 0 public var tellKeyHandler: ((Double) -> (Int))? public func tell(key: Double) -> Int { tellKeyCallCount += 1 if let tellKeyHandler = tellKeyHandler { return tellKeyHandler(key) } return 0 } } """ let overloadMock2 = """ public class FooMock: Foo { public init() { } public var tellStatusCallCount = 0 public var tellStatusHandler: ((Int, String) -> (Double))? public func tell(status: Int, msg: String) -> Double { tellStatusCallCount += 1 if let tellStatusHandler = tellStatusHandler { return tellStatusHandler(status, msg) } return 0.0 } public var tellCallCount = 0 public var tellHandler: (([String: String], ClientProtocol) -> (Observable<EncryptedData>))? public func tell(data: [String: String], for client: ClientProtocol) -> Observable<EncryptedData> { tellCallCount += 1 if let tellHandler = tellHandler { return tellHandler(data, client) } return Observable.empty() } public var tellKeyCallCount = 0 public var tellKeyHandler: ((Double) -> (Int))? public func tell(key: Double) -> Int { tellKeyCallCount += 1 if let tellKeyHandler = tellKeyHandler { return tellKeyHandler(key) } return 0 } } """
24.488372
103
0.594017
efa250245359eedb7a8b390ef1f06db4a2d7870b
730
// // CommonMethods.swift // EcbCurrencyConverter // // Created by Vassilis Voutsas on 12/07/2018. // Copyright © 2018 Vassilis Voutsas. All rights reserved. // import UIKit func showLoader(view: UIView) -> UIActivityIndicatorView { let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40)) spinner.backgroundColor = UIColor.black.withAlphaComponent(0.4) spinner.layer.cornerRadius = 3.0 spinner.clipsToBounds = true spinner.hidesWhenStopped = true spinner.style = UIActivityIndicatorView.Style.white spinner.center = view.center view.addSubview(spinner) spinner.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() return spinner }
30.416667
90
0.741096
8f266c2b8cfd2d239c62b77ac8622c399f12fbef
437
// // RecordCollectionViewCell.swift // FirstPhaseByRxSwift // // Created by Keisuke Horiguchi on 2021/07/22. // import Foundation import UIKit class RecordCollectionViewCell: UICollectionViewCell { @IBOutlet weak var recordImg: UIImageView! @IBOutlet weak var recordTitle: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
17.48
54
0.654462
e2190438801b76068f47419d3a8d94e9c1b7ba1c
1,618
// // InfoView.swift // Yep // // Created by nixzhu on 15/9/23. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import Ruler class InfoView: UIView { var info: String? private var infoLabel: UILabel? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) makeUI() } convenience init(_ info: String? = nil) { self.init(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 240)) self.info = info } func makeUI() { let label = UILabel() label.numberOfLines = 0 label.textAlignment = .Center label.textColor = UIColor.lightGrayColor() self.infoLabel = label label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) let views = [ "label": label ] let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-margin-[label]-margin-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: ["margin": Ruler.iPhoneHorizontal(20, 40, 40).value], views: views) let constraintsV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) NSLayoutConstraint.activateConstraints(constraintsH) NSLayoutConstraint.activateConstraints(constraintsV) } override func didMoveToSuperview() { super.didMoveToSuperview() infoLabel?.text = info } }
24.515152
226
0.648949
61c7734de378025be5d0b763c74eb6892279f082
383
// // RequestRetrier.swift // Networking // // Created by new user on 12.10.2020. // import Foundation public protocol RequestRetrier: AnyObject { func canHandleError<T: Request>(_ error: ErrorResponse<T.ErrorType>, for request: T) -> Bool func handleError<T: Request>(_ error: ErrorResponse<T.ErrorType>, for request: T, completion: @escaping (T?) -> Void) }
23.9375
121
0.689295
feb841d917995c483a8065b3665a4c36ba0684f7
2,632
// // ContainerNavigationController.swift // edX // // Created by Akiva Leffert on 6/29/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own status bar styling instead of leaving it up to its container, which is the default /// behavior. /// It is deliberately empty and just exists so controllers can declare they want this behavior. protocol StatusBarOverriding { } /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own interface orientation instead of using the defaults. /// It is deliberately empty and just exists so controllers can declare they want this behavior. @objc protocol InterfaceOrientationOverriding { } /// A simple UINavigationController subclass that can forward status bar /// queries to its children should they opt into that by implementing the ContainedNavigationController protocol class ForwardingNavigationController: UINavigationController { override var childViewControllerForStatusBarStyle: UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childViewControllerForStatusBarStyle } } override var childViewControllerForStatusBarHidden: UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childViewControllerForStatusBarHidden } } override var shouldAutorotate: Bool { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.shouldAutorotate } else { return super.shouldAutorotate } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.supportedInterfaceOrientations } else { return .portrait } } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.preferredInterfaceOrientationForPresentation } else { return .portrait } } }
36.054795
112
0.710866
cc19967c725f6b3e216bf08c23f668785bdcb393
180,121
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 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 */ import XCTest import TSCBasic import PackageLoading import PackageModel import PackageGraph import SourceControl import TSCUtility import SPMBuildCore import Workspace import SPMTestSupport final class WorkspaceTests: XCTestCase { func testBasics() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), TestTarget(name: "Bar", dependencies: ["Baz"]), TestTarget(name: "BarTests", dependencies: ["Bar"], type: .test), ], products: [ TestProduct(name: "Foo", targets: ["Foo", "Bar"]), ], dependencies: [ TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0", "1.5.0"] ), TestPackage( name: "Quix", targets: [ TestTarget(name: "Quix"), ], products: [ TestProduct(name: "Quix", targets: ["Quix"]), ], versions: ["1.0.0", "1.2.0"] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Quix", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Quix"])), .init(name: "Baz", requirement: .exact("1.0.0"), products: .specific(["Baz"])), ] workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Baz", "Foo", "Quix") result.check(targets: "Bar", "Baz", "Foo", "Quix") result.check(testModules: "BarTests") result.checkTarget("Foo") { result in result.check(dependencies: "Bar") } result.checkTarget("Bar") { result in result.check(dependencies: "Baz") } result.checkTarget("BarTests") { result in result.check(dependencies: "Bar") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "baz", at: .checkout(.version("1.0.0"))) result.check(dependency: "quix", at: .checkout(.version("1.2.0"))) } // Check the load-package callbacks. XCTAssertMatch(workspace.delegate.events, [ .equal("will load manifest for root package: /tmp/ws/roots/Foo"), .equal("did load manifest for root package: /tmp/ws/roots/Foo"), ]) XCTAssertMatch(workspace.delegate.events, [ .equal("will load manifest for remote package: /tmp/ws/pkgs/Quix"), .equal("did load manifest for remote package: /tmp/ws/pkgs/Quix"), .equal("will load manifest for remote package: /tmp/ws/pkgs/Baz"), .equal("did load manifest for remote package: /tmp/ws/pkgs/Baz") ]) // Close and reopen workspace. workspace.closeWorkspace() workspace.checkManagedDependencies() { result in result.check(dependency: "baz", at: .checkout(.version("1.0.0"))) result.check(dependency: "quix", at: .checkout(.version("1.2.0"))) } let stateFile = workspace.createWorkspace().state.path // Remove state file and check we can get the state back automatically. try fs.removeFileTree(stateFile) workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { _, _ in } XCTAssertTrue(fs.exists(stateFile)) // Remove state file and check we get back to a clean state. try fs.removeFileTree(workspace.createWorkspace().state.path) workspace.closeWorkspace() workspace.checkManagedDependencies() { result in result.checkEmpty() } } func testInterpreterFlags() throws { let fs = localFileSystem mktmpdir { path in let foo = path.appending(component: "foo") func createWorkspace(withManifest manifest: (OutputByteStream) -> ()) throws -> Workspace { try fs.writeFileContents(foo.appending(component: "Package.swift")) { manifest($0) } let manifestLoader = ManifestLoader(manifestResources: Resources.default) let sandbox = path.appending(component: "ws") return Workspace( dataPath: sandbox.appending(component: ".build"), editablesPath: sandbox.appending(component: "edits"), pinsFile: sandbox.appending(component: "Package.resolved"), manifestLoader: manifestLoader, delegate: TestWorkspaceDelegate() ) } do { let ws = try createWorkspace { $0 <<< """ // swift-tools-version:4.0 import PackageDescription let package = Package( name: "foo" ) """ } XCTAssertMatch((ws.interpreterFlags(for: foo)), [.equal("-swift-version"), .equal("4")]) } do { let ws = try createWorkspace { $0 <<< """ // swift-tools-version:3.1 import PackageDescription let package = Package( name: "foo" ) """ } XCTAssertEqual(ws.interpreterFlags(for: foo), []) } } } func testMultipleRootPackages() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Baz"]), ], products: [], dependencies: [ TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", dependencies: ["Baz"]), ], products: [], dependencies: [ TestDependency(name: "Baz", requirement: .exact("1.0.1")), ] ), ], packages: [ TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0", "1.0.1", "1.0.3", "1.0.5", "1.0.8"] ), ] ) workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Bar", "Foo") result.check(packages: "Bar", "Baz", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Baz") } result.checkTarget("Bar") { result in result.check(dependencies: "Baz") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "baz", at: .checkout(.version("1.0.1"))) } } func testRootPackagesOverride() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Baz"]), ], products: [], dependencies: [ TestDependency(name: nil, path: "bazzz", requirement: .upToNextMajor(from: "1.0.0")), ], toolsVersion: .v5 ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [] ), TestPackage( name: "Baz", path: "Overridden/bazzz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ] ), ], packages: [ TestPackage( name: "Baz", path: "bazzz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0", "1.0.1", "1.0.3", "1.0.5", "1.0.8"] ), ] ) workspace.checkPackageGraph(roots: ["Foo", "Bar", "Overridden/bazzz"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Bar", "Foo", "Baz") result.check(packages: "Bar", "Baz", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Baz") } } XCTAssertNoDiagnostics(diagnostics) } } func testDependencyRefsAreIteratedInStableOrder() throws { // This graph has two references to Bar, one with .git suffix and one without. // The test ensures that we use the URL which appears first (i.e. the one with .git suffix). let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0"] ), ] ) let dependencies: [PackageGraphRootInput.PackageDependency] = [ .init( url: workspace.packagesDir.appending(component: "Foo").pathString, requirement: .upToNextMajor(from: "1.0.0"), productFilter: .specific(["Foo"]), location: "" ), .init( url: workspace.packagesDir.appending(component: "Bar").pathString + ".git", requirement: .upToNextMajor(from: "1.0.0"), productFilter: .specific(["Bar"]), location: "" ), ] // Add entry for the Bar.git package. do { let barKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar", version: "1.0.0") let barGitKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar.git", version: "1.0.0") let manifest = workspace.manifestLoader.manifests[barKey]! workspace.manifestLoader.manifests[barGitKey] = manifest.with(url: "/tmp/ws/pkgs/Bar.git") } workspace.checkPackageGraph(dependencies: dependencies) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "Bar", "Foo") result.check(targets: "Bar", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Bar") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", url: "/tmp/ws/pkgs/Bar.git") } } func testDuplicateRootPackages() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: []), ], products: [], dependencies: [] ), TestPackage( name: "Foo", path: "Nested/Foo", targets: [ TestTarget(name: "Foo", dependencies: []), ], products: [], dependencies: [] ), ], packages: [] ) workspace.checkPackageGraph(roots: ["Foo", "Nested/Foo"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("found multiple top-level packages named 'Foo'"), behavior: .error) } } } /// Test that the remote repository is not resolved when a root package with same name is already present. func testRootAsDependency1() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["BazAB"]), ], products: [], dependencies: [ TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ], toolsVersion: .v5 ), TestPackage( name: "Baz", targets: [ TestTarget(name: "BazA"), TestTarget(name: "BazB"), ], products: [ TestProduct(name: "BazAB", targets: ["BazA", "BazB"]), ] ), ], packages: [ TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0"] ), ] ) workspace.checkPackageGraph(roots: ["Foo", "Baz"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Baz", "Foo") result.check(packages: "Baz", "Foo") result.check(targets: "BazA", "BazB", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "BazAB") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(notPresent: "baz") } XCTAssertNoMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")]) XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")]) } /// Test that a root package can be used as a dependency when the remote version was resolved previously. func testRootAsDependency2() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Baz"]), ], products: [], dependencies: [ TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "BazA"), TestTarget(name: "BazB"), ], products: [ TestProduct(name: "Baz", targets: ["BazA", "BazB"]), ] ), ], packages: [ TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0"] ), ] ) // Load only Foo right now so Baz is loaded from remote. workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Baz", "Foo") result.check(targets: "Baz", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Baz") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "baz", at: .checkout(.version("1.0.0"))) } XCTAssertMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")]) XCTAssertMatch(workspace.delegate.events, [.equal("will resolve dependencies")]) // Now load with Baz as a root package. workspace.delegate.events = [] workspace.checkPackageGraph(roots: ["Foo", "Baz"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Baz", "Foo") result.check(packages: "Baz", "Foo") result.check(targets: "BazA", "BazB", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Baz") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(notPresent: "baz") } XCTAssertNoMatch(workspace.delegate.events, [.equal("fetching repo: /tmp/ws/pkgs/Baz")]) XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")]) XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Baz")]) } func testGraphRootDependencies() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0"] ), ] ) let dependencies: [PackageGraphRootInput.PackageDependency] = [ .init( url: workspace.packagesDir.appending(component: "Bar").pathString, requirement: .upToNextMajor(from: "1.0.0"), productFilter: .specific(["Bar"]), location: "" ), .init( url: "file://\(workspace.packagesDir.appending(component: "Foo").pathString)/", requirement: .upToNextMajor(from: "1.0.0"), productFilter: .specific(["Foo"]), location: "" ), ] workspace.checkPackageGraph(dependencies: dependencies) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "Bar", "Foo") result.check(targets: "Bar", "Foo") result.checkTarget("Foo") { result in result.check(dependencies: "Bar") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } } func testCanResolveWithIncompatiblePins() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [], packages: [ TestPackage( name: "A", targets: [ TestTarget(name: "A", dependencies: ["AA"]), ], products: [ TestProduct(name: "A", targets: ["A"]), ], dependencies: [ TestDependency(name: "AA", requirement: .exact("1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "A", targets: [ TestTarget(name: "A", dependencies: ["AA"]), ], products: [ TestProduct(name: "A", targets: ["A"]), ], dependencies: [ TestDependency(name: "AA", requirement: .exact("2.0.0")), ], versions: ["1.0.1"] ), TestPackage( name: "AA", targets: [ TestTarget(name: "AA"), ], products: [ TestProduct(name: "AA", targets: ["AA"]), ], versions: ["1.0.0", "2.0.0"] ), ] ) // Resolve when A = 1.0.0. do { let deps: [TestWorkspace.PackageDependency] = [ .init(name: "A", requirement: .exact("1.0.0"), products: .specific(["A"])) ] workspace.checkPackageGraph(deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "A", "AA") result.check(targets: "A", "AA") result.checkTarget("A") { result in result.check(dependencies: "AA") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "a", at: .checkout(.version("1.0.0"))) result.check(dependency: "aa", at: .checkout(.version("1.0.0"))) } workspace.checkResolved() { result in result.check(dependency: "a", at: .checkout(.version("1.0.0"))) result.check(dependency: "aa", at: .checkout(.version("1.0.0"))) } } // Resolve when A = 1.0.1. do { let deps: [TestWorkspace.PackageDependency] = [ .init(name: "A", requirement: .exact("1.0.1"), products: .specific(["A"])) ] workspace.checkPackageGraph(deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.checkTarget("A") { result in result.check(dependencies: "AA") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "a", at: .checkout(.version("1.0.1"))) result.check(dependency: "aa", at: .checkout(.version("2.0.0"))) } workspace.checkResolved() { result in result.check(dependency: "a", at: .checkout(.version("1.0.1"))) result.check(dependency: "aa", at: .checkout(.version("2.0.0"))) } XCTAssertMatch(workspace.delegate.events, [.equal("updating repo: /tmp/ws/pkgs/A")]) XCTAssertMatch(workspace.delegate.events, [.equal("updating repo: /tmp/ws/pkgs/AA")]) XCTAssertEqual(workspace.delegate.events.filter({ $0.hasPrefix("updating repo") }).count, 2) } } func testResolverCanHaveError() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [], packages: [ TestPackage( name: "A", targets: [ TestTarget(name: "A", dependencies: ["AA"]), ], products: [ TestProduct(name: "A", targets: ["A"]) ], dependencies: [ TestDependency(name: "AA", requirement: .exact("1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "B", targets: [ TestTarget(name: "B", dependencies: ["AA"]), ], products: [ TestProduct(name: "B", targets: ["B"]) ], dependencies: [ TestDependency(name: "AA", requirement: .exact("2.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "AA", targets: [ TestTarget(name: "AA"), ], products: [ TestProduct(name: "AA", targets: ["AA"]), ], versions: ["1.0.0", "2.0.0"] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "A", requirement: .exact("1.0.0"), products: .specific(["A"])), .init(name: "B", requirement: .exact("1.0.0"), products: .specific(["B"])), ] workspace.checkPackageGraph(deps: deps) { (_, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("version solving failed"), behavior: .error) } } // There should be no extra fetches. XCTAssertNoMatch(workspace.delegate.events, [.contains("updating repo")]) } func testPrecomputeResolution_empty() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let v2 = CheckoutState(revision: Revision(identifier: "hello"), version: "2.0.0") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [] ), ], packages: [] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: v2], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5) .editedDependency(subpath: bPath, unmanagedPath: nil) ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result.isRequired, false) } } func testPrecomputeResolution_newPackages() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let v1 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.0") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: v1Requirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: ["1.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: ["1.0.0"] ), ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1) ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .newPackages(packages: [cRef]))) } } func testPrecomputeResolution_requirementChange_versionToBranch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let cPath = RelativePath("C") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let branchRequirement: TestDependency.Requirement = .branch("master") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: branchRequirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: v1_5], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5), ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .packageRequirementChange( package: cRef, state: .checkout(v1_5), requirement: .revision("master") ))) } } func testPrecomputeResolution_requirementChange_versionToRevision() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let cPath = RelativePath("C") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let testWorkspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "C", requirement: .revision("hello")), ] ), ], packages: [ TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let cRepo = RepositorySpecifier(url: testWorkspace.urlForPackage(withName: "C")) let cRef = PackageReference(identity: "c", path: cRepo.url) try testWorkspace.set( pins: [cRef: v1_5], managedDependencies: [ ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5), ] ) try testWorkspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .packageRequirementChange( package: cRef, state: .checkout(v1_5), requirement: .revision("hello") ))) } } func testPrecomputeResolution_requirementChange_localToBranch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let masterRequirement: TestDependency.Requirement = .branch("master") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: masterRequirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency.local(packageRef: cRef) ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .packageRequirementChange( package: cRef, state: .local, requirement: .revision("master") ))) } } func testPrecomputeResolution_requirementChange_versionToLocal() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let cPath = RelativePath("C") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let localRequirement: TestDependency.Requirement = .localPackage let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: localRequirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: v1_5], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5), ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .packageRequirementChange( package: cRef, state: .checkout(v1_5), requirement: .unversioned ))) } } func testPrecomputeResolution_requirementChange_branchToLocal() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let cPath = RelativePath("C") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let localRequirement: TestDependency.Requirement = .localPackage let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let master = CheckoutState(revision: Revision(identifier: "master"), branch: "master") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: localRequirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: master], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: master), ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .packageRequirementChange( package: cRef, state: .checkout(master), requirement: .unversioned ))) } } func testPrecomputeResolution_other() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let cPath = RelativePath("C") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let v2Requirement: TestDependency.Requirement = .range("2.0.0" ..< "3.0.0") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: v2Requirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: v1_5], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v1_5), ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result, .required(reason: .other)) } } func testPrecomputeResolution_notRequired() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let bPath = RelativePath("B") let cPath = RelativePath("C") let v1Requirement: TestDependency.Requirement = .range("1.0.0" ..< "2.0.0") let v2Requirement: TestDependency.Requirement = .range("2.0.0" ..< "3.0.0") let v1_5 = CheckoutState(revision: Revision(identifier: "hello"), version: "1.0.5") let v2 = CheckoutState(revision: Revision(identifier: "hello"), version: "2.0.0") let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "A", targets: [TestTarget(name: "A")], products: [], dependencies: [ TestDependency(name: "B", requirement: v1Requirement), TestDependency(name: "C", requirement: v2Requirement), ] ), ], packages: [ TestPackage( name: "B", targets: [TestTarget(name: "B")], products: [TestProduct(name: "B", targets: ["B"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ), TestPackage( name: "C", targets: [TestTarget(name: "C")], products: [TestProduct(name: "C", targets: ["C"])], versions: [nil, "1.0.0", "1.0.5", "2.0.0"] ) ] ) let bRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "B")) let cRepo = RepositorySpecifier(url: workspace.urlForPackage(withName: "C")) let bRef = PackageReference(identity: "b", path: bRepo.url) let cRef = PackageReference(identity: "c", path: cRepo.url) try workspace.set( pins: [bRef: v1_5, cRef: v2], managedDependencies: [ ManagedDependency(packageRef: bRef, subpath: bPath, checkoutState: v1_5), ManagedDependency(packageRef: cRef, subpath: cPath, checkoutState: v2), ] ) try workspace.checkPrecomputeResolution { result in XCTAssertEqual(result.diagnostics.hasErrors, false) XCTAssertEqual(result.result.isRequired, false) } } func testLoadingRootManifests() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ .genericPackage1(named: "A"), .genericPackage1(named: "B"), .genericPackage1(named: "C"), ], packages: [] ) workspace.checkPackageGraph(roots: ["A", "B", "C"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "A", "B", "C") result.check(targets: "A", "B", "C") } XCTAssertNoDiagnostics(diagnostics) } } func testUpdate() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Root", targets: ["Root"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.5.0"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0"] ), ] ) // Do an intial run, capping at Foo at 1.0.0. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Run update. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.5.0"))) } XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Bar")]) // Run update again. // Ensure that up-to-date delegate is called when there is nothing to update. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } XCTAssertMatch(workspace.delegate.events, [.equal("Everything is already up-to-date")]) } func testUpdateDryRun() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Root", targets: ["Root"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.5.0"] ), ] ) // Do an intial run, capping at Foo at 1.0.0. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } // Run update. workspace.checkUpdateDryRun(roots: ["Root"]) { changes, diagnostics in XCTAssertNoDiagnostics(diagnostics) let expectedChange = ( PackageReference(identity: "foo", path: "/tmp/ws/pkgs/Foo"), Workspace.PackageStateChange.updated( .init(requirement: .version(Version("1.5.0")), products: .specific(["Foo"])) ) ) guard let change = changes?.first, changes?.count == 1 else { XCTFail() return } XCTAssertEqual(expectedChange, change) } workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } } func testPartialUpdate() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Root", targets: ["Root"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.5.0"] ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMinor(from: "1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "1.2.0"] ), ] ) // Do an intial run, capping at Foo at 1.0.0. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Run partial updates. // // Try to update just Bar. This shouldn't do anything because Bar can't be updated due // to Foo's requirements. workspace.checkUpdate(roots: ["Root"], packages: ["Bar"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Try to update just Foo. This should update Foo but not Bar. workspace.checkUpdate(roots: ["Root"], packages: ["Foo"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.5.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Run full update. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.5.0"))) result.check(dependency: "bar", at: .checkout(.version("1.2.0"))) } } func testCleanAndReset() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Root", targets: ["Root"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), ] ) // Load package graph. workspace.checkPackageGraph(roots: ["Root"]) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } // Drop a build artifact in data directory. let ws = workspace.createWorkspace() let buildArtifact = ws.dataPath.appending(component: "test.o") try fs.writeFileContents(buildArtifact, bytes: "Hi") // Sanity checks. XCTAssert(fs.exists(buildArtifact)) XCTAssert(fs.exists(ws.checkoutsPath)) // Check clean. workspace.checkClean { diagnostics in // Only the build artifact should be removed. XCTAssertFalse(fs.exists(buildArtifact)) XCTAssert(fs.exists(ws.checkoutsPath)) XCTAssert(fs.exists(ws.dataPath)) XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } // Add the build artifact again. try fs.writeFileContents(buildArtifact, bytes: "Hi") // Check reset. workspace.checkReset { diagnostics in // Only the build artifact should be removed. XCTAssertFalse(fs.exists(buildArtifact)) XCTAssertFalse(fs.exists(ws.checkoutsPath)) XCTAssertFalse(fs.exists(ws.dataPath)) XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.checkEmpty() } } func testDependencyManifestLoading() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root1", targets: [ TestTarget(name: "Root1", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), TestPackage( name: "Root2", targets: [ TestTarget(name: "Root2", dependencies: ["Bar"]), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ .genericPackage1(named: "Foo"), .genericPackage1(named: "Bar"), ] ) // Check that we can compute missing dependencies. workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { (manifests, diagnostics) in XCTAssertEqual(manifests.missingPackageURLs().map{$0.path}.sorted(), ["/tmp/ws/pkgs/Bar", "/tmp/ws/pkgs/Foo"]) XCTAssertNoDiagnostics(diagnostics) } // Load the graph with one root. workspace.checkPackageGraph(roots: ["Root1"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "Foo", "Root1") } XCTAssertNoDiagnostics(diagnostics) } // Check that we compute the correct missing dependencies. workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { (manifests, diagnostics) in XCTAssertEqual(manifests.missingPackageURLs().map{$0.path}.sorted(), ["/tmp/ws/pkgs/Bar"]) XCTAssertNoDiagnostics(diagnostics) } // Load the graph with both roots. workspace.checkPackageGraph(roots: ["Root1", "Root2"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "Bar", "Foo", "Root1", "Root2") } XCTAssertNoDiagnostics(diagnostics) } // Check that we compute the correct missing dependencies. workspace.loadDependencyManifests(roots: ["Root1", "Root2"]) { (manifests, diagnostics) in XCTAssertEqual(manifests.missingPackageURLs().map{$0.path}.sorted(), []) XCTAssertNoDiagnostics(diagnostics) } } func testDependencyManifestsOrder() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root1", targets: [ TestTarget(name: "Root1", dependencies: ["Foo", "Bar", "Baz", "Bam"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bam", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar", "Baz"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), .genericPackage1(named: "Bar"), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz", dependencies: ["Bam"]), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], dependencies: [ TestDependency(name: "Bam", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), .genericPackage1(named: "Bam"), ] ) workspace.checkPackageGraph(roots: ["Root1"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.loadDependencyManifests(roots: ["Root1"]) { (manifests, diagnostics) in // Ensure that the order of the manifests is stable. XCTAssertEqual(manifests.allDependencyManifests().map({ $0.name }), ["Foo", "Baz", "Bam", "Bar"]) XCTAssertNoDiagnostics(diagnostics) } } func testBranchAndRevision() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .branch("develop")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["develop"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["boo"] ), ] ) // Get some revision identifier of Bar. let bar = RepositorySpecifier(url: "/tmp/ws/pkgs/Bar") let barRevision = workspace.repoProvider.specifierMap[bar]!.revisions[0] // We request Bar via revision. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bar", requirement: .revision(barRevision), products: .specific(["Bar"])) ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.branch("develop"))) result.check(dependency: "bar", at: .checkout(.revision(barRevision))) } } func testResolve() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", "1.2.3"] ), ] ) // Load initial version. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.2.3"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.2.3"))) } // Resolve to an older version. workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.0.0") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } // Check failure. workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.3.0") { diagnostics in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("Foo 1.3.0"), behavior: .error) } } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } } func testDeletedCheckoutDirectory() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ .genericPackage1(named: "Foo"), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } try fs.removeFileTree(workspace.createWorkspace().checkoutsPath) workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("dependency 'Foo' is missing; cloning again"), behavior: .warning) } } } func testMinimumRequiredToolsVersionInDependencyResolution() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"], toolsVersion: .v3 ), ] ) workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("Foo[Foo] 1.0.0..<2.0.0"), behavior: .error) } } } func testToolsVersionRootPackages() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [] ), ], packages: [], toolsVersion: .v4 ) let roots = workspace.rootPaths(for: ["Foo", "Bar", "Baz"]).map({ $0.appending(component: "Package.swift") }) try fs.writeFileContents(roots[0], bytes: "// swift-tools-version:4.0") try fs.writeFileContents(roots[1], bytes: "// swift-tools-version:4.1.0") try fs.writeFileContents(roots[2], bytes: "// swift-tools-version:3.1") workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkPackageGraph(roots: ["Bar"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("package at '/tmp/ws/roots/Bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"), behavior: .error, location: "/tmp/ws/roots/Bar") } } workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("package at '/tmp/ws/roots/Bar' is using Swift tools version 4.1.0 but the installed version is 4.0.0"), behavior: .error, location: "/tmp/ws/roots/Bar") } } workspace.checkPackageGraph(roots: ["Baz"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("package at '/tmp/ws/roots/Baz' is using Swift tools version 3.1.0 which is no longer supported; consider using '// swift-tools-version:4.0' to specify the current tools version"), behavior: .error, location: "/tmp/ws/roots/Baz") } } } func testEditDependency() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo", "Bar"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", nil] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", nil] ), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } // Edit foo. let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo") workspace.checkEdit(packageName: "Foo") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } XCTAssertTrue(fs.exists(fooPath)) workspace.loadDependencyManifests(roots: ["Root"]) { (manifests, diagnostics) in let editedPackages = manifests.editedPackagesConstraints() XCTAssertEqual(editedPackages.map({ $0.identifier.path }), [fooPath.pathString]) XCTAssertNoDiagnostics(diagnostics) } // Try re-editing foo. workspace.checkEdit(packageName: "Foo") { diagnostics in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("dependency 'Foo' already in edit mode"), behavior: .error) } } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } // Try editing bar at bad revision. workspace.checkEdit(packageName: "Bar", revision: Revision(identifier: "dev")) { diagnostics in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("revision 'dev' does not exist"), behavior: .error) } } // Edit bar at a custom path and branch (ToT). let barPath = AbsolutePath("/tmp/ws/custom/bar") workspace.checkEdit(packageName: "Bar", path: barPath, checkoutBranch: "dev") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "bar", at: .edited(barPath)) } let barRepo = try workspace.repoProvider.openCheckout(at: barPath) as! InMemoryGitRepository XCTAssert(barRepo.revisions.contains("dev")) // Test unediting. workspace.checkUnedit(packageName: "Foo", roots: ["Root"]) { diagnostics in XCTAssertFalse(fs.exists(fooPath)) XCTAssertNoDiagnostics(diagnostics) } workspace.checkUnedit(packageName: "Bar", roots: ["Root"]) { diagnostics in XCTAssert(fs.exists(barPath)) XCTAssertNoDiagnostics(diagnostics) } } func testMissingEditCanRestoreOriginalCheckout() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", nil] ), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { _, _ in } // Edit foo. let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo") workspace.checkEdit(packageName: "Foo") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } XCTAssertTrue(fs.exists(fooPath)) // Remove the edited package. try fs.removeFileTree(fooPath) workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("dependency 'Foo' was being edited but is missing; falling back to original checkout"), behavior: .warning) } } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } } func testCanUneditRemovedDependencies() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", nil] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])), ] let ws = workspace.createWorkspace() // Load the graph and edit foo. workspace.checkPackageGraph(deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(packages: "Foo") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkEdit(packageName: "Foo") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } // Remove foo. workspace.checkUpdate { diagnostics in XCTAssertNoDiagnostics(diagnostics) } XCTAssertMatch(workspace.delegate.events, [.equal("removing repo: /tmp/ws/pkgs/Foo")]) workspace.checkPackageGraph(deps: []) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } // There should still be an entry for `foo`, which we can unedit. let editedDependency = ws.state.dependencies[forNameOrIdentity: "foo"]! XCTAssertNil(editedDependency.basedOn) workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } // Unedit foo. workspace.checkUnedit(packageName: "Foo", roots: []) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.checkEmpty() } } func testDependencyResolutionWithEdit() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo", "Bar"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", "1.2.0", "1.3.2"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", nil] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .exact("1.0.0"), products: .specific(["Foo"])), ] // Load the graph. workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Edit bar. workspace.checkEdit(packageName: "Bar") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .edited(nil)) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Add entry for the edited package. do { let barKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Bar") let editedBarKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Bar") let manifest = workspace.manifestLoader.manifests[barKey]! workspace.manifestLoader.manifests[editedBarKey] = manifest } // Now, resolve foo at a different version. workspace.checkResolve(pkg: "Foo", roots: ["Root"], version: "1.2.0") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.2.0"))) result.check(dependency: "bar", at: .edited(nil)) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.2.0"))) result.check(notPresent: "bar") } // Try package update. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(dependency: "bar", at: .edited(nil)) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(notPresent: "bar") } // Unedit should get the Package.resolved entry back. workspace.checkUnedit(packageName: "bar", roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } } func testPrefetchingWithOverridenPackage() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: [nil] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0"] ), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Bar", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } } // Test that changing a particular dependency re-resolves the graph. func testChangeOneDependency() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .exact("1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "1.5.0"] ), ] ) // Initial resolution. workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Bar", "Foo") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // Check that changing the requirement to 1.5.0 triggers re-resolution. // // FIXME: Find a cleaner way to change a dependency requirement. let fooKey = MockManifestLoader.Key(url: "/tmp/ws/roots/Foo") let manifest = workspace.manifestLoader.manifests[fooKey]! workspace.manifestLoader.manifests[fooKey] = Manifest( name: manifest.name, platforms: [], path: manifest.path, url: manifest.url, version: manifest.version, toolsVersion: manifest.toolsVersion, packageKind: .root, dependencies: [PackageDependencyDescription(name: nil, url: manifest.dependencies[0].url, requirement: .exact("1.5.0"))], targets: manifest.targets ) workspace.checkPackageGraph(roots: ["Foo"]) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "bar", at: .checkout(.version("1.5.0"))) } } func testResolutionFailureWithEditedDependency() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", nil] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", nil] ), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkEdit(packageName: "Foo") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } workspace.checkResolved() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } // Add entry for the edited package. do { let fooKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Foo") let editedFooKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Foo") let manifest = workspace.manifestLoader.manifests[fooKey]! workspace.manifestLoader.manifests[editedFooKey] = manifest } // Try resolving a bad graph. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bar", requirement: .exact("1.1.0"), products: .specific(["Bar"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("Bar[Bar] 1.1.0"), behavior: .error) } } } func testSkipUpdate() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Root", targets: ["Root"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.5.0"] ), ], skipUpdate: true ) // Run update and remove all events. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.delegate.events = [] // Check we don't have updating Foo event. workspace.checkUpdate(roots: ["Root"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) XCTAssertMatch(workspace.delegate.events, ["Everything is already up-to-date"]) } } func testLocalDependencyBasics() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar", "Baz"]), TestTarget(name: "FooTests", dependencies: ["Foo"], type: .test), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .localPackage), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "1.5.0", nil] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0", "1.5.0"] ), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Bar", "Baz", "Foo") result.check(targets: "Bar", "Baz", "Foo") result.check(testModules: "FooTests") result.checkTarget("Baz") { result in result.check(dependencies: "Bar") } result.checkTarget("Foo") { result in result.check(dependencies: "Baz", "Bar") } result.checkTarget("FooTests") { result in result.check(dependencies: "Foo") } } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "baz", at: .checkout(.version("1.5.0"))) result.check(dependency: "bar", at: .local) } // Test that its not possible to edit or resolve this package. workspace.checkEdit(packageName: "Bar") { diagnostics in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("local dependency 'Bar' can't be edited"), behavior: .error) } } workspace.checkResolve(pkg: "Bar", roots: ["Foo"], version: "1.0.0") { diagnostics in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("local dependency 'Bar' can't be edited"), behavior: .error) } } } func testLocalDependencyTransitive() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), TestTarget(name: "FooTests", dependencies: ["Foo"], type: .test), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", dependencies: ["Baz"]), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], dependencies: [ TestDependency(name: "Baz", requirement: .localPackage), ], versions: ["1.0.0", "1.5.0", nil] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0", "1.5.0", nil] ), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Foo") result.check(targets: "Foo") } DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("Bar[Bar] {1.0.0..<1.5.0, 1.5.1..<2.0.0} is forbidden"), behavior: .error) } } } func testLocalDependencyWithPackageUpdate() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "1.5.0", nil] ), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Bar", "Foo") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "bar", at: .checkout(.version("1.5.0"))) } // Override with local package and run update. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bar", requirement: .localPackage, products: .specific(["Bar"])), ] workspace.checkUpdate(roots: ["Foo"], deps: deps) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "bar", at: .local) } // Go back to the versioned state. workspace.checkUpdate(roots: ["Foo"]) { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "bar", at: .checkout(.version("1.5.0"))) } } func testMissingLocalDependencyDiagnostic() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: []), ], products: [], dependencies: [ TestDependency(name: nil, path: "Bar", requirement: .localPackage), ] ), ], packages: [ ] ) workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Foo") result.check(targets: "Foo") } DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("the package at '/tmp/ws/pkgs/Bar' cannot be accessed (doesn't exist in file system"), behavior: .error) } } } func testRevisionVersionSwitch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: []), ], products: [], dependencies: [] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["develop", "1.0.0"] ), ] ) // Test that switching between revision and version requirement works // without running swift package update. var deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .branch("develop"), products: .specific(["Foo"])) ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.branch("develop"))) } deps = [ .init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } deps = [ .init(name: "Foo", requirement: .branch("develop"), products: .specific(["Foo"])) ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.branch("develop"))) } } func testLocalVersionSwitch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: []), ], products: [], dependencies: [] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["develop", "1.0.0", nil] ), ] ) // Test that switching between local and version requirement works // without running swift package update. var deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } deps = [ .init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } deps = [ .init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } } func testLocalLocalSwitch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: []), ], products: [], dependencies: [] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: [nil] ), TestPackage( name: "Foo", path: "Foo2", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: [nil] ), ] ) // Test that switching between two same local packages placed at // different locations works correctly. var deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } deps = [ .init(name: "Foo2", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo2", at: .local) } } func testDependencySwitchWithSameIdentity() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: []), ], products: [], dependencies: [] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: [nil] ), TestPackage( name: "Foo", path: "Nested/Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: [nil] ), ] ) // Test that switching between two same local packages placed at // different locations works correctly. var deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } do { let ws = workspace.createWorkspace() XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Foo"]) } deps = [ .init(name: "Nested/Foo", requirement: .localPackage, products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } do { let ws = workspace.createWorkspace() XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Nested/Foo"]) } } func testResolvedFileUpdate() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: []), ], products: [], dependencies: [] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Foo", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Foo"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } workspace.checkResolved() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } workspace.checkPackageGraph(roots: ["Root"], deps: []) { (_, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) } workspace.checkResolved() { result in result.check(notPresent: "foo") } } func testPackageMirror() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Dep"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Dep", requirement: .upToNextMajor(from: "1.0.0")), ], toolsVersion: .v5 ), ], packages: [ TestPackage( name: "Dep", targets: [ TestTarget(name: "Dep", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Dep", targets: ["Dep"]), ], dependencies: [ TestDependency(name: nil, path: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0", "1.5.0"], toolsVersion: .v5 ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "1.5.0"] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Bar", targets: ["Baz"]), ], versions: ["1.0.0", "1.4.0"] ), TestPackage( name: "Bam", targets: [ TestTarget(name: "Bam"), ], products: [ TestProduct(name: "Bar", targets: ["Bam"]), ], versions: ["1.0.0", "1.5.0"] ), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Foo", "Dep", "Bar") result.check(targets: "Foo", "Dep", "Bar") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "Dep", at: .checkout(.version("1.5.0"))) result.check(dependency: "Bar", at: .checkout(.version("1.5.0"))) result.check(notPresent: "Baz") } try workspace.config.set(mirrorURL: workspace.packagesDir.appending(component: "Baz").pathString, forURL: workspace.packagesDir.appending(component: "Bar").pathString) try workspace.config.set(mirrorURL: workspace.packagesDir.appending(component: "Baz").pathString, forURL: workspace.packagesDir.appending(component: "Bam").pathString) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bam", requirement: .upToNextMajor(from: "1.0.0"), products: .specific(["Bar"])), ] workspace.checkPackageGraph(roots: ["Foo"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Foo") result.check(packages: "Foo", "Dep", "Baz") result.check(targets: "Foo", "Dep", "Baz") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "Dep", at: .checkout(.version("1.5.0"))) result.check(dependency: "Baz", at: .checkout(.version("1.4.0"))) result.check(notPresent: "Bar") result.check(notPresent: "Bam") } } func testTransitiveDependencySwitchWithSameIdentity() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Bar"]), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", dependencies: ["Foo"]), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", dependencies: ["Nested/Foo"]), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], dependencies: [ TestDependency(name: nil, path: "Nested/Foo", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.1.0"], toolsVersion: .v5 ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), TestPackage( name: "Foo", path: "Nested/Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Nested/Foo", targets: ["Foo"]), ], versions: ["1.0.0"] ), ] ) // In this test, we get into a state where add an entry in the resolved // file for a transitive dependency whose URL is later changed to // something else, while keeping the same package identity. // // This is normally detected during pins validation before the // dependency resolution process even begins but if we're starting with // a clean slate, we don't even know about the correct urls of the // transitive dependencies. We will end up fetching the wrong // dependency as we prefetch the pins. If we get into this case, it // should kick off another dependency resolution operation which will // have enough information to remove the invalid pins of transitive // dependencies. var deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bar", requirement: .exact("1.0.0"), products: .specific(["Bar"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } do { let ws = workspace.createWorkspace() XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Foo"]) } workspace.checkReset { diagnostics in XCTAssertNoDiagnostics(diagnostics) } deps = [ .init(name: "Bar", requirement: .exact("1.1.0"), products: .specific(["Bar"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in PackageGraphTester(graph) { result in result.check(roots: "Root") result.check(packages: "Bar", "Foo", "Root") } XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.1.0"))) } do { let ws = workspace.createWorkspace() XCTAssertNotNil(ws.state.dependencies[forURL: "/tmp/ws/pkgs/Nested/Foo"]) } } func testForceResolveToResolvedVersions() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo", "Bar"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: ["1.0.0", "1.2.0", "1.3.2"] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", "develop"] ), ] ) // Load the initial graph. let deps: [TestWorkspace.PackageDependency] = [ .init(name: "Bar", requirement: .revision("develop"), products: .specific(["Bar"])), ] workspace.checkPackageGraph(roots: ["Root"], deps: deps) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(dependency: "bar", at: .checkout(.branch("develop"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.3.2"))) result.check(dependency: "bar", at: .checkout(.branch("develop"))) } // Change pin of foo to something else. do { let ws = workspace.createWorkspace() let pinsStore = try ws.pinsStore.load() let fooPin = pinsStore.pins.first(where: { $0.packageRef.identity == "foo" })! let fooRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: fooPin.packageRef.path)]! let revision = try fooRepo.resolveRevision(tag: "1.0.0") let newState = CheckoutState(revision: revision, version: "1.0.0") pinsStore.pin(packageRef: fooPin.packageRef, state: newState) try pinsStore.saveState() } // Check force resolve. This should produce an error because the resolved file is out-of-date. workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: "cannot update Package.resolved file because automatic resolution is disabled", checkContains: true, behavior: .error) } } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.branch("develop"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.branch("develop"))) } // A normal resolution. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } // This force resolution should succeed. workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } workspace.checkResolved { result in result.check(dependency: "foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "bar", at: .checkout(.version("1.0.0"))) } } func testForceResolveToResolvedVersionsLocalPackage() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .localPackage), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo"), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], versions: [nil] ), ] ) workspace.checkPackageGraph(roots: ["Root"], forceResolvedVersions: true) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies() { result in result.check(dependency: "foo", at: .local) } } func testSimpleAPI() throws { guard Resources.havePD4Runtime else { return } // This verifies that the simplest possible loading APIs are available for package clients. // This checkout of the SwiftPM package. let package = AbsolutePath(#file).parentDirectory.parentDirectory.parentDirectory // Clients must locate the corresponding “swiftc” exectuable themselves for now. // (This just uses the same one used by all the other tests.) let swiftCompiler = Resources.default.swiftCompiler // From here the API should be simple and straightforward: let diagnostics = DiagnosticsEngine() let manifest = try ManifestLoader.loadManifest( packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], packageKind: .local) let loadedPackage = try PackageBuilder.loadPackage( packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], xcTestMinimumDeploymentTargets: [:], diagnostics: diagnostics) let graph = try Workspace.loadGraph( packagePath: package, swiftCompiler: swiftCompiler, swiftCompilerFlags: [], diagnostics: diagnostics) XCTAssertEqual(manifest.name, "SwiftPM") XCTAssertEqual(loadedPackage.name, "SwiftPM") XCTAssert(graph.reachableProducts.contains(where: { $0.name == "SwiftPM" })) } func testRevisionDepOnLocal() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .branch("develop")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Local"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Local", requirement: .localPackage), ], versions: ["develop"] ), TestPackage( name: "Local", targets: [ TestTarget(name: "Local"), ], products: [ TestProduct(name: "Local", targets: ["Local"]), ], versions: [nil] ), ] ) workspace.checkPackageGraph(roots: ["Root"]) { (_, diagnostics) in DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .equal("package 'Foo' is required using a revision-based requirement and it depends on local package 'Local', which is not supported"), behavior: .error) } } } func testRootPackagesOverrideBasenameMismatch() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Baz", path: "Overridden/bazzz-master", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ] ), ], packages: [ TestPackage( name: "Baz", path: "bazzz", targets: [ TestTarget(name: "Baz"), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0"] ), ] ) let deps: [TestWorkspace.PackageDependency] = [ .init(name: "bazzz", requirement: .exact("1.0.0"), products: .specific(["Baz"])), ] workspace.checkPackageGraph(roots: ["Overridden/bazzz-master"], deps: deps) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics, ignoreNotes: true) { result in result.check(diagnostic: .equal("unable to override package 'Baz' because its basename 'bazzz' doesn't match directory name 'bazzz-master'"), behavior: .error) } } } func testUnsafeFlags() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", nil] ), TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar", "Baz"]), ], products: [], dependencies: [ TestDependency(name: "Bar", requirement: .localPackage), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar", settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["1.0.0", nil] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz", dependencies: ["Bar"], settings: [.init(tool: .swift, name: .unsafeFlags, value: ["-F", "/tmp"])]), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0", "1.5.0"] ), ] ) // We should only see errors about use of unsafe flag in the version-based dependency. workspace.checkPackageGraph(roots: ["Foo", "Bar"]) { (graph, diagnostics) in DiagnosticsEngineTester(diagnostics, ignoreNotes: true) { result in result.checkUnordered(diagnostic: .equal("the target 'Baz' in product 'Baz' contains unsafe build flags"), behavior: .error) result.checkUnordered(diagnostic: .equal("the target 'Bar' in product 'Baz' contains unsafe build flags"), behavior: .error) } } } func testEditDependencyHadOverridableConstraints() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo", "Baz"]), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .branch("master")), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ] ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Foo", targets: ["Foo"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .branch("master")), ], versions: ["master", nil] ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), ], versions: ["master", "1.0.0", nil] ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz", dependencies: ["Bar"]), ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], dependencies: [ TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0", nil] ), ] ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .checkout(.branch("master"))) result.check(dependency: "bar", at: .checkout(.branch("master"))) result.check(dependency: "baz", at: .checkout(.version("1.0.0"))) } // Edit foo. let fooPath = workspace.createWorkspace().editablesPath.appending(component: "Foo") workspace.checkEdit(packageName: "Foo") { diagnostics in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) } XCTAssertTrue(fs.exists(fooPath)) // Add entry for the edited package. do { let fooKey = MockManifestLoader.Key(url: "/tmp/ws/pkgs/Foo") let editedFooKey = MockManifestLoader.Key(url: "/tmp/ws/edits/Foo") let manifest = workspace.manifestLoader.manifests[fooKey]! workspace.manifestLoader.manifests[editedFooKey] = manifest } XCTAssertMatch(workspace.delegate.events, [.equal("will resolve dependencies")]) workspace.delegate.events.removeAll() workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "foo", at: .edited(nil)) result.check(dependency: "bar", at: .checkout(.branch("master"))) result.check(dependency: "baz", at: .checkout(.version("1.0.0"))) } XCTAssertNoMatch(workspace.delegate.events, [.equal("will resolve dependencies")]) } func testTargetBasedDependency() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Root", targets: [ TestTarget(name: "Root", dependencies: ["Foo", "Bar"]), TestTarget(name: "RootTests", dependencies: ["TestHelper1"], type: .test), ], products: [], dependencies: [ TestDependency(name: "Foo", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Bar", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "TestHelper1", requirement: .upToNextMajor(from: "1.0.0")), ], toolsVersion: .v5_2 ), ], packages: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo1", dependencies: ["Foo2"]), TestTarget(name: "Foo2", dependencies: ["Baz"]), TestTarget(name: "FooTests", dependencies: ["TestHelper2"], type: .test) ], products: [ TestProduct(name: "Foo", targets: ["Foo1"]), ], dependencies: [ TestDependency(name: "TestHelper2", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Baz", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"], toolsVersion: .v5_2 ), TestPackage( name: "Bar", targets: [ TestTarget(name: "Bar"), TestTarget(name: "BarUnused", dependencies: ["Biz"]), TestTarget(name: "BarTests", dependencies: ["TestHelper2"], type: .test), ], products: [ TestProduct(name: "Bar", targets: ["Bar"]), TestProduct(name: "BarUnused", targets: ["BarUnused"]) ], dependencies: [ TestDependency(name: "TestHelper2", requirement: .upToNextMajor(from: "1.0.0")), TestDependency(name: "Biz", requirement: .upToNextMajor(from: "1.0.0")), ], versions: ["1.0.0"], toolsVersion: .v5_2 ), TestPackage( name: "Baz", targets: [ TestTarget(name: "Baz") ], products: [ TestProduct(name: "Baz", targets: ["Baz"]), ], versions: ["1.0.0"], toolsVersion: .v5_2 ), TestPackage( name: "TestHelper1", targets: [ TestTarget(name: "TestHelper1"), ], products: [ TestProduct(name: "TestHelper1", targets: ["TestHelper1"]), ], versions: ["1.0.0"], toolsVersion: .v5_2 ), ], toolsVersion: .v5_2, enablePubGrub: true ) // Load the graph. workspace.checkPackageGraph(roots: ["Root"]) { (graph, diagnostics) in XCTAssertNoDiagnostics(diagnostics) } workspace.checkManagedDependencies { result in result.check(dependency: "Foo", at: .checkout(.version("1.0.0"))) result.check(dependency: "Bar", at: .checkout(.version("1.0.0"))) result.check(dependency: "Baz", at: .checkout(.version("1.0.0"))) result.check(dependency: "TestHelper1", at: .checkout(.version("1.0.0"))) result.check(notPresent: "Biz") result.check(notPresent: "TestHelper2") } } func testChecksumForBinaryArtifact() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["Foo"]), ], products: [] ), ], packages: [] ) let ws = workspace.createWorkspace() // Checks the valid case. do { let binaryPath = sandbox.appending(component: "binary.zip") try fs.writeFileContents(binaryPath, bytes: ByteString([0xaa, 0xbb, 0xcc])) let diagnostics = DiagnosticsEngine() let checksum = ws.checksum(forBinaryArtifactAt: binaryPath, diagnostics: diagnostics) XCTAssertTrue(!diagnostics.hasErrors) XCTAssertEqual(workspace.checksumAlgorithm.hashes.map({ $0.contents }), [[0xaa, 0xbb, 0xcc]]) XCTAssertEqual(checksum, "ccbbaa") } // Checks an unsupported extension. do { let unknownPath = sandbox.appending(component: "unknown") let diagnostics = DiagnosticsEngine() let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics) XCTAssertEqual(checksum, "") DiagnosticsEngineTester(diagnostics) { result in let expectedDiagnostic = "unexpected file type; supported extensions are: zip" result.check(diagnostic: .contains(expectedDiagnostic), behavior: .error) } } // Checks a supported extension that is not a file (does not exist). do { let unknownPath = sandbox.appending(component: "missingFile.zip") let diagnostics = DiagnosticsEngine() let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics) XCTAssertEqual(checksum, "") DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("file not found at path: /tmp/ws/missingFile.zip"), behavior: .error) } } // Checks a supported extension that is a directory instead of a file. do { let unknownPath = sandbox.appending(component: "aDirectory.zip") try fs.createDirectory(unknownPath) let diagnostics = DiagnosticsEngine() let checksum = ws.checksum(forBinaryArtifactAt: unknownPath, diagnostics: diagnostics) XCTAssertEqual(checksum, "") DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("file not found at path: /tmp/ws/aDirectory.zip"), behavior: .error) } } } func testArtifactDownload() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() var downloads: [MockDownloader.Download] = [] let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, downloader: MockDownloader(fileSystem: fs, downloadFile: { url, destination, progress, completion in let contents: [UInt8] switch url.lastPathComponent { case "a1.zip": contents = [0xa1] case "a2.zip": contents = [0xa2] case "a3.zip": contents = [0xa3] case "b.zip": contents = [0xb0] default: XCTFail("unexpected url") contents = [] } try! fs.writeFileContents( destination, bytes: ByteString(contents), atomically: true ) downloads.append(MockDownloader.Download(url: url, destinationPath: destination)) completion(.success(())) }), roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: [ "B", .product(name: "A1", package: "A"), .product(name: "A2", package: "A"), .product(name: "A3", package: "A"), .product(name: "A4", package: "A"), ]), ], products: [], dependencies: [ TestDependency(name: "A", requirement: .exact("1.0.0")), TestDependency(name: "B", requirement: .exact("1.0.0")), ] ), ], packages: [ TestPackage( name: "A", targets: [ TestTarget( name: "A1", type: .binary, url: "https://a.com/a1.zip", checksum: "a1"), TestTarget( name: "A2", type: .binary, url: "https://a.com/a2.zip", checksum: "a2"), TestTarget( name: "A3", type: .binary, url: "https://a.com/a3.zip", checksum: "a3"), TestTarget( name: "A4", type: .binary, path: "A4.xcframework"), ], products: [ TestProduct(name: "A1", targets: ["A1"]), TestProduct(name: "A2", targets: ["A2"]), TestProduct(name: "A3", targets: ["A3"]), TestProduct(name: "A4", targets: ["A4"]), ], versions: ["1.0.0"] ), TestPackage( name: "B", targets: [ TestTarget( name: "B", type: .binary, url: "https://b.com/b.zip", checksum: "b0"), ], products: [ TestProduct(name: "B", targets: ["B"]), ], versions: ["1.0.0"] ), ] ) let a4FrameworkPath = workspace.packagesDir.appending(components: "A", "A4.xcframework") try fs.createDirectory(a4FrameworkPath, recursive: true) try [("A", "A1.xcframework"), ("A", "A2.xcframework"), ("B", "B.xcframework")].forEach { let frameworkPath = workspace.artifactsDir.appending(components: $0.0, $0.1) try fs.createDirectory(frameworkPath, recursive: true) } // Pin A to 1.0.0, Checkout B to 1.0.0 let aPath = workspace.urlForPackage(withName: "A") let aRef = PackageReference(identity: "a", path: aPath) let aRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: aPath)]! let aRevision = try aRepo.resolveRevision(tag: "1.0.0") let aState = CheckoutState(revision: aRevision, version: "1.0.0") try workspace.set( pins: [aRef: aState], managedDependencies: [], managedArtifacts: [ ManagedArtifact( packageRef: aRef, targetName: "A1", source: .remote( url: "https://a.com/a1.zip", checksum: "a1", subpath: RelativePath("A/A1.xcframework"))), ManagedArtifact( packageRef: aRef, targetName: "A3", source: .remote( url: "https://a.com/old/a3.zip", checksum: "a3-old-checksum", subpath: RelativePath("A/A3.xcframework"))), ManagedArtifact( packageRef: aRef, targetName: "A4", source: .remote( url: "https://a.com/a4.zip", checksum: "a4", subpath: RelativePath("A/A4.xcframework"))), ManagedArtifact( packageRef: aRef, targetName: "A5", source: .remote( url: "https://a.com/a5.zip", checksum: "a5", subpath: RelativePath("A/A5.xcframework"))), ManagedArtifact( packageRef: aRef, targetName: "A6", source: .local(path: "A6.xcframework")), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { graph, diagnostics in XCTAssertEqual(diagnostics.diagnostics.map { $0.message.text }, ["downloaded archive of binary target 'A3' does not contain expected binary artifact 'A3.xcframework'"]) XCTAssert(fs.isDirectory(AbsolutePath("/tmp/ws/.build/artifacts/B"))) XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A3.xcframework"))) XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A4.xcframework"))) XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/A/A5.xcframework"))) XCTAssert(!fs.exists(AbsolutePath("/tmp/ws/.build/artifacts/Foo"))) XCTAssertEqual(downloads.map({ $0.url }), [ URL(string: "https://b.com/b.zip")!, URL(string: "https://a.com/a2.zip")!, URL(string: "https://a.com/a3.zip")!, ]) XCTAssertEqual(workspace.checksumAlgorithm.hashes, [ ByteString([0xb0]), ByteString([0xa2]), ByteString([0xa3]), ]) XCTAssertEqual(workspace.archiver.extractions.map({ $0.destinationPath }), [ AbsolutePath("/tmp/ws/.build/artifacts/B"), AbsolutePath("/tmp/ws/.build/artifacts/A"), AbsolutePath("/tmp/ws/.build/artifacts/A"), ]) XCTAssertEqual( downloads.map({ $0.destinationPath }), workspace.archiver.extractions.map({ $0.archivePath }) ) PackageGraphTester(graph) { graph in if let a1 = graph.find(target: "A1")?.underlyingTarget as? BinaryTarget { XCTAssertEqual(a1.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A1.xcframework")) XCTAssertEqual(a1.artifactSource, .remote(url: "https://a.com/a1.zip")) } else { XCTFail("expected binary target") } if let a2 = graph.find(target: "A2")?.underlyingTarget as? BinaryTarget { XCTAssertEqual(a2.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A2.xcframework")) XCTAssertEqual(a2.artifactSource, .remote(url: "https://a.com/a2.zip")) } else { XCTFail("expected binary target") } if let a3 = graph.find(target: "A3")?.underlyingTarget as? BinaryTarget { XCTAssertEqual(a3.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/A/A3.xcframework")) XCTAssertEqual(a3.artifactSource, .remote(url: "https://a.com/a3.zip")) } else { XCTFail("expected binary target") } if let a4 = graph.find(target: "A4")?.underlyingTarget as? BinaryTarget { XCTAssertEqual(a4.artifactPath, a4FrameworkPath) XCTAssertEqual(a4.artifactSource, .local) } else { XCTFail("expected binary target") } if let b = graph.find(target: "B")?.underlyingTarget as? BinaryTarget { XCTAssertEqual(b.artifactPath, AbsolutePath("/tmp/ws/.build/artifacts/B/B.xcframework")) XCTAssertEqual(b.artifactSource, .remote(url: "https://b.com/b.zip")) } else { XCTFail("expected binary target") } } } workspace.checkManagedArtifacts { result in result.check(packageName: "A", targetName: "A1", source: .remote( url: "https://a.com/a1.zip", checksum: "a1", subpath: RelativePath("A/A1.xcframework"))) result.check(packageName: "A", targetName: "A2", source: .remote( url: "https://a.com/a2.zip", checksum: "a2", subpath: RelativePath("A/A2.xcframework"))) result.check(packageName: "A", targetName: "A3", source: .remote( url: "https://a.com/a3.zip", checksum: "a3", subpath: RelativePath("A/A3.xcframework"))) result.check(packageName: "A", targetName: "A4", source: .local(path: "A4.xcframework")) result.checkNotPresent(packageName: "A", targetName: "A5") result.check(packageName: "B", targetName: "B", source: .remote( url: "https://b.com/b.zip", checksum: "b0", subpath: RelativePath("B/B.xcframework"))) } } func testArtifactDownloaderOrArchiverError() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, downloader: MockDownloader(fileSystem: fs, downloadFile: { url, destination, _, completion in switch url { case URL(string: "https://a.com/a1.zip")!: completion(.failure(.serverError(statusCode: 500))) case URL(string: "https://a.com/a2.zip")!: try! fs.writeFileContents(destination, bytes: ByteString([0xa2])) completion(.success(())) case URL(string: "https://a.com/a3.zip")!: try! fs.writeFileContents(destination, bytes: "different contents = different checksum") completion(.success(())) default: XCTFail("unexpected url") completion(.success(())) } }), archiver: MockArchiver(extract: { _, destinationPath, completion in XCTAssertEqual(destinationPath, AbsolutePath("/tmp/ws/.build/artifacts/A")) completion(.failure(DummyError())) }), roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: [ .product(name: "A1", package: "A"), .product(name: "A2", package: "A"), ]), ], products: [], dependencies: [ TestDependency(name: "A", requirement: .exact("1.0.0")) ] ), ], packages: [ TestPackage( name: "A", targets: [ TestTarget( name: "A1", type: .binary, url: "https://a.com/a1.zip", checksum: "a1"), TestTarget( name: "A2", type: .binary, url: "https://a.com/a2.zip", checksum: "a2"), TestTarget( name: "A3", type: .binary, url: "https://a.com/a3.zip", checksum: "a3"), ], products: [ TestProduct(name: "A1", targets: ["A1"]), TestProduct(name: "A2", targets: ["A2"]), TestProduct(name: "A3", targets: ["A3"]), ], versions: ["1.0.0"] ), ] ) workspace.checkPackageGraph(roots: ["Foo"]) { result, diagnostics in print(diagnostics.diagnostics) DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("artifact of binary target 'A1' failed download: invalid status code 500"), behavior: .error) result.check(diagnostic: .contains("artifact of binary target 'A2' failed extraction: dummy error"), behavior: .error) result.check(diagnostic: .contains("checksum of downloaded artifact of binary target 'A3' (6d75736b6365686320746e65726566666964203d2073746e65746e6f6320746e65726566666964) does not match checksum specified by the manifest (a3)"), behavior: .error) } } } func testArtifactChecksumChange() throws { let sandbox = AbsolutePath("/tmp/ws/") let fs = InMemoryFileSystem() let workspace = try TestWorkspace( sandbox: sandbox, fs: fs, roots: [ TestPackage( name: "Foo", targets: [ TestTarget(name: "Foo", dependencies: ["A"]), ], products: [], dependencies: [ TestDependency(name: "A", requirement: .exact("1.0.0")) ] ), ], packages: [ TestPackage( name: "A", targets: [ TestTarget(name: "A", type: .binary, url: "https://a.com/a.zip", checksum: "a"), ], products: [ TestProduct(name: "A", targets: ["A"]) ], versions: ["0.9.0", "1.0.0"] ), ] ) // Pin A to 1.0.0, Checkout A to 1.0.0 let aPath = workspace.urlForPackage(withName: "A") let aRef = PackageReference(identity: "a", path: aPath) let aRepo = workspace.repoProvider.specifierMap[RepositorySpecifier(url: aPath)]! let aRevision = try aRepo.resolveRevision(tag: "1.0.0") let aState = CheckoutState(revision: aRevision, version: "1.0.0") let aDependency = ManagedDependency(packageRef: aRef, subpath: RelativePath("A"), checkoutState: aState) try workspace.set( pins: [aRef: aState], managedDependencies: [aDependency], managedArtifacts: [ ManagedArtifact( packageRef: aRef, targetName: "A", source: .remote( url: "https://a.com/a.zip", checksum: "old-checksum", subpath: RelativePath("A/A.xcframework"))) ] ) workspace.checkPackageGraph(roots: ["Foo"]) { result, diagnostics in XCTAssertEqual(workspace.downloader.downloads, []) DiagnosticsEngineTester(diagnostics) { result in result.check(diagnostic: .contains("artifact of binary target 'A' has changed checksum"), behavior: .error) } } } func testAndroidCompilerFlags() throws { let target = try Triple("x86_64-unknown-linux-android") let sdk = AbsolutePath("/some/path/to/an/SDK.sdk") let toolchainPath = AbsolutePath("/some/path/to/a/toolchain.xctoolchain") let destination = Destination( target: target, sdk: sdk, binDir: toolchainPath.appending(components: "usr", "bin") ) XCTAssertEqual(UserToolchain.deriveSwiftCFlags(triple: target, destination: destination), [ // Needed when cross‐compiling for Android. 2020‐03‐01 "-sdk", sdk.pathString ]) } } extension PackageGraph { /// Finds the package matching the given name. func lookup(_ name: String) -> PackageModel.ResolvedPackage { return packages.first{ $0.name == name }! } } struct DummyError: LocalizedError, Equatable { public var errorDescription: String? { "dummy error" } }
39.319144
277
0.469229
f89b4cff5b5351f2f94a6da0dca5ee925ead3f8e
702
import Foundation import XCTest class HRTest: XCTestCase { var scores: [Int] = [] var weighs: [Int] = [] override func setUp() { scores = [10, 40, 30, 50, 20] weighs = [1, 2, 3, 4, 5] } override func tearDown() { scores.removeAll() weighs.removeAll() } func testGetWeightedMean() { // Assemble var result: Double // Activate result = getWeightedMean(data: scores, weighs: weighs) // Assert XCTAssertEqual(result, 32.0) } } HRTest.defaultTestSuite.run() //let n = Int(readLine()!)! //let data = readLine()!.split(separator: " ").map{ Int($0)! } //let weighs = readLine()!.split(separator: " ").map{ Int($0)! } // //print(getWeightedMean(data: data, weighs: weighs))
18.473684
64
0.636752
46ec143e5682919e938eb1e5c4840e03ddbf46f5
1,661
// swift-tools-version:5.5 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "swift-inotify", platforms: [ // These are necessary even though we don't support them. // The requirements are taken from swift-filestreamer. .macOS(.v10_12), .iOS(.v10), .tvOS(.v10), .watchOS(.v3), ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "Inotify", targets: ["Inotify"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. .package(url: "https://github.com/apple/swift-system.git", .upToNextMinor(from: "0.0.2")), .package(url: "https://github.com/sersoft-gmbh/swift-filestreamer.git", .upToNextMinor(from: "0.3.0")), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .systemLibrary( name: "Cinotify" ), .target( name: "Inotify", dependencies: [ .product(name: "SystemPackage", package: "swift-system"), .product(name: "FileStreamer", package: "swift-filestreamer"), "Cinotify", ]), .testTarget( name: "InotifyTests", dependencies: ["Inotify"]), ] )
36.911111
117
0.593016
f995863222a56708898f27cc55f17f087977ef7a
1,378
/* See LICENSE folder for this sample’s licensing information. Abstract: A view displaying inforamtion about a hike, including an elevation graph. */ import SwiftUI struct HikeView: View { var hike: Hike @State private var showDetail = false var body: some View { VStack { HStack { HikeGraph(hike: hike, path: \.elevation) .frame(width: 50, height: 30) .animation(nil) VStack(alignment: .leading) { Text(verbatim: hike.name) .font(.headline) Text(verbatim: hike.distanceText) } Spacer() Button(action: { self.showDetail.toggle() }) { Image(systemName: "chevron.right.circle") .imageScale(.large) .rotationEffect(.degrees(showDetail ? 90 : 0)) .padding() } } if showDetail { HikeDetail(hike: hike) } } } } struct HikeView_Previews: PreviewProvider { static var previews: some View { VStack { HikeView(hike: hikeData[0]) .padding() Spacer() } } }
25.054545
73
0.451379
892ef99e3043fd88d110c434121197c8539543ad
388
import Foundation import CoreLocation protocol SmartGuessService { func get(forLocation: CLLocation) -> SmartGuess? @discardableResult func add(withCategory category: Category, location: CLLocation) -> SmartGuess? func markAsUsed(_ smartGuess: SmartGuess, atTime time: Date) func strike(withId id: Int) func purgeEntries(olderThan maxAge: Date) }
24.25
101
0.726804
6aa75b594190edac1c6779e84f70a431f5232d12
2,348
// MIT License // // Copyright (c) 2017 Wesley Wickwire // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation extension UnsafePointer { var raw: UnsafeRawPointer { return UnsafeRawPointer(self) } var mutable: UnsafeMutablePointer<Pointee> { return UnsafeMutablePointer<Pointee>(mutating: self) } func vector(n: IntegerConvertible) -> [Pointee] { var result = [Pointee]() for i in 0..<n.getInt() { result.append(advanced(by: i).pointee) } return result } } extension UnsafePointer where Pointee: Equatable { func advance(to value: Pointee) -> UnsafePointer<Pointee> { var pointer = self while pointer.pointee != value { pointer = pointer.advanced(by: 1) } return pointer } } extension UnsafeMutablePointer { var raw: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(self) } func vector(n: IntegerConvertible) -> [Pointee] { var result = [Pointee]() for i in 0..<n.getInt() { result.append(advanced(by: i).pointee) } return result } func advanced(by n: Int, wordSize: Int) -> UnsafeMutableRawPointer { return self.raw.advanced(by: n * wordSize) } }
32.611111
81
0.675894
1af2a0b24625802e00fca9fbcdbf54c960a0d422
787
// // DHToolBar.swift // EasyTodoList // // Created by DJ on 14/12/2016. // Copyright © 2016 DJ. All rights reserved. // import UIKit class DHToolBar: UIToolbar { @IBOutlet weak var cancelButton: UIBarButtonItem! @IBOutlet weak var doneButton: UIBarButtonItem! override func awakeFromNib() { super.awakeFromNib() } class func initWithTarget(target: AnyObject, tag: Int) -> DHToolBar { let toolbar = UINib.init(nibName: "DHToolBar", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! DHToolBar toolbar.doneButton.target = target toolbar.doneButton.tag = tag toolbar.cancelButton.target = target toolbar.cancelButton.tag = tag return toolbar } }
21.861111
126
0.634053
4a475e8a217169478a80be1b2dd2ea34a6f6245e
20,322
// RUN: %target-parse-verify-swift func markUsed<T>(_ t: T) {} let bad_property_1: Int { // expected-error {{'let' declarations cannot be computed properties}} get { return 42 } } let bad_property_2: Int = 0 { get { // expected-error {{use of unresolved identifier 'get'}} return 42 } } let no_initializer : Int func foreach_variable() { for i in 0..<42 { i = 11 // expected-error {{cannot assign to value: 'i' is a 'let' constant}} } } func takeClosure(_ fn : (Int) -> Int) {} func passClosure() { takeClosure { a in a = 42 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} return a } takeClosure { $0 = 42 // expected-error{{cannot assign to value: '$0' is immutable}} return 42 } takeClosure { (a : Int) -> Int in a = 42 // expected-error{{cannot assign to value: 'a' is a 'let' constant}} return 42 } } class FooClass { class let type_let = 5 // expected-error {{class stored properties not supported in classes}} init() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } func bar() { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}} mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func baz() {} var x : Int { get { return 32 } set(value) { value = 42 // expected-error {{cannot assign to value: 'value' is a 'let' constant}} } } subscript(i : Int) -> Int { get { i = 42 // expected-error {{cannot assign to value: 'i' is immutable}} return 1 } } } func let_decls() { // <rdar://problem/16927246> provide a fixit to change "let" to "var" if needing to mutate a variable let a = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} a = 17 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} let (b,c) = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(b); markUsed(c) b = 17 // expected-error {{cannot assign to value: 'b' is a 'let' constant}} let d = (4, "hello") // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} markUsed(d.0); markUsed(d.1) d.0 = 17 // expected-error {{cannot assign to property: 'd' is a 'let' constant}} let e = 42 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} ++e // expected-error {{cannot pass immutable value to mutating operator: 'e' is a 'let' constant}} // <rdar://problem/16306600> QoI: passing a 'let' value as an inout results in an unfriendly diagnostic let f = 96 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} var v = 1 swap(&f, &v) // expected-error {{cannot pass immutable value as inout argument: 'f' is a 'let' constant}} // <rdar://problem/19711233> QoI: poor diagnostic for operator-assignment involving immutable operand let g = 14 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} g /= 2 // expected-error {{left side of mutating operator isn't mutable: 'g' is a 'let' constant}} } struct SomeStruct { var iv = 32 static let type_let = 5 // expected-note {{change 'let' to 'var' to make it mutable}} {{10-13=var}} mutating static func f() { // expected-error {{static functions may not be declared mutating}} {{3-12=}} } mutating func g() { iv = 42 } mutating func g2() { iv = 42 } func h() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} iv = 12 // expected-error {{cannot assign to property: 'self' is immutable}} } var p: Int { // Getters default to non-mutating. get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } // Setters default to mutating. set { iv = newValue } } // Defaults can be changed. var q : Int { mutating get { iv = 37 return 42 } nonmutating set { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = newValue // expected-error {{cannot assign to property: 'self' is immutable}} } } var r : Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} {{5-5=mutating }} iv = 37 // expected-error {{cannot assign to property: 'self' is immutable}} return 42 } mutating // Redundant but OK. set { iv = newValue } } } markUsed(SomeStruct.type_let) // ok SomeStruct.type_let = 17 // expected-error {{cannot assign to property: 'type_let' is a 'let' constant}} struct TestMutableStruct { mutating func f() {} func g() {} var mutating_property : Int { mutating get {} set {} } var nonmutating_property : Int { get {} nonmutating set {} } // This property has a mutating getter and !mutating setter. var weird_property : Int { mutating get {} nonmutating set {} } @mutating func mutating_attr() {} // expected-error {{'mutating' is a declaration modifier, not an attribute}} {{3-4=}} @nonmutating func nonmutating_attr() {} // expected-error {{'nonmutating' is a declaration modifier, not an attribute}} {{3-4=}} } func test_mutability() { // Non-mutable method on rvalue is ok. TestMutableStruct().g() // Non-mutable method on let is ok. let x = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x.g() // Mutable methods on let and rvalue are not ok. x.f() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} TestMutableStruct().f() // expected-error {{cannot use mutating member on immutable value: function call returns immutable value}} _ = TestMutableStruct().weird_property // expected-error {{cannot use mutating getter on immutable value: function call returns immutable value}} let tms = TestMutableStruct() // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} _ = tms.weird_property // expected-error {{cannot use mutating getter on immutable value: 'tms' is a 'let' constant}} } func test_arguments(_ a : Int, b : Int, let c : Int) { // expected-error {{'let' as a parameter attribute is not allowed}} {{21-25=}} var b = b a = 1 // expected-error {{cannot assign to value: 'a' is a 'let' constant}} b = 2 // ok. _ = b } protocol ClassBoundProtocolMutating : class { mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func f() } protocol MutatingTestProto { mutating func mutatingfunc() func nonmutatingfunc() // expected-note {{protocol requires}} } class TestClass : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct1 : MutatingTestProto { func mutatingfunc() {} // Ok, doesn't need to be mutating. func nonmutatingfunc() {} } struct TestStruct2 : MutatingTestProto { mutating func mutatingfunc() {} // Ok, can be mutating. func nonmutatingfunc() {} } struct TestStruct3 : MutatingTestProto { // expected-error {{type 'TestStruct3' does not conform to protocol 'MutatingTestProto'}} func mutatingfunc() {} // This is not ok, "nonmutatingfunc" doesn't allow mutating functions. mutating func nonmutatingfunc() {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } // <rdar://problem/16722603> invalid conformance of mutating setter protocol NonMutatingSubscriptable { subscript(i: Int) -> Int {get nonmutating set} // expected-note {{protocol requires subscript with type '(Int) -> Int'}} } struct MutatingSubscriptor : NonMutatingSubscriptable { // expected-error {{type 'MutatingSubscriptor' does not conform to protocol 'NonMutatingSubscriptable'}} subscript(i: Int) -> Int { get { return 42 } mutating set {} // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } } protocol NonMutatingGet { var a: Int { get } // expected-note {{protocol requires property 'a' with type 'Int'}} } struct MutatingGet : NonMutatingGet { // expected-error {{type 'MutatingGet' does not conform to protocol 'NonMutatingGet'}} var a: Int { mutating get { return 0 } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } func test_properties() { let rvalue = TestMutableStruct() // expected-note 4 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} {{3-6=var}} {{3-6=var}} markUsed(rvalue.nonmutating_property) // ok markUsed(rvalue.mutating_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} markUsed(rvalue.weird_property) // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.nonmutating_property = 1 // ok rvalue.mutating_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} rvalue.weird_property = 1 // expected-error {{cannot use mutating getter on immutable value: 'rvalue' is a 'let' constant}} var lvalue = TestMutableStruct() markUsed(lvalue.mutating_property) // ok markUsed(lvalue.nonmutating_property) // ok markUsed(lvalue.weird_property) // ok lvalue.mutating_property = 1 // ok lvalue.nonmutating_property = 1 // ok lvalue.weird_property = 1 // ok } protocol OpaqueBase {} extension OpaqueBase { var x: Int { get { return 0 } set { } } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} } protocol OpaqueRefinement : class, OpaqueBase { var x: Int { get set } // expected-note {{protocol requires property 'x' with type 'Int'}} } class SetterMutatingConflict : OpaqueRefinement {} // expected-error {{type 'SetterMutatingConflict' does not conform to protocol 'OpaqueRefinement'}} struct DuplicateMutating { mutating mutating func f() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} } protocol SubscriptNoGetter { subscript (i: Int) -> Int { get } } func testSubscriptNoGetter(let iis: SubscriptNoGetter) { // expected-error {{'let' as a parameter attribute is not allowed}}{{28-31=}} var _: Int = iis[17] } func testSelectorStyleArguments1(_ x: Int, bar y: Int) { var x = x var y = y x += 1 y += 1 _ = x _ = y } func testSelectorStyleArguments2(let x: Int, // expected-error {{'let' as a parameter attribute is not allowed}}{{34-37=}} let bar y: Int) { // expected-error {{'let' as a parameter attribute is not allowed}}{{34-38=}} } func testSelectorStyleArguments3(_ x: Int, bar y: Int) { ++x // expected-error {{cannot pass immutable value to mutating operator: 'x' is a 'let' constant}} ++y // expected-error {{cannot pass immutable value to mutating operator: 'y' is a 'let' constant}} } func invalid_inout(inout var x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{26-30=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}}{{20-25=}}{{34-34=inout }} } func invalid_var(var x: Int) { // expected-error {{parameters may not have the 'var' specifier}}{{18-21=}} {{1-1= var x = x\n}} } func takesClosure(_: (Int) -> Int) { takesClosure { (var d) in d } // expected-error {{parameters may not have the 'var' specifier}} } func updateInt(_ x : inout Int) {} // rdar://15785677 - allow 'let' declarations in structs/classes be initialized in init() class LetClassMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } struct LetStructMembers { let a : Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} let b : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(arg : Int) { a = arg // ok, a is mutable in init() updateInt(&a) // ok, a is mutable in init() and has been initialized b = 17 // ok, b is mutable in init() } func f() { a = 42 // expected-error {{cannot assign to property: 'a' is a 'let' constant}} b = 42 // expected-error {{cannot assign to property: 'b' is a 'let' constant}} updateInt(&a) // expected-error {{cannot pass immutable value as inout argument: 'a' is a 'let' constant}} } } func QoI() { let x = 97 // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} x = 17 // expected-error {{cannot assign to value: 'x' is a 'let' constant}} var get_only: Int { get { return 7 } } get_only = 92 // expected-error {{cannot assign to value: 'get_only' is a get-only property}} } // <rdar://problem/17051675> Structure initializers in an extension cannot assign to constant properties struct rdar17051675_S { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S { init(newY: Int) { x = 42 } } struct rdar17051675_S2<T> { let x : Int init(newX: Int) { x = 42 } } extension rdar17051675_S2 { init(newY: Int) { x = 42 } } // <rdar://problem/17400366> let properties should not be mutable in convenience initializers class ClassWithConvenienceInit { let x : Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(newX: Int) { x = 42 } convenience init(newY: Int) { self.init(newX: 19) x = 67 // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } } struct StructWithDelegatingInit { let x: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} init(x: Int) { self.x = x } init() { self.init(x: 0); self.x = 22 } // expected-error {{cannot assign to property: 'x' is a 'let' constant}} } func test_recovery_missing_name_2(let: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}}{{35-38=}} // expected-error @-1 2{{expected ',' separator}} {{38-38=,}} expected-error @-1 2 {{expected parameter name followed by ':'}} // <rdar://problem/16792027> compiler infinite loops on a really really mutating function struct F { // expected-note 2 {{in declaration of 'F'}} mutating mutating mutating f() { // expected-error 2 {{duplicate modifier}} expected-note 2 {{modifier already specified here}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error 2 {{expected declaration}} } mutating nonmutating func g() { // expected-error {{method may not be declared both mutating and nonmutating}} {{12-24=}} } } protocol SingleIntProperty { var i: Int { get } } struct SingleIntStruct : SingleIntProperty { let i: Int // expected-note {{change 'let' to 'var' to make it mutable}} {{3-6=var}} } extension SingleIntStruct { init(_ other: SingleIntStruct) { other.i = 999 // expected-error {{cannot assign to property: 'i' is a 'let' constant}} } } // <rdar://problem/19370429> QoI: fixit to add "mutating" when assigning to a member of self in a struct // <rdar://problem/17632908> QoI: Modifying struct member in non-mutating function produces difficult to understand error message struct TestSubscriptMutability { let let_arr = [1,2,3] // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_arr = [1,2,3] func nonmutating1() { let_arr[1] = 1 // expected-error {{cannot assign through subscript: 'let_arr' is a 'let' constant}} } func nonmutating2() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} var_arr[1] = 1 // expected-error {{cannot assign through subscript: 'self' is immutable}} } func nonmutating3() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self = TestSubscriptMutability() // expected-error {{cannot assign to value: 'self' is immutable}} } subscript(a : Int) -> TestSubscriptMutability { return TestSubscriptMutability() } func test() { self[1] = TestSubscriptMutability() // expected-error {{cannot assign through subscript: subscript is get-only}} self[1].var_arr = [] // expected-error {{cannot assign to property: subscript is get-only}} self[1].let_arr = [] // expected-error {{cannot assign to property: 'let_arr' is a 'let' constant}} } } func f(_ a : TestSubscriptMutability) { a.var_arr = [] // expected-error {{cannot assign to property: 'a' is a 'let' constant}} } struct TestSubscriptMutability2 { subscript(a : Int) -> Int { get { return 42 } set {} } func test() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} self[1] = 2 // expected-error {{cannot assign through subscript: 'self' is immutable}} } } struct TestBangMutability { let let_opt = Optional(1) // expected-note 2 {{change 'let' to 'var' to make it mutable}} {{3-6=var}} {{3-6=var}} var var_opt = Optional(1) func nonmutating1() { // expected-note {{mark method 'mutating' to make 'self' mutable}} {{3-3=mutating }} let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // expected-error {{cannot assign through '!': 'self' is immutable}} self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } mutating func nonmutating2() { let_opt! = 1 // expected-error {{cannot assign through '!': 'let_opt' is a 'let' constant}} var_opt! = 1 // ok self[]! = 2 // expected-error {{cannot assign through '!': subscript is get-only}} } subscript() -> Int? { return nil } } // <rdar://problem/21176945> mutation through ? not considered a mutation func testBindOptional() { var a : TestStruct2? = nil // Mutated through optional chaining. a?.mutatingfunc() } struct HasTestStruct2 { var t = TestStruct2() } func testConditional(b : Bool) { var x = TestStruct2() var y = TestStruct2() var z = HasTestStruct2() (b ? x : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? (b ? x : y) : y).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : (b ? x : y)).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} (b ? x : z.t).mutatingfunc() // expected-error {{cannot use mutating member on immutable value: result of conditional operator '? :' is never mutable}} } // <rdar://problem/27384685> QoI: Poor diagnostic when assigning a value to a method func f(a : FooClass, b : LetStructMembers) { a.baz = 1 // expected-error {{cannot assign to property: 'baz' is a method}} b.f = 42 // expected-error {{cannot assign to property: 'f' is a method}} }
35.28125
262
0.640144
ab000e1d70d836c1f9348bfcf83a7df90cc8112f
899
// // swiftDemoTests.swift // swiftDemoTests // // Created by Mr.Zhang on 2021/7/17. // import XCTest @testable import swiftDemo class swiftDemoTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.441176
111
0.664071
9b2a8f3ffdd5047ce92751af6eae8a2457a5419b
798
//: Playground - noun: a place where people can play import UIKit import XCPlayground var str = "Hello, playground" var label = UILabel(frame: CGRectMake(0, 0, 200, 63)) // The text is tailed with ... at the end of first line label.text = "This appendix shows how to use the Auto Layout visual format language to specify common constraints, including standard spacing and dimensions, vertical layout, and constraints with different priorities. In addition, this appendix contains a complete language grammar." // The text will be word wrapped and tailed at the end of third line label.numberOfLines = 3 // Same result as above, but this is the prefer way, because sometimes you don't need to care about how many lines acturally. label.numberOfLines = 0 label.adjustsFontSizeToFitWidth = true
42
283
0.775689
5d92a353ad3a1a5d0b46f69e7881c8746cd8188f
3,777
// // UIColor+Yep.swift // Yep // // Created by NIX on 15/3/16. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit extension UIColor { class func yepTintColor() -> UIColor { return UIColor(red: 50/255.0, green: 167/255.0, blue: 255/255.0, alpha: 1.0) } class func yepMessageColor() -> UIColor { return UIColor(red: 64/255.0, green: 64/255.0, blue: 64/255.0, alpha: 1.0) } class func yepNavgationBarTitleColor() -> UIColor { return UIColor(red: 0.247, green: 0.247, blue: 0.247, alpha: 1.0) } class func yepViewBackgroundColor() -> UIColor { return UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 1.0) } class func yepInputTextColor() -> UIColor { return UIColor(red: 0.557, green: 0.557, blue: 0.576, alpha: 1.0) } class func yepMessageToolbarSubviewBorderColor() -> UIColor { return UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) } class func yepBorderColor() -> UIColor { return UIColor(red: 0.898, green: 0.898, blue: 0.898, alpha: 1) } class func avatarBackgroundColor() -> UIColor { return UIColor(red: 50/255.0, green: 167/255.0, blue: 255/255.0, alpha: 0.3) } class func leftBubbleTintColor() -> UIColor { return UIColor(white: 231 / 255.0, alpha: 1.0) } class func rightBubbleTintColor() -> UIColor { return UIColor.yepTintColor() } class func leftWaveColor() -> UIColor { return UIColor.darkGray.withAlphaComponent(0.2) } class func rightWaveColor() -> UIColor { return UIColor(red:0.176, green:0.537, blue:0.878, alpha:1) } class func skillMasterColor() -> UIColor { return yepTintColor() } class func skillLearningColor() -> UIColor { return UIColor(red:0.49, green:0.83, blue:0.13, alpha:1) } class func messageToolBarColor() -> UIColor { return UIColor(red:0.557, green:0.557, blue:0.576, alpha:1) } class func messageToolBarHighlightColor() -> UIColor { return UIColor.yepTintColor() } class func messageToolBarNormalColor() -> UIColor { return UIColor.lightGray } class func yepDisabledColor() -> UIColor { return UIColor(red:0.95, green:0.95, blue:0.95, alpha:1) } class func yepGrayColor() -> UIColor { return UIColor(red: 142.0/255.0, green: 142.0/255.0, blue: 147.0/255.0, alpha: 1.0) } class func yepBackgroundColor() -> UIColor { return UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) } class func yepCellSeparatorColor() -> UIColor { return UIColor.lightGray.withAlphaComponent(0.3) } class func yepCellAccessoryImageViewTintColor() -> UIColor { return UIColor.lightGray } class func yepIconImageViewTintColor() -> UIColor { return yepCellAccessoryImageViewTintColor() } } extension UIColor { class func yep_mangmorGrayColor() -> UIColor { return UIColor(red: 199/255.0, green: 199/255.0, blue: 204/255.0, alpha: 1) } } extension UIColor { // 反色 var yep_inverseColor: UIColor { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return UIColor(red: 1 - red, green: 1 - green, blue: 1 - blue, alpha: alpha) } // 黑白色 var yep_binaryColor: UIColor { var white: CGFloat = 0 getWhite(&white, alpha: nil) return white > 0.92 ? UIColor.black : UIColor.white } var yep_profilePrettyColor: UIColor { //return yep_inverseColor return yep_binaryColor } }
26.598592
91
0.611861
6a37c503bfaf7ab22672feb32ee8fe763b9e745d
570
#if os(macOS) import AppKit #else import UIKit #endif internal protocol DeclarativeProtocolInternal { var _properties: PropertiesInternal { get set } var __height: State<CGFloat> { get } var __width: State<CGFloat> { get } var __top: State<CGFloat> { get } var __leading: State<CGFloat> { get } var __left: State<CGFloat> { get } var __trailing: State<CGFloat> { get } var __right: State<CGFloat> { get } var __bottom: State<CGFloat> { get } var __centerX: State<CGFloat> { get } var __centerY: State<CGFloat> { get } }
27.142857
51
0.666667
759872726c8eaef2c1c040834aa62bb9db62d90a
450
// // LoadingView.swift // Dollar // // Created by Daniil Belikov on 01.09.2021. // Copyright © 2021 belikov.dev. All rights reserved. // import SwiftUI struct LoadingView: View { var body: some View { ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: .white)) } } struct LoadingView_Previews: PreviewProvider { static var previews: some View { LoadingView() } }
16.666667
71
0.628889
7a23a314ea5cdc19b529b89aa7f2e2db8ff3d823
889
// // CLCTests.swift // SwiftNesTests // // Created by Tibor Bodecs on 2021. 09. 12.. // import XCTest @testable import SwiftNes final class CLCTests: XCTestCase { private func testUnchangedRegisterFlags(_ nes: Nes) { XCTAssertFalse(nes.cpu.registers.signFlag) XCTAssertFalse(nes.cpu.registers.interruptFlag) XCTAssertFalse(nes.cpu.registers.decimalFlag) XCTAssertFalse(nes.cpu.registers.breakFlag) XCTAssertFalse(nes.cpu.registers.overflowFlag) } func testClearFlag() throws { let nes = Nes() nes.cpu.registers.carryFlag = true nes.memory.storage[0x00] = nes.cpu.opcode(.clc, .implicit) let cycles = 2 nes.start(cycles: cycles) XCTAssertFalse(nes.cpu.registers.carryFlag) testUnchangedRegisterFlags(nes) XCTAssertEqual(nes.cpu.totalCycles, cycles) } }
26.939394
66
0.671541
d6841b50535e0ec6b1f051e22b300adc4dac3d82
1,087
// // RegisterFlow.swift // GigyaNss // // Created by Shmuel, Sagi on 25/02/2020. // Copyright © 2020 Gigya. All rights reserved. // import Gigya import Flutter class RegisterAction<T: GigyaAccountProtocol>: Action<T> { init(busnessApi: BusinessApiDelegate) { super.init() self.busnessApi = busnessApi } override func next(method: ApiChannelEvent, params: [String: Any]?) { super.next(method: method, params: params) switch method { case .submit: var exportedParams = params let email = params?["email"] as? String ?? "" let password = params?["password"] as? String ?? "" exportedParams?.removeValue(forKey: "email") exportedParams?.removeValue(forKey: "password") busnessApi?.callRegister(dataType: T.self, email: email, password: password, params: exportedParams!, completion: delegate!.getMainLoginClosure(obj: T.self)) default: break } } deinit { GigyaLogger.log(with: self, message: "deinit") } }
26.512195
169
0.616375
20c1bed7270b4b0910bdfb6588d8a4cbd223be1c
1,833
// // AppDelegate.swift // Swift_CoreData_MVVM // // Created by Ares on 19/10/2019. // Copyright © 2019 haochen. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last { print("ulrString =" + url.absoluteString) } return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { } func applicationWillTerminate(_ application: UIApplication) { saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "Swift_CoreData_MVVM") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
29.095238
177
0.708674
d9c72badef18cacead2d581e43063e10a8305ae0
579
// // UIScrollViewExtensionsTest.swift // SwifterSwift // // Created by camila oliveira on 22/04/18. // Copyright © 2018 SwifterSwift // import XCTest @testable import SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit final class UIScrollViewExtensionsTest: XCTestCase { func testSnapshot() { let frame = CGRect(x: 0, y: 0, width: 100, height: 100) let scroll = UIScrollView(frame: frame) scroll.contentSize = frame.size let snapshot = scroll.snapshot XCTAssertNotNil(snapshot) let view = UIScrollView() XCTAssertNil(view.snapshot) } } #endif
21.444444
57
0.73057
0a1b704a4b7b116dc3c53692b9f6520fc9f6336d
2,126
// // RowingHeartRateBeltInformation.swift // Pods // // Created by Jesse Curry on 10/27/15. // Edited by Paul Aschmann on 08/06/2020 // import CoreData struct RowingHeartRateBeltInformation: CharacteristicModel, CustomDebugStringConvertible { let DataLength = 6 /* Manufacturer ID, Device Type, Belt ID Lo, Belt ID Mid Lo, Belt ID Mid Hi, Belt ID Hi */ var manufacturerID:C2HeartRateBeltManufacturerID var deviceType:C2HeartRateBeltType var beltID:C2HeartRateBeltID init(fromData data: NSData) { var arr:[UInt8] = Array(repeating: 0, count: DataLength); data.getBytes(&arr, length: DataLength) manufacturerID = C2HeartRateBeltManufacturerID(arr[0]) deviceType = C2HeartRateBeltType(arr[1]) beltID = C2HeartRateBeltID( heartRateBeltIDWithLow: UInt32(arr[2]), midLow: UInt32(arr[3]), midHigh: UInt32(arr[4]), high: UInt32(arr[5])) } // MARK: PerformanceMonitor func updatePerformanceMonitor(performanceMonitor:PerformanceMonitor) { performanceMonitor.manufacturerID.value = manufacturerID performanceMonitor.deviceType.value = deviceType performanceMonitor.beltID.value = beltID } // MARK: - var debugDescription:String { return "[RowingHeartRateBeltInformation]" } } /* NSData extension to allow writing of this value */ extension NSData { convenience init(rowingHeartRateBeltInformation:RowingHeartRateBeltInformation) { let arr:[UInt8] = [ UInt8(rowingHeartRateBeltInformation.manufacturerID), UInt8(rowingHeartRateBeltInformation.deviceType), UInt8(0xFF & (rowingHeartRateBeltInformation.manufacturerID)), UInt8(0xFF & (rowingHeartRateBeltInformation.manufacturerID >> 8)), UInt8(0xFF & (rowingHeartRateBeltInformation.manufacturerID >> 16)), UInt8(0xFF & (rowingHeartRateBeltInformation.manufacturerID >> 24)) ]; self.init(bytes: arr, length: arr.count * MemoryLayout<UInt8>.size) } }
32.212121
90
0.673565
ff0412a86c7aecb32f6ff9223e5475f440475db9
20,264
// // PeerConnectionManager.swift // PeerConnectivity // // Created by Reid Chatham on 12/23/15. // Copyright © 2015 Reid Chatham. All rights reserved. // import UIKit /** The service type describing the channel over which connections are made. */ public typealias ServiceType = String /** Struct representing specified keys for configuring a connection manager. */ public struct PeerConnectivityKeys { static fileprivate let CertificateListener = "CertificateRecievedListener" } /** Enum represeting available connection types. `.automatic`, `.inviteOnly`, `.custom`. */ public enum PeerConnectionType : Int { /** Connection type where all available devices attempt to connect automatically. */ case automatic = 0 /** Connection type providing the browser view controller and advertiser assistant giving the user the ability to handle connections with nearby peers. */ case inviteOnly /** No default connection implementation is given allowing full control for determining approval of connections using custom algorithms. */ case custom } /** Functional wrapper for Apple's MultipeerConnectivity framework. Initialize a PeerConnectionManager to enable mesh-networking over bluetooth and wifi when available. Configure the networking protocol of the session and then start to begin connecting to nearby peers. */ public class PeerConnectionManager { // MARK: Static /** Access to shared connection managers by their service type. */ public fileprivate(set) static var shared : [ServiceType:PeerConnectionManager] = [:] // MARK: Properties /** The connection type for the connection manager. (ex. `.automatic`, `.inviteOnly`, `.custom`) */ public let connectionType : PeerConnectionType /** Access to the local peer representing the user. */ public let peer : Peer /** Returns the peers that are connected on the current session. */ public var connectedPeers : [Peer] { return session.connectedPeers } /** Nearby peers available for connecting. - Note: Can be observed by listening for PeerConnectivityEvent.nearbyPeersChanged(foundPeers:). */ public fileprivate(set) var foundPeers: [Peer] = [] { didSet { observer.value = .nearbyPeersChanged(foundPeers: foundPeers) } } // Private fileprivate let serviceType : ServiceType fileprivate let observer = MultiObservable<PeerConnectionEvent>(.ready) fileprivate let sessionObserver = Observable<PeerSessionEvent>(.none) fileprivate let browserObserver = Observable<PeerBrowserEvent>(.none) fileprivate let browserViewControllerObserver = Observable<PeerBrowserViewControllerEvent>(.none) fileprivate let advertiserObserver = Observable<PeerAdvertiserEvent>(.none) fileprivate let advertiserAssisstantObserver = Observable<PeerAdvertiserAssisstantEvent>(.none) fileprivate let sessionEventProducer : PeerSessionEventProducer fileprivate let browserEventProducer : PeerBrowserEventProducer fileprivate let browserViewControllerEventProducer : PeerBrowserViewControllerEventProducer fileprivate let advertiserEventProducer : PeerAdvertiserEventProducer fileprivate let advertiserAssisstantEventProducer : PeerAdvertiserAssisstantEventProducer fileprivate let session : PeerSession fileprivate let browser : PeerBrowser fileprivate let browserAssisstant : PeerBrowserAssisstant fileprivate let advertiser : PeerAdvertiser fileprivate let advertiserAssisstant : PeerAdvertiserAssisstant fileprivate let responder : PeerConnectionResponder // MARK: Initializer /** Initializer for a connection manager. Requires the requested service type. If the connectionType and displayName are not specified the connection manager defaults to .Automatic and using the local device name. - parameter serviceType: The requested service type describing the channel on which peers are able to connect. - parameter connectionType: Takes a PeerConnectionType case determining the default behavior of the framework. - parameter displayName: The local user's display name to other peers. - Returns: A fully initialized `PeerConnectionManager`. */ public init(serviceType: ServiceType, connectionType: PeerConnectionType = .automatic, displayName: String = UIDevice.current.name) { self.connectionType = connectionType self.serviceType = serviceType self.peer = Peer(displayName: displayName) sessionEventProducer = PeerSessionEventProducer(observer: sessionObserver) browserEventProducer = PeerBrowserEventProducer(observer: browserObserver) browserViewControllerEventProducer = PeerBrowserViewControllerEventProducer(observer: browserViewControllerObserver) advertiserEventProducer = PeerAdvertiserEventProducer(observer: advertiserObserver) advertiserAssisstantEventProducer = PeerAdvertiserAssisstantEventProducer(observer: advertiserAssisstantObserver) session = PeerSession(peer: peer, eventProducer: sessionEventProducer) browser = PeerBrowser(session: session, serviceType: serviceType, eventProducer: browserEventProducer) browserAssisstant = PeerBrowserAssisstant(session: session, serviceType: serviceType, eventProducer: browserViewControllerEventProducer) advertiser = PeerAdvertiser(session: session, serviceType: serviceType, eventProducer: advertiserEventProducer) advertiserAssisstant = PeerAdvertiserAssisstant(session: session, serviceType: serviceType, eventProducer: advertiserAssisstantEventProducer) responder = PeerConnectionResponder(observer: observer) // Currently checking security certificates is not yet supported. responder.addListener({ (event) in switch event { case .receivedCertificate(peer: _, certificate: _, handler: let handler): //print("PeerConnectionManager: listenOn: certificateReceived") handler(true) default: break } }, forKey: PeerConnectivityKeys.CertificateListener) // Prevent mingling signals from the same device if let existing = PeerConnectionManager.shared[serviceType] { existing.stop() existing.removeAllListeners() PeerConnectionManager.shared[serviceType] = self } } deinit { stop() removeAllListeners() if let existing = PeerConnectionManager.shared[serviceType], existing === self { PeerConnectionManager.shared.removeValue(forKey: serviceType) } } } extension PeerConnectionManager { // MARK: Using the PeerConnectionManager /** Start the connection manager with optional completion. Calling this initiates browsing and advertising using the specified connection type. - parameter completion: Called once session is initialized. Default is `nil`. */ public func start(_ completion: ((Void)->Void)? = nil) { browserObserver.addObserver { [weak self] event in switch event { case .foundPeer(let peer): self?.observer.value = .foundPeer(peer: peer) case .lostPeer(let peer): self?.observer.value = .lostPeer(peer: peer) case .didNotStartBrowsingForPeers(let error): self?.observer.value = .error(error) default: break } } advertiserObserver.addObserver { [weak self] event in switch event { case.didReceiveInvitationFromPeer(peer: let peer, withContext: let context, invitationHandler: let invite): let invitationReceiver = { [weak self] (accept: Bool) -> Void in guard let session = self?.session else { return } invite(accept, session) } self?.observer.value = .receivedInvitation(peer: peer, withContext: context, invitationHandler: invitationReceiver) case .didNotStartAdvertisingPeer(let error): self?.observer.value = .error(error) default: break } } sessionObserver.addObserver { [weak self] event in switch event { case .devicesChanged(peer: let peer): guard let connectedPeers = self?.connectedPeers else { break } self?.observer.value = .devicesChanged(peer: peer, connectedPeers: connectedPeers) case .didReceiveData(peer: let peer, data: let data): self?.observer.value = .receivedData(peer: peer, data: data) guard let eventInfo = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String:Any] else { return } self?.observer.value = .receivedEvent(peer: peer, eventInfo: eventInfo) case .didReceiveCertificate(peer: let peer, certificate: let certificate, handler: let handler): self?.observer.value = .receivedCertificate(peer: peer, certificate: certificate, handler: handler) case .didReceiveStream(peer: let peer, stream: let stream, name: let name): self?.observer.value = .receivedStream(peer: peer, stream: stream, name: name) case .startedReceivingResource(peer: let peer, name: let name, progress: let progress): self?.observer.value = .startedReceivingResource(peer: peer, name: name, progress: progress) case .finishedReceivingResource(peer: let peer, name: let name, url: let url, error: let error): self?.observer.value = .finishedReceivingResource(peer: peer, name: name, url: url, error: error) default: break } } browserObserver.addObserver { [weak self] event in DispatchQueue.main.async { switch event { case .foundPeer(let peer): guard let peers = self?.foundPeers , !peers.contains(peer) else { break } self?.foundPeers.append(peer) case .lostPeer(let peer): guard let index = self?.foundPeers.index(of: peer) else { break } self?.foundPeers.remove(at: index) default: break } } } sessionObserver.addObserver { [weak self] event in DispatchQueue.main.async { guard let peerCount = self?.connectedPeers.count else { return } switch event { case .devicesChanged(peer: let peer) where peerCount <= 0 : switch peer.status { case .notConnected: self?.refresh() default: break } default: break } } } switch connectionType { case .automatic: browserObserver.addObserver { [unowned self] event in DispatchQueue.main.async { switch event { case .foundPeer(let peer): self.browser.invitePeer(peer) default: break } } } advertiserObserver.addObserver { [unowned self] event in DispatchQueue.main.async { switch event { case .didReceiveInvitationFromPeer(peer: _, withContext: _, invitationHandler: let handler): handler(true, self.session) self.advertiser.stopAdvertising() default: break } } } case .inviteOnly: advertiserAssisstant.startAdvertisingAssisstant() case .custom: break } session.startSession() browser.startBrowsing() advertiser.startAdvertising() observer.value = .started completion?() } /** Returns a browser view controller if the connectionType was set to `.InviteOnly` or returns `nil` if not. - parameter callback: Events sent back with cases `.DidFinish` and `.DidCancel`. - Returns: A browser view controller for inviting available peers nearby if connection type is `.InviteOnly` or `nil` otherwise. */ public func browserViewController(_ callback: @escaping (PeerBrowserViewControllerEvent)->Void) -> UIViewController? { browserViewControllerObserver.addObserver { callback($0) } switch connectionType { case .inviteOnly: return browserAssisstant.peerBrowserViewController() default: return nil } } /** Use to invite peers that have been found locally to join a MultipeerConnectivity session. - parameter peer: `Peer` object to invite to current session. - parameter withContext: `Data` object associated with the invitation. - parameter timeout: Time interval until the invitation expires. */ public func invitePeer(_ peer: Peer, withContext context: Data? = nil, timeout: TimeInterval = 30) { browser.invitePeer(peer, withContext: context, timeout: timeout) } /** Send data to connected users. If no peer is specified it broadcasts to all users on a current session. - parameter data: Data to be sent to specified peers. - parameter toPeers: Specified `Peer` objects to send data. */ public func sendData(_ data: Data, toPeers peers: [Peer] = []) { session.sendData(data, toPeers: peers) } /** Send events to connected users. Encoded as Data using the NSKeyedArchiver. If no peer is specified it broadcasts to all users on a current session. - parameter eventInfo: Dictionary of Any data which is encoded with the NSKeyedArchiver and passed to the specified peers. - parameter toPeers: Specified `Peer` objects to send event. */ public func sendEvent(_ eventInfo: [String:Any], toPeers peers: [Peer] = []) { let eventData = NSKeyedArchiver.archivedData(withRootObject: eventInfo) session.sendData(eventData, toPeers: peers) } /** Send a data stream to a connected user. This method throws an error if the stream cannot be established. This method returns the NSOutputStream with which you can send events to the connected users. - parameter streamName: The name of the stream to be established between two users. - parameter toPeer: The peer with which to start a data stream - Throws: Propagates errors thrown by Apple's MultipeerConnectivity framework. - Returns: The OutputStream for sending information to the specified `Peer` object. */ public func sendDataStream(streamName name: String, toPeer peer: Peer) throws -> OutputStream { do { return try session.sendDataStream(name, toPeer: peer) } catch let error { throw error } } /** Send a resource with a specified url for retrieval on a connected device. This method can send a resource to multiple peers and returns an Progress associated with each Peer. This method takes an error completion handler if the resource fails to send. - parameter resourceURL: The url that the resource will be passed with for retrieval. - parameter withName: The name with which the progress is associated with. - parameter toPeers: The specified peers for the resource to be sent to. - parameter withCompletionHandler: the completion handler called when an error is thrown sending a resource. - Returns: A dictionary of optional Progress associated with each peer that the resource was sent to. */ public func sendResourceAtURL(_ resourceURL: URL, withName name: String, toPeers peers: [Peer] = [], withCompletionHandler completion: ((Error?) -> Void)? ) -> [Peer:Progress?] { var progress : [Peer:Progress?] = [:] let peers = (peers.isEmpty) ? self.connectedPeers : peers for peer in peers { progress[peer] = session.sendResourceAtURL(resourceURL, withName: name, toPeer: peer, withCompletionHandler: completion) } return progress } /** Refresh the current session. This call disconnects the user from the current session and then restarts the session with completion maintaing the current sessions configuration. - parameter completion: Completion handler called after the session has completed refreshing. */ public func refresh(_ completion: ((Void)->Void)? = nil) { stop() start(completion) } /** Stop the current connection manager from listening to delegate callbacks and disconnects from the current session. */ public func stop() { observer.value = .ended session.stopSession() browser.stopBrowsing() advertiser.stopAdvertising() advertiserAssisstant.stopAdvertisingAssisstant() foundPeers = [] sessionObserver.observers = [] browserObserver.observers = [] advertiserObserver.observers = [] advertiserAssisstantObserver.observers = [] browserViewControllerObserver.observers = [] sessionObserver.value = .none browserObserver.value = .none advertiserObserver.value = .none advertiserAssisstantObserver.value = .none browserViewControllerObserver.value = .none observer.value = .ready } /** Close session for browsing peers to invite. */ public func closeSession() { browser.stopBrowsing() } /** Open session for browsing peers to invite. */ public func openSession() { browser.startBrowsing() } } extension PeerConnectionManager { // MARK: Listening to PeerConnectivity generated events /** Takes a `PeerConnectionEventListener` to respond to events. - parameter listener: Takes a `PeerConnectionEventListener`. - parameter performListenerInBackground: Default is `false`. Set to `true` to perform the listener asyncronously. - parameter withKey: The key with which to associate the listener. */ public func listenOn(_ listener: @escaping PeerConnectionEventListener, performListenerInBackground background: Bool = false, withKey key: String) { switch background { case true: responder.addListener(listener, forKey: key) case false: responder.addListener({ (event) in DispatchQueue.main.async(execute: { listener(event) }) }, forKey: key) } } /** Takes a key to register the callback and calls the listener when an event is recieved and also passes back the `Peer` that sent it. - parameter key: `String` key with which to keep track of the listener for later removal. - parameter listener: Callback that returns the event info and the `Peer` whenever an event is received. */ public func observeEventListenerForKey(_ key: String, listener: @escaping ([String:Any], Peer)->Void) { responder.addListener({ (event) in switch event { case .receivedEvent(let peer, let eventInfo): listener(eventInfo, peer) default: break } }, forKey: key) } /** Remove a listener associated with a specified key. - parameter key: The key with which to attempt to find and remove a listener with. */ public func removeListenerForKey(_ key: String) { responder.removeListenerForKey(key) } /** Remove all listeners. */ public func removeAllListeners() { responder.removeAllListeners() } }
42.128898
256
0.653129
28fb4581f80ffba8ba3e940ed5c17e2bdd4c87d4
3,166
// // Copyright (c) 2020 Arpit Lokwani // // 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 AVKit //------------------------------------------------------------------------------------------------------------------------------------------------- class VideoView: UIViewController { private var url: URL! private var controller: AVPlayerViewController? //--------------------------------------------------------------------------------------------------------------------------------------------- init(url: URL) { super.init(nibName: nil, bundle: nil) self.url = url self.isModalInPresentation = true self.modalPresentationStyle = .fullScreen } //--------------------------------------------------------------------------------------------------------------------------------------------- init(path: String) { super.init(nibName: nil, bundle: nil) self.url = URL(fileURLWithPath: path) self.isModalInPresentation = true self.modalPresentationStyle = .fullScreen } //--------------------------------------------------------------------------------------------------------------------------------------------- required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() let notification = NSNotification.Name.AVPlayerItemDidPlayToEndTime NotificationCenter.addObserver(target: self, selector: #selector(actionDone), name: notification.rawValue) } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, policy: .default, options: .defaultToSpeaker) controller = AVPlayerViewController() controller?.player = AVPlayer(url: url) controller?.player?.play() if (controller != nil) { addChild(controller!) view.addSubview(controller!.view) controller!.view.frame = view.frame } } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.removeObserver(target: self) } // MARK: - User actions //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionDone() { dismiss(animated: true) } }
35.177778
147
0.47031
e8ab785e318e7ecd59474422679eec94ba1b53a1
352
// // ViewController.swift // WJDetailHeaderView // // Created by liuwj on 2019/6/12. // Copyright © 2019 liuwj. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
16.761905
80
0.670455
9cb79913bc46cbc9ca3afb39357b9d6ee2cee93f
2,222
// // QuadExtension.swift // ReceiptScanner // // Created by Kamil Wyszomierski on 28/10/2019. // Copyright © 2019 Kamil Wyszomierski. All rights reserved. // import KWFoundation import Vision extension Quad { init(observation: VNRectangleObservation, orientation: CGImagePropertyOrientation) { let topLeftObservation = Point(cameraPoint: observation.topLeft, orientation: orientation) let bottomLeftObservation = Point(cameraPoint: observation.bottomLeft, orientation: orientation) let bottomRightObservation = Point(cameraPoint: observation.bottomRight, orientation: orientation) let topRightObservation = Point(cameraPoint: observation.topRight, orientation: orientation) var topLeft = topLeftObservation var bottomLeft = bottomLeftObservation var bottomRight = bottomRightObservation var topRight = topRightObservation switch orientation { case .down: topLeft = topRightObservation bottomLeft = topLeftObservation bottomRight = bottomLeftObservation topRight = bottomRightObservation case .downMirrored: topLeft = topLeftObservation bottomLeft = topRightObservation bottomRight = bottomRightObservation topRight = bottomLeftObservation case .left: // This one isn't used. break case .leftMirrored: topLeft = topRightObservation bottomLeft = bottomRightObservation bottomRight = bottomLeftObservation topRight = topLeftObservation case .right: topLeft = topLeftObservation bottomLeft = bottomLeftObservation bottomRight = bottomRightObservation topRight = topRightObservation case .rightMirrored: // This one isn't used. break case .up: topLeft = bottomLeftObservation bottomLeft = bottomRightObservation bottomRight = topRightObservation topRight = topLeftObservation case .upMirrored: topLeft = bottomRightObservation bottomLeft = bottomLeftObservation bottomRight = topLeftObservation topRight = topRightObservation default: topLeft = bottomLeftObservation bottomLeft = bottomRightObservation bottomRight = topRightObservation topRight = topLeftObservation } self.init(topLeft: topLeft, topRight: topRight, bottomRight: bottomRight, bottomLeft: bottomLeft) } }
28.126582
100
0.780378
894629f4df215923c1f88c663fa0e9ea50ec491b
1,028
// // CodeSystems.swift // HealthRecords // // Generated from FHIR 1.0.2.7202 // Copyright 2020 Apple 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 FMCore /** HTTP verbs (in the HTTP command line). URL: http://hl7.org/fhir/http-verb ValueSet: http://hl7.org/fhir/ValueSet/http-verb */ public enum HTTPVerb: String, FHIRPrimitiveType { /// HTTP GET case GET = "GET" /// HTTP POST case POST = "POST" /// HTTP PUT case PUT = "PUT" /// HTTP DELETE case DELETE = "DELETE" }
24.47619
76
0.695525
0aa261cea1edf289a8e6962f75448fb7a7bb74ed
876
import Foundation import Url /// Maps names command line tools/executables to file urls. /// The protcol is implemented in a different frameworok. public protocol ExecutableProvider { func urlForExecuable(_ executableName: String) -> Absolute? } open class ExecutableProviderGroup { // MARK: - Init public init() {} // MARK: - Properties public private(set) var providers = [ExecutableProvider]() // MARK: - Working with the Group public func add(_ provider: ExecutableProvider) { providers.append(provider) } } extension ExecutableProviderGroup: ExecutableProvider { public func urlForExecuable(_ executableName: String) -> Absolute? { for provider in providers { if let url = provider.urlForExecuable(executableName) { return url } } return nil } }
26.545455
72
0.663242
28ec1cbf2cebc15114707b099eba911c47456974
1,537
// // AKMoviesDisplayView.swift // Akane // // Created by 御前崎悠羽 on 2020/5/13. // Copyright © 2020 御前崎悠羽. All rights reserved. // import UIKit class AKMoviesDisplayView: AKUIView { // MARK: - Property. var moviesCollectionView: AKUICollectionView! // MARK: - Init. override init(frame: CGRect) { super.init(frame: frame) let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init() self.moviesCollectionView = AKUICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: self.frame.width, height: self.frame.height), collectionViewLayout: flowLayout) flowLayout.itemSize = CGSize.init(width: AKConstant.MovieDisplayView.itemSizeWidth, height: AKConstant.MovieDisplayView.itemSizeHeight) flowLayout.minimumLineSpacing = AKConstant.MovieDisplayView.minLineSpace flowLayout.sectionInset.top = AKConstant.MovieDisplayView.itemTopEdge flowLayout.sectionInset.left = AKConstant.MovieDisplayView.itemLeftEdge flowLayout.sectionInset.right = AKConstant.MovieDisplayView.itemRightEdge flowLayout.sectionInset.bottom = AKConstant.MovieDisplayView.itemBottomEdge self.moviesCollectionView.register(AKMovieCollectionViewCell.self, forCellWithReuseIdentifier: "MovieCell") self.moviesCollectionView.allowsMultipleSelection = true self.addSubview(self.moviesCollectionView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
39.410256
177
0.735198
01ff3c263a6e66150d749fad664b7086e5c300d4
4,152
// // ALFace.swift // ALVisionerKit // // Created by amir.lahav on 30/11/2019. // import Foundation import Vision struct ALFace { init(face:ALFace, faceObservation:VNFaceObservation) { if face.faceLandmarkRegions == nil { self.faceLandmarkRegions = ALFaceLandmarkRegion(landmarks: faceObservation.landmarks) }else { self.faceLandmarkRegions = face.faceLandmarkRegions } self.faceQuality = face.faceQuality > 0 ? face.faceQuality : faceObservation.faceCaptureQuality ?? 0 self.rect = faceObservation.boundingBox } init(faceObservation:VNFaceObservation) { self.faceLandmarkRegions = ALFaceLandmarkRegion(landmarks: faceObservation.landmarks) self.rect = faceObservation.boundingBox self.faceQuality = faceQuality > 0 ? faceQuality : faceObservation.faceCaptureQuality ?? 0 } var faceQuality:Float = 0 var rect:CGRect var faceLandmarkRegions:ALFaceLandmarkRegion? init(faceQuality:Float, rect:CGRect, faceLandmarkRegions:ALFaceLandmarkRegion?) { self.faceQuality = faceQuality self.rect = rect self.faceLandmarkRegions = faceLandmarkRegions } func duplicate(faceQuality:Float? = nil, rect:CGRect? = nil, faceLandmarkRegions:VNFaceObservation? = nil) -> ALFace { ALFace(faceQuality: faceQuality ?? self.faceQuality, rect: rect ?? self.rect, faceLandmarkRegions: faceLandmarkRegions?.landmarks != nil ? ALFaceLandmarkRegion(landmarks: faceLandmarkRegions?.landmarks) : self.faceLandmarkRegions) } } struct ALFaceLandmarkRegion { init(landmarks:VNFaceLandmarks2D?) { if let faceContour = landmarks?.faceContour { self.faceContour = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: faceContour) } if let leftEye = landmarks?.leftEye { self.leftEye = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: leftEye) } if let rightEye = landmarks?.rightEye { self.rightEye = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: rightEye) } if let leftEyebrow = landmarks?.leftEyebrow { self.leftEyebrow = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: leftEyebrow) } if let rightEyebrow = landmarks?.rightEyebrow { self.rightEyebrow = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: rightEyebrow) } if let nose = landmarks?.nose { self.nose = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: nose) } if let noseCrest = landmarks?.noseCrest { self.noseCrest = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: noseCrest) } if let medianLine = landmarks?.medianLine { self.medianLine = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: medianLine) } if let outerLips = landmarks?.outerLips { self.outerLips = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: outerLips) } if let innerLips = landmarks?.innerLips { self.innerLips = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: innerLips) } if let leftPupil = landmarks?.leftPupil { self.leftPupil = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: leftPupil) } if let rightPupil = landmarks?.rightPupil { self.rightPupil = ALFaceLandmarkRegion2D(faceLandmarkRegion2D: rightPupil) } } var faceContour: ALFaceLandmarkRegion2D? var leftEye: ALFaceLandmarkRegion2D? var rightEye: ALFaceLandmarkRegion2D? var leftEyebrow: ALFaceLandmarkRegion2D? var rightEyebrow: ALFaceLandmarkRegion2D? var nose: ALFaceLandmarkRegion2D? var noseCrest: ALFaceLandmarkRegion2D? var medianLine: ALFaceLandmarkRegion2D? var outerLips: ALFaceLandmarkRegion2D? var innerLips: ALFaceLandmarkRegion2D? var leftPupil: ALFaceLandmarkRegion2D? var rightPupil: ALFaceLandmarkRegion2D? } struct ALFaceLandmarkRegion2D { var normalizedPoint:[CGPoint] = [] init(faceLandmarkRegion2D:VNFaceLandmarkRegion2D) { self.normalizedPoint = faceLandmarkRegion2D.normalizedPoints } }
39.169811
238
0.69894
b93cff88109b349cca51fc595618f6a468685a1a
513
// // AppDelegate.swift // Example // // Created by Lasha Efremidze on 3/8/17. // Copyright © 2017 efremidze. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } }
23.318182
145
0.707602
2f84823522f35fa5172c98892e6f67a3ecd1b381
1,514
// // AutoTimer.swift // SightCallAlpha // // Created by Jason Jobe on 3/18/21. // import Foundation public class AutoTimer { public typealias Stepper = (AutoTimer) -> Void var timer: Timer? public private(set) var started: Date? var endAt: Date? { Date(timeInterval: timeout, since: started!) } // var current: TimeInterval { // guard let started = started else { return 0 } // return Date().timeIntervalSince(started) // } var timeout: TimeInterval = 20 var interval: TimeInterval var step: Stepper? public var elapsed: TimeInterval { guard let started = started else { return timeout } return Date().timeIntervalSince(started) } public var isFinished: Bool { (timer == nil) || elapsed >= timeout } public init (timeout: TimeInterval, every secs: TimeInterval, step: Stepper? = nil) { self.timeout = timeout interval = secs self.step = step } public func start() -> Self { started = Date() timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(tick), userInfo: nil, repeats: true) timer?.tolerance = interval * 0.1 return self } public func stop() { timer?.invalidate() self.timer = nil } @objc func tick(_ timer: Timer) { // current += 1 step?(self) if isFinished { stop() } } }
23.292308
131
0.575958
9b46366b77904a03e5c130b00902ebc43ac5e39f
3,354
// // RegistrationRequestHelper.swift // SwiftSenpai-UnitTest-HttpRequest // // Created by Lee Kah Seng on 06/02/2020. // Copyright © 2020 Lee Kah Seng. All rights reserved. // import Foundation protocol RegistrationHelperProtocol { func register(_ username: String, password: String, completion: (Result<User, RegistrationRequestError>) -> Void) } class RegistrationRequestHelper: RegistrationHelperProtocol { private let networkLayer: NetworkLayerProtocol private let encryptionHelper: EncryptionHelperProtocol // Inject networkLayer and encryptionHelper during initialisation init(_ networkLayer: NetworkLayerProtocol, encryptionHelper: EncryptionHelperProtocol) { self.networkLayer = networkLayer self.encryptionHelper = encryptionHelper } func register(_ username: String, password: String, completion: (Result<User, RegistrationRequestError>) -> Void) { // Remote API URL let url = URL(string: "https://api-call")! // Encrypt password using encryptionHelper let encryptedPassword = encryptionHelper.encrypt(password) // Encode post parameters to JSON data let parameters = ["username": username, "password": encryptedPassword] let encoder = JSONEncoder() let requestData = try! encoder.encode(parameters) // Perform POST request using network layer networkLayer.post(url, parameters: requestData) { (result) in switch result { case .success(let jsonData): // Create JSON decoder to decode response JSON to User object let decoder = JSONDecoder() // Convert JSON key from snake case to camel case // Ex: user_id --> userId decoder.keyDecodingStrategy = .convertFromSnakeCase if let user = try? decoder.decode(User.self, from: jsonData) { // Parsing JSON to user object successful // Trigger completion handler with user object completion(.success(user)) return } else if let error = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any] { // Parsing JSON to get error code if let errorCode = error["error_code"] as? String { // Error code available // Use error code to identify the error switch errorCode { case "E001": completion(.failure(.usernameAlreadyExists)) return default: break } } } // Failed to parse response JSON // Trigger completion handler with error completion(.failure(.unexpectedResponse)) case .failure: // HTTP Request failed // Trigger completion handler with error completion(.failure(.requestFailed)) } } } }
38.113636
107
0.549493
4ae21e38a84cd4f4cde8f63a5dcb38b97debce1a
749
import XCTest import SamplePlayer class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.827586
111
0.602136
de9be942f12d76f63fabe8bf64a6078d839a0174
1,344
// // ListViewController.swift // BasicTableView // // Created by giftbot on 2019. 4. 10.. // Copyright © 2019년 giftbot. All rights reserved. // import UIKit final class ListViewController: UIViewController { var viewControllers: [UIViewController] = [] override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewControllers = [ TableViewBasic(), TableViewLifeCycle(), TableViewSection(), TableViewRefresh(), TableViewCellStyle(), TableViewCustomCell(), TableViewEditing(), ] } } // MARK: - UITableViewDataSource extension ListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewControllers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "list", for: indexPath) cell.textLabel?.text = "\(viewControllers[indexPath.row])" return cell } } // MARK: - UITableViewDelegate extension ListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = viewControllers[indexPath.row] navigationController?.pushViewController(vc, animated: true) } }
25.846154
98
0.72247
91bba9b56e37af182aefa8c4eee8a47d7f7f266f
1,900
import UIKit extension UIAlertController { /// Add a date picker /// /// - Parameters: /// - mode: date picker mode /// - date: selected date of date picker /// - minimumDate: minimum date of date picker /// - maximumDate: maximum date of date picker /// - action: an action for datePicker value change func addDatePicker(mode: UIDatePicker.Mode, date: Date?, minimumDate: Date? = nil, maximumDate: Date? = nil, action: DatePickerViewController.Action?) { let datePicker = DatePickerViewController(mode: mode, date: date, minimumDate: minimumDate, maximumDate: maximumDate, action: action) set(vc: datePicker, height: 217) } } final class DatePickerViewController: UIViewController { public typealias Action = (Date) -> Void fileprivate var action: Action? fileprivate lazy var datePicker: UIDatePicker = { [unowned self] in $0.addTarget(self, action: #selector(DatePickerViewController.actionForDatePicker), for: .valueChanged) return $0 }(UIDatePicker()) required init(mode: UIDatePicker.Mode, date: Date? = nil, minimumDate: Date? = nil, maximumDate: Date? = nil, action: Action?) { super.init(nibName: nil, bundle: nil) datePicker.datePickerMode = mode datePicker.date = date ?? Date() datePicker.minimumDate = minimumDate datePicker.maximumDate = maximumDate self.action = action } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { Log("has deinitialized") } override func loadView() { view = datePicker } @objc func actionForDatePicker() { action?(datePicker.date) } public func setDate(_ date: Date) { datePicker.setDate(date, animated: true) } }
31.666667
156
0.637895
e6ae704dbf405fb0518345a76abafa492fcb8c32
361
// // User+Convenience.swift // Budget Blocks // // Created by Nick Nguyen on 5/28/20. // Copyright © 2020 Isaac Lyons. All rights reserved. // import Foundation extension User { var userRepresentation: UserRepresentation? { guard let name = name, let email = email else { return nil } return UserRepresentation(name: name, email: email) } }
21.235294
64
0.692521
01768826afb488a5201c22d44ca3e93a2c29043c
271
// // Copyright © 2019 MBition GmbH. All rights reserved. // import Foundation // MARK: - VehicleCommandStatusUpdateModel struct VehicleCommandStatusUpdateModel { let requestIDs: [String] let clientMessageData: Data? let sequenceNumber: Int32 let vin: String }
16.9375
55
0.760148
1d0f6011ce8a980307896cd210521db48a68e551
4,937
// // UsageAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation open class UsageAPI { /** Get the results of a usage query - parameter executionId: (path) ID of the query execution - parameter completion: completion handler to receive the data and the error objects */ open class func getUsageQueryExecutionIdResults(executionId: String, completion: @escaping ((_ data: ApiUsageQueryResult?,_ error: Error?) -> Void)) { let requestBuilder = getUsageQueryExecutionIdResultsWithRequestBuilder(executionId: executionId) requestBuilder.execute { (response: Response<ApiUsageQueryResult>?, error) -> Void in do { if let e = error { completion(nil, e) } else if let r = response { try requestBuilder.decode(r) completion(response?.body, error) } else { completion(nil, error) } } catch { completion(nil, error) } } } /** Get the results of a usage query - GET /api/v2/usage/query/{executionId}/results - - OAuth: - type: oauth2 - name: PureCloud OAuth - examples: [{contentType=application/json, example={ "queryStatus" : "aeiou", "results" : [ { "date" : "2000-01-23T04:56:07.000+0000", "clientId" : "aeiou", "clientName" : "aeiou", "templateUri" : "aeiou", "requests" : 123456789, "httpMethod" : "aeiou", "userId" : "aeiou", "organizationId" : "aeiou", "status429" : 123456789, "status400" : 123456789, "status500" : 123456789, "status200" : 123456789, "status300" : 123456789 } ] }}] - parameter executionId: (path) ID of the query execution - returns: RequestBuilder<ApiUsageQueryResult> */ open class func getUsageQueryExecutionIdResultsWithRequestBuilder(executionId: String) -> RequestBuilder<ApiUsageQueryResult> { var path = "/api/v2/usage/query/{executionId}/results" let executionIdPreEscape = "\(executionId)" let executionIdPostEscape = executionIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" path = path.replacingOccurrences(of: "{executionId}", with: executionIdPostEscape, options: .literal, range: nil) let URLString = PureCloudPlatformClientV2API.basePath + path let body: Data? = nil let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<ApiUsageQueryResult>.Type = PureCloudPlatformClientV2API.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", url: url!, body: body) } /** Query organization API Usage - - parameter body: (body) Query - parameter completion: completion handler to receive the data and the error objects */ open class func postUsageQuery(body: ApiUsageQuery, completion: @escaping ((_ data: UsageExecutionResult?,_ error: Error?) -> Void)) { let requestBuilder = postUsageQueryWithRequestBuilder(body: body) requestBuilder.execute { (response: Response<UsageExecutionResult>?, error) -> Void in do { if let e = error { completion(nil, e) } else if let r = response { try requestBuilder.decode(r) completion(response?.body, error) } else { completion(nil, error) } } catch { completion(nil, error) } } } /** Query organization API Usage - - POST /api/v2/usage/query - After calling this method, you will then need to poll for the query results based on the returned execution Id - OAuth: - type: oauth2 - name: PureCloud OAuth - examples: [{contentType=application/json, example={ "executionId" : "aeiou", "resultsUri" : "aeiou" }}] - parameter body: (body) Query - returns: RequestBuilder<UsageExecutionResult> */ open class func postUsageQueryWithRequestBuilder(body: ApiUsageQuery) -> RequestBuilder<UsageExecutionResult> { let path = "/api/v2/usage/query" let URLString = PureCloudPlatformClientV2API.basePath + path let body = JSONEncodingHelper.encodingParameters(forEncodableObject: body) let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<UsageExecutionResult>.Type = PureCloudPlatformClientV2API.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", url: url!, body: body) } }
32.058442
154
0.604011
e81931587d9c60fb29fe85ed49400f0053b10f1c
7,827
/* Copyright (c) 2021, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if !os(watchOS) && canImport(ResearchKit) import CareKitStore import CareKitUI import ResearchKit import UIKit // MARK: OCKSurveyTaskViewControllerDelegate public protocol OCKSurveyTaskViewControllerDelegate: AnyObject { func surveyTask( viewController: OCKSurveyTaskViewController, for task: OCKAnyTask, didFinish result: Result<ORKTaskViewControllerFinishReason, Error>) func surveyTask( viewController: OCKSurveyTaskViewController, shouldAllowDeletingOutcomeForEvent event: OCKAnyEvent) -> Bool } public extension OCKSurveyTaskViewControllerDelegate { func surveyTask( viewController: OCKSurveyTaskViewController, for task: OCKAnyTask, didFinish result: Result<ORKTaskViewControllerFinishReason, Error>) { // No-op } func surveyTask( viewController: OCKSurveyTaskViewController, shouldAllowDeletingOutcomeForEvent event: OCKAnyEvent) -> Bool { return true } } open class OCKSurveyTaskViewController: OCKTaskViewController<OCKTaskController, OCKSurveyTaskViewSynchronizer>, ORKTaskViewControllerDelegate { private let extractOutcome: (ORKTaskResult) -> [OCKOutcomeValue]? public let survey: ORKTask public weak var surveyDelegate: OCKSurveyTaskViewControllerDelegate? public convenience init( task: OCKAnyTask, eventQuery: OCKEventQuery, storeManager: OCKSynchronizedStoreManager, survey: ORKTask, viewSynchronizer: OCKSurveyTaskViewSynchronizer = OCKSurveyTaskViewSynchronizer(), extractOutcome: @escaping (ORKTaskResult) -> [OCKOutcomeValue]?) { self.init( taskID: task.id, eventQuery: eventQuery, storeManager: storeManager, survey: survey, viewSynchronizer: viewSynchronizer, extractOutcome: extractOutcome ) } public init( taskID: String, eventQuery: OCKEventQuery, storeManager: OCKSynchronizedStoreManager, survey: ORKTask, viewSynchronizer: OCKSurveyTaskViewSynchronizer = OCKSurveyTaskViewSynchronizer(), extractOutcome: @escaping (ORKTaskResult) -> [OCKOutcomeValue]?) { self.survey = survey self.extractOutcome = extractOutcome super.init( viewSynchronizer: viewSynchronizer, taskID: taskID, eventQuery: eventQuery, storeManager: storeManager ) } override open func taskView( _ taskView: UIView & OCKTaskDisplayable, didCompleteEvent isComplete: Bool, at indexPath: IndexPath, sender: Any?) { guard isComplete else { if let event = controller.eventFor(indexPath: indexPath), let delegate = surveyDelegate, delegate.surveyTask( viewController: self, shouldAllowDeletingOutcomeForEvent: event) == false { return } let cancelAction = UIAlertAction( title: "Cancel", style: .cancel, handler: nil ) let confirmAction = UIAlertAction( title: "Delete", style: .destructive) { _ in super.taskView( taskView, didCompleteEvent: isComplete, at: indexPath, sender: sender ) } let warningAlert = UIAlertController( title: "Delete", message: "Are you sure you want to delete your response?", preferredStyle: .actionSheet ) warningAlert.addAction(cancelAction) warningAlert.addAction(confirmAction) present(warningAlert, animated: true, completion: nil) return } let surveyViewController = ORKTaskViewController( task: survey, taskRun: nil ) let directory = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask ).last!.appendingPathComponent("ResearchKit", isDirectory: true) surveyViewController.outputDirectory = directory surveyViewController.delegate = self present(surveyViewController, animated: true, completion: nil) } // MARK: ORKTaskViewControllerDelegate open func taskViewController( _ taskViewController: ORKTaskViewController, didFinishWith reason: ORKTaskViewControllerFinishReason, error: Error?) { taskViewController.dismiss(animated: true, completion: nil) guard let task = controller.taskEvents.first?.first?.task else { assertionFailure("Task controller is missing its task") return } if let error = error { surveyDelegate?.surveyTask( viewController: self, for: task, didFinish: .failure(error) ) return } guard reason == .completed else { return } let indexPath = IndexPath(item: 0, section: 0) guard let event = controller.eventFor(indexPath: indexPath) else { return } guard let values = extractOutcome(taskViewController.result) else { return } let outcome = OCKOutcome( taskUUID: event.task.uuid, taskOccurrenceIndex: event.scheduleEvent.occurrence, values: values ) controller.storeManager.store.addAnyOutcome( outcome, callbackQueue: .main) { result in if case let .failure(error) = result { self.surveyDelegate?.surveyTask( viewController: self, for: task, didFinish: .failure(error) ) } self.surveyDelegate?.surveyTask( viewController: self, for: task, didFinish: .success(reason) ) } } } #endif
32.209877
144
0.639581
691590699782926b9e553e17d56fa60d40e67271
2,623
/* * Copyright (c) 2019, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import Foundation public struct FilterStatus: StaticProxyConfigurationMessage { public static let opCode: UInt8 = 0x03 public var parameters: Data? { return Data([filterType.rawValue]) + listSize.bigEndian } /// The current filter type. public let filterType: ProxyFilerType /// Number of addresses in the proxy filter list. public let listSize: UInt16 /// Creates a new Filter Status message. /// /// - parameter type: The current filter type. /// - parameter listSize: Number of addresses in the proxy /// filter list. public init(_ type: ProxyFilerType, listSize: UInt16) { self.filterType = type self.listSize = listSize } public init?(parameters: Data) { guard parameters.count == 3 else { return nil } guard let type = ProxyFilerType(rawValue: parameters[0]) else { return nil } filterType = type listSize = parameters.readBigEndian(fromOffset: 1) } }
39.742424
84
0.713687
62159d91ec3ceb8e1886ae772be7dc4837ac523b
901
// // ABFlowTests.swift // ABFlowTests // // Created by Tatsuya Tobioka on 2019/01/08. // Copyright © 2019 tnantoka. All rights reserved. // import XCTest @testable import ABFlow class ABFlowTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
25.742857
111
0.653718
d64180fcc37a0a2a2e7e0a9ca9129f33e81bb096
12,403
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2017 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module import ObjectiveC public protocol _KeyValueCodingAndObserving {} public struct NSKeyValueObservedChange<Value> { public typealias Kind = NSKeyValueChange public let kind: Kind ///newValue and oldValue will only be non-nil if .new/.old is passed to `observe()`. In general, get the most up to date value by accessing it directly on the observed object instead. public let newValue: Value? public let oldValue: Value? ///indexes will be nil unless the observed KeyPath refers to an ordered to-many property public let indexes: IndexSet? ///'isPrior' will be true if this change observation is being sent before the change happens, due to .prior being passed to `observe()` public let isPrior:Bool } ///Conforming to NSKeyValueObservingCustomization is not required to use Key-Value Observing. Provide an implementation of these functions if you need to disable auto-notifying for a key, or add dependent keys public protocol NSKeyValueObservingCustomization : NSObjectProtocol { static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool } fileprivate extension NSObject { @objc class func _old_unswizzled_automaticallyNotifiesObservers(forKey key: String?) -> Bool { fatalError("Should never be reached") } @objc class func _old_unswizzled_keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> { fatalError("Should never be reached") } } @objc private class _KVOKeyPathBridgeMachinery : NSObject { @nonobjc static var keyPathTable: [String : AnyKeyPath] = { /* Move all our methods into place. We want the following: _KVOKeyPathBridgeMachinery's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replaces NSObject's versions of them NSObject's automaticallyNotifiesObserversForKey:, and keyPathsForValuesAffectingValueForKey: methods replace NSObject's _old_unswizzled_* methods NSObject's _old_unswizzled_* methods replace _KVOKeyPathBridgeMachinery's methods, and are never invoked */ let rootClass: AnyClass = NSObject.self let bridgeClass: AnyClass = _KVOKeyPathBridgeMachinery.self let dependentSel = #selector(NSObject.keyPathsForValuesAffectingValue(forKey:)) let rootDependentImpl = class_getClassMethod(rootClass, dependentSel)! let bridgeDependentImpl = class_getClassMethod(bridgeClass, dependentSel)! method_exchangeImplementations(rootDependentImpl, bridgeDependentImpl) // NSObject <-> Us let originalDependentImpl = class_getClassMethod(bridgeClass, dependentSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation let originalDependentSel = #selector(NSObject._old_unswizzled_keyPathsForValuesAffectingValue(forKey:)) let dummyDependentImpl = class_getClassMethod(rootClass, originalDependentSel)! method_exchangeImplementations(originalDependentImpl, dummyDependentImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version let autoSel = #selector(NSObject.automaticallyNotifiesObservers(forKey:)) let rootAutoImpl = class_getClassMethod(rootClass, autoSel)! let bridgeAutoImpl = class_getClassMethod(bridgeClass, autoSel)! method_exchangeImplementations(rootAutoImpl, bridgeAutoImpl) // NSObject <-> Us let originalAutoImpl = class_getClassMethod(bridgeClass, autoSel)! //we swizzled it onto this class, so this is actually NSObject's old implementation let originalAutoSel = #selector(NSObject._old_unswizzled_automaticallyNotifiesObservers(forKey:)) let dummyAutoImpl = class_getClassMethod(rootClass, originalAutoSel)! method_exchangeImplementations(originalAutoImpl, dummyAutoImpl) // NSObject's original version <-> NSObject's _old_unswizzled_ version return [:] }() @nonobjc static var keyPathTableLock = NSLock() @nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:AnyKeyPath) -> String { guard let keyPathString = keyPath._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \(keyPath)") } _KVOKeyPathBridgeMachinery.keyPathTableLock.lock() defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() } _KVOKeyPathBridgeMachinery.keyPathTable[keyPathString] = keyPath return keyPathString } @nonobjc fileprivate static func _bridgeKeyPath(_ keyPath:String?) -> AnyKeyPath? { guard let keyPath = keyPath else { return nil } _KVOKeyPathBridgeMachinery.keyPathTableLock.lock() defer { _KVOKeyPathBridgeMachinery.keyPathTableLock.unlock() } let path = _KVOKeyPathBridgeMachinery.keyPathTable[keyPath] return path } @objc override class func automaticallyNotifiesObservers(forKey key: String) -> Bool { //This is swizzled so that it's -[NSObject automaticallyNotifiesObserversForKey:] if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key) { return customizingSelf.automaticallyNotifiesObservers(for: path) } else { return self._old_unswizzled_automaticallyNotifiesObservers(forKey: key) //swizzled to be NSObject's original implementation } } @objc override class func keyPathsForValuesAffectingValue(forKey key: String?) -> Set<String> { //This is swizzled so that it's -[NSObject keyPathsForValuesAffectingValueForKey:] if let customizingSelf = self as? NSKeyValueObservingCustomization.Type, let path = _KVOKeyPathBridgeMachinery._bridgeKeyPath(key!) { let resultSet = customizingSelf.keyPathsAffectingValue(for: path) return Set(resultSet.lazy.map { guard let str = $0._kvcKeyPathString else { fatalError("Could not extract a String from KeyPath \($0)") } return str }) } else { return self._old_unswizzled_keyPathsForValuesAffectingValue(forKey: key) //swizzled to be NSObject's original implementation } } } func _bridgeKeyPathToString(_ keyPath:AnyKeyPath) -> String { return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath) } func _bridgeStringToKeyPath(_ keyPath:String) -> AnyKeyPath? { return _KVOKeyPathBridgeMachinery._bridgeKeyPath(keyPath) } public class NSKeyValueObservation : NSObject { @nonobjc weak var object : NSObject? @nonobjc let callback : (NSObject, NSKeyValueObservedChange<Any>) -> Void @nonobjc let path : String //workaround for <rdar://problem/31640524> Erroneous (?) error when using bridging in the Foundation overlay @nonobjc static var swizzler : NSKeyValueObservation? = { let bridgeClass: AnyClass = NSKeyValueObservation.self let observeSel = #selector(NSObject.observeValue(forKeyPath:of:change:context:)) let swapSel = #selector(NSKeyValueObservation._swizzle_me_observeValue(forKeyPath:of:change:context:)) let rootObserveImpl = class_getInstanceMethod(bridgeClass, observeSel) let swapObserveImpl = class_getInstanceMethod(bridgeClass, swapSel) method_exchangeImplementations(rootObserveImpl, swapObserveImpl) return nil }() fileprivate init(object: NSObject, keyPath: AnyKeyPath, callback: @escaping (NSObject, NSKeyValueObservedChange<Any>) -> Void) { path = _bridgeKeyPathToString(keyPath) let _ = NSKeyValueObservation.swizzler self.object = object self.callback = callback } fileprivate func start(_ options: NSKeyValueObservingOptions) { object?.addObserver(self, forKeyPath: path, options: options, context: nil) } ///invalidate() will be called automatically when an NSKeyValueObservation is deinited @objc public func invalidate() { object?.removeObserver(self, forKeyPath: path, context: nil) object = nil } @objc func _swizzle_me_observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSString : Any]?, context: UnsafeMutableRawPointer?) { guard let ourObject = self.object, object as? NSObject == ourObject, let change = change else { return } let rawKind:UInt = change[NSKeyValueChangeKey.kindKey.rawValue as NSString] as! UInt let kind = NSKeyValueChange(rawValue: rawKind)! let notification = NSKeyValueObservedChange(kind: kind, newValue: change[NSKeyValueChangeKey.newKey.rawValue as NSString], oldValue: change[NSKeyValueChangeKey.oldKey.rawValue as NSString], indexes: change[NSKeyValueChangeKey.indexesKey.rawValue as NSString] as! IndexSet?, isPrior: change[NSKeyValueChangeKey.notificationIsPriorKey.rawValue as NSString] as? Bool ?? false) callback(ourObject, notification) } deinit { object?.removeObserver(self, forKeyPath: path, context: nil) } } public extension _KeyValueCodingAndObserving { ///when the returned NSKeyValueObservation is deinited or invalidated, it will stop observing public func observe<Value>( _ keyPath: KeyPath<Self, Value>, options: NSKeyValueObservingOptions = [], changeHandler: @escaping (Self, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation { let result = NSKeyValueObservation(object: self as! NSObject, keyPath: keyPath) { (obj, change) in let notification = NSKeyValueObservedChange(kind: change.kind, newValue: change.newValue as? Value, oldValue: change.oldValue as? Value, indexes: change.indexes, isPrior: change.isPrior) changeHandler(obj as! Self, notification) } result.start(options) return result } public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>) { (self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath)) } public func willChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) { (self as! NSObject).willChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath)) } public func willChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void { (self as! NSObject).willChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set) } public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>) { (self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath)) } public func didChange<Value>(_ changeKind: NSKeyValueChange, valuesAt indexes: IndexSet, for keyPath: KeyPath<Self, Value>) { (self as! NSObject).didChange(changeKind, valuesAt: indexes, forKey: _bridgeKeyPathToString(keyPath)) } public func didChangeValue<Value>(for keyPath: KeyPath<Self, Value>, withSetMutation mutation: NSKeyValueSetMutationKind, using set: Set<Value>) -> Void { (self as! NSObject).didChangeValue(forKey: _bridgeKeyPathToString(keyPath), withSetMutation: mutation, using: set) } } extension NSObject : _KeyValueCodingAndObserving {}
54.399123
209
0.69717
fbd9e5a57f917daebccfb70f9032e92a2fec8468
2,081
import MarketKit import StorageKit class RestoreFavoriteCoinWorker { private let localStorageKey = "restore-favorite-coin-worker-run" private let coinManager: CoinManager private let favoritesManager: FavoritesManager private let localStorage: StorageKit.ILocalStorage private let storage: IFavoriteCoinRecordStorage init(coinManager: CoinManager, favoritesManager: FavoritesManager, localStorage: StorageKit.ILocalStorage, storage: IFavoriteCoinRecordStorage) { self.coinManager = coinManager self.favoritesManager = favoritesManager self.localStorage = localStorage self.storage = storage } } extension RestoreFavoriteCoinWorker { func run() throws { let alreadyRun: Bool = localStorage.value(for: localStorageKey) ?? false guard !alreadyRun else { return } localStorage.set(value: true, for: localStorageKey) let oldRecords = storage.favoriteCoinRecords_v_0_22 let oldCoinTypes = oldRecords.map { $0.coinType } var coinsUids = Set<String>() for oldCoinType in oldCoinTypes { switch oldCoinType { case .bitcoin: coinsUids.insert("bitcoin") case .bitcoinCash: coinsUids.insert("bitcoin-cash") case .litecoin: coinsUids.insert("litecoin") case .dash: coinsUids.insert("dash") case .zcash: coinsUids.insert("zcash") case .ethereum: coinsUids.insert("ethereum") case .binanceSmartChain: coinsUids.insert("binancecoin") case .erc20, .bep20, .bep2: if let platformCoin = try coinManager.platformCoin(coinType: oldCoinType) { coinsUids.insert(platformCoin.coin.uid) } case .unsupported(let type): if let fullCoin = try coinManager.fullCoin(coinUid: type) { coinsUids.insert(fullCoin.coin.uid) } default: () } } favoritesManager.add(coinUids: Array(coinsUids)) } }
33.031746
149
0.64248
de167a83dc7e26631d2d44cf8474d8e071f15f18
594
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- func bar() { print ("bar()") } func main() -> Int { var func_ptr = bar func_ptr(); // Set breakpoint here return 0 } main()
25.826087
80
0.590909
e876d48f4adcf51a40fc702f9cf6b933446f33df
783
// // AnchorPoint.swift // // Copyright © 2020 Apple Inc. All rights reserved. // import UIKit import PlaygroundSupport import SPCCore import SPCIPC /// An enumeration of the points within a graphic to which its position can be anchored. /// /// - localizationKey: AnchorPoint public enum AnchorPoint: Int { case center case left case top case right case bottom } extension AnchorPoint: PlaygroundValueTransformable { public var playgroundValue: PlaygroundValue? { return .integer(self.rawValue) } public static func from(_ playgroundValue: PlaygroundValue) -> PlaygroundValueTransformable? { guard case .integer(let integer) = playgroundValue else { return nil } return AnchorPoint(rawValue: integer) } }
23.029412
98
0.706258
143f7e7647b12b55cbe2bcd3ebe9b9bb6cb0ad58
1,808
//#-hidden-code import PlaygroundSupport let liveViewProxy = PlaygroundPage.current.liveView as! PlaygroundRemoteLiveViewProxy let playgroundPageController = PlaygroundPageController( liveViewProxy: liveViewProxy, successStatus: .pass(message: "Great Thinking—it's now safe to operate that um… LED!\n\n[Next Puzzle](@next)"), failureStatus: .fail(hints: ["Think about which logic gate might match the situation."], solution: "Type `showSolution()` to show one possibility.")) liveViewProxy.delegate = playgroundPageController //#-end-hidden-code /*: # Safety First Some industrial machines need can be very dangerous for humans to operate. Let's pretend the LED on the right is a machine that can cause serious harm when activited while an operator's arm is resting on it. Luckily, there is the concept of two-hand control devices: In order to activate the machine, the operator has simultaneously push two buttons that are an arm's length apart. Thus, he can only activate the machine from a safe distance. Let's build that security mechanism! * Callout(Your Goal): Connect the LED to both switches (this time, think of them as buttons) in such a way that it only lights up when both are true. ## A Few More Tips - [And gates](glossary://AndGate) and [or gates](glossary://OrGate) have inputs on the top, left, and bottom - Just like in the real world, gates have a little bit of a delay, which is exaggarated in this simulation—this is called [propagation delay](glossary://PropagationDelay) - Importantly, a disconnected input is not _zero_ or _false_ but unknown and will not be taken into account */ //#-code-completion(everything, hide) //#-code-completion(identifier, show, showPuzzle(), showSolution()) //#-editable-code //#-end-editable-code
50.222222
235
0.753872
e0faea3784366f2384c796e260ee39d8fd7f4491
903
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation // ApplicationGatewayRequestRoutingRulePropertiesFormatProtocol is properties of request routing rule of the // application gateway. public protocol ApplicationGatewayRequestRoutingRulePropertiesFormatProtocol : Codable { var ruleType: ApplicationGatewayRequestRoutingRuleTypeEnum? { get set } var backendAddressPool: SubResourceProtocol? { get set } var backendHttpSettings: SubResourceProtocol? { get set } var httpListener: SubResourceProtocol? { get set } var urlPathMap: SubResourceProtocol? { get set } var redirectConfiguration: SubResourceProtocol? { get set } var provisioningState: String? { get set } }
53.117647
109
0.768549
5d5224c7db56f7fae578a8c0299f36ca3031ab75
1,808
// // MVVMView.swift // Calculator // // Created by 顾海军 on 2019/12/3. // Copyright © 2019 顾海军. All rights reserved. // import UIKit import RxSwift import RxCocoa class MVVMView: CalculatorView { var perform: Observable<String?>? private var performReturn: BehaviorRelay<String?> = BehaviorRelay(value: nil) override init(frame: CGRect) { super.init(frame: frame) self.inputTextField.delegate = self self.setupEvents() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupEvents() { perform = Observable.of( self.performButton.rx.tap .flatMapLatest({ (_) -> Observable<String?> in return Observable.just(self.inputTextField.text) }), self.performReturn.asObservable()) .merge() } } extension MVVMView: UITextFieldDelegate { internal func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] let currentText = textField.text as NSString? if currentText?.lowercased.contains("error") == true { textField.text = "" return true } if currentText?.length == 1 && currentText == "0" { if range.location == 1 && numbers.contains(string) { textField.text = "" return true } } return true } internal func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.performReturn.accept(textField.text) return true } }
26.588235
138
0.566925
ef256d8cc85caf652e5f63ae511190091607906a
531
import Flutter import UIKit public class SwiftApplangaFlutterPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "applanga_flutter", binaryMessenger: registrar.messenger()) let instance = SwiftApplangaFlutterPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } }
35.4
104
0.781544
5668863f14f0ebbbbd0073fbbe13a1595e60c196
8,211
/* Copyright (c) <2020> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation extension BFIELD { static func parse(data: Data, type: BFORM) -> BFIELD { //print("PARSE \(type): \(data?.base64EncodedString() ?? "NIL")") data.withUnsafeBytes{ ptr in self.read(ptr[0..<data.count], type: type) } } static func read(_ data: UnsafeRawBufferPointer.SubSequence?, type: BFORM) -> BFIELD { //print("PARSE \(type): \(data?.base64EncodedString() ?? "NIL")") switch type { case .L: if let data = data, !data.isEmpty, var string = String(bytes: data, encoding: .ascii) { string = string.trimmingCharacters(in: .whitespacesAndNewlines) let arr = string.reduce(into: [Bool](), { arr, char in if char == "T" { arr.append(true) } else if char == "F" { arr.append(false) } }) return BFIELD.L(val: arr) } else { return BFIELD.L(val: nil) } case .X: if let data = data { return BFIELD.X(val: Data(data)) } else { return BFIELD.X(val: Data()) } case .B: if let data = data { let values : [UInt8] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt8.self).map{UInt8.init(bigEndian: $0)} } return BFIELD.B(val: values) } else { return BFIELD.B(val: nil) } case .I: if let data = data { let values : [Int16] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int16.self).map{Int16.init(bigEndian: $0)} } return BFIELD.I(val: values) } else { return BFIELD.I(val: nil) } case .J: if let data = data { let values : [Int32] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int32.self).map{Int32.init(bigEndian: $0)} } return BFIELD.J(val: values) } else { return BFIELD.J(val: nil) } case .K: if let data = data { let values : [Int64] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int64.self).map{Int64.init(bigEndian: $0)} } return BFIELD.K(val: values) } else { return BFIELD.K(val: nil) } case .A: if let data = data { let values : [UInt8] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt8.self).map{$0} } return BFIELD.A(val: values) } else { return BFIELD.A(val: nil) } case .E: if let data = data { let values : [Float] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt32.self).map{Float(bitPattern: $0.bigEndian)} } return BFIELD.E(val: values) } else { return BFIELD.E(val: nil) } case .D: if let data = data { let values : [Double] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt64.self).map{Double(bitPattern: $0.bigEndian)} } return BFIELD.D(val: values) } else { return BFIELD.D(val: nil) } case .C: return BFIELD.C(val: nil) case .M: return BFIELD.M(val: nil) // variable length array case .PL: if let data = data, !data.isEmpty, var string = String(bytes: data, encoding: .ascii) { string = string.trimmingCharacters(in: .whitespacesAndNewlines) let arr = string.reduce(into: [Bool](), { arr, char in if char == "T" { arr.append(true) } else if char == "F" { arr.append(false) } }) return BFIELD.PL(val: arr) } else { return BFIELD.PL(val: nil) } case .PX: if let data = data { return BFIELD.PX(val: Data(data)) } else { return BFIELD.PX(val: Data()) } case .PB: if let data = data { let values : [UInt8] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt8.self).map{UInt8.init(bigEndian: $0)} } return BFIELD.PB(val: values) } else { return BFIELD.PB(val: nil) } case .PI: if let data = data { let values : [Int16] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int16.self).map{Int16.init(bigEndian: $0)} } return BFIELD.PI(val: values) } else { return BFIELD.PI(val: nil) } case .PJ: if let data = data { let values : [Int32] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int32.self).map{Int32.init(bigEndian: $0)} } return BFIELD.PJ(val: values) } else { return BFIELD.PJ(val: nil) } case .PK: if let data = data { let values : [Int64] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: Int64.self).map{Int64.init(bigEndian: $0)} } return BFIELD.PK(val: values) } else { return BFIELD.PK(val: nil) } case .PA: if let data = data { let values : [UInt8] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt8.self).map{$0} } return BFIELD.PA(val: values) } else { return BFIELD.PA(val: nil) } case .PE: if let data = data { let values : [Float32] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt32.self).map{Float32(bitPattern: $0)} } return BFIELD.PE(val: values) } else { return BFIELD.PE(val: nil) } case .PC: return BFIELD.PC(val: nil) case .QD: if let data = data { let values : [Double] = data.withUnsafeBytes { ptr in ptr.bindMemory(to: UInt64.self).map{Double(bitPattern: $0)} } return BFIELD.QD(val: values) } else { return BFIELD.QD(val: nil) } case .QM: return BFIELD.QM(val: nil) } } }
36.65625
99
0.47753
28decb950da91ddf5dd2fd5a84a25fc25c093a63
793
// // ViewController.swift // ReduxDemo // // Created by Viktor Shcherban on 13/02/2017. // Copyright © 2017 Bonial. All rights reserved. // import UIKit import ReSwift class ViewController: UIViewController, StoreSubscriber { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) mainStore.subscribe(self) } func newState(state: AppState) { DispatchQueue.main.async { [weak self] in self?.label.text = "\(state.counter ?? 0)" } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) mainStore.unsubscribe(self) } @IBOutlet weak var label: UILabel! @IBAction func plusOneTapped(_ sender: Any) { mainStore.dispatch(Actions.incrementCounter) } }
18.44186
57
0.682219
5bd73513ddadad9b55c781b5bb96ca99384f0033
1,432
// // ETHNode.swift // HackathonWallet // // Created by Nino Zhang on 2022/3/31. // import Foundation enum ETHNode { case eth case cronos case bsc case polygon } extension ETHNode { var nodeHttpUrl: String { switch self { case .eth: return Configuration.ethMainnetHttpUrl case .cronos: return Configuration.cronosHttpUrl case .bsc: return Configuration.bscHttpUrl case .polygon: return Configuration.polygonHttpUrl } } var scanBaseUrl: String { switch self { case .eth: return Configuration.etherscanBaseUrl case .cronos: return Configuration.cronoscanBaseUrl case .bsc: return Configuration.bscscanBaseUrl case .polygon: return Configuration.polygonscanBaseUrl } } var scanKey: String { switch self { case .eth: return Configuration.etherscanAPIKey case .cronos: return Configuration.cronoscanAPIKey case .bsc: return Configuration.bscscanAPIKey case .polygon: return Configuration.polygonscanAPIKey } } var explorerBaseUrl: String { switch self { case .eth: return Configuration.etherExplorerUrl case .cronos: return Configuration.cronosExplorerUrl case .bsc: return Configuration.bscExplorerUrl case .polygon: return Configuration.polygonExplorerUrl } } }
26.518519
62
0.655726