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
d6016a4144957d739007518ff81133511deb79ab
732
// // StorageConfiguration.swift // LevelDB // // Created by Krzysztof Kapitan on 22.02.2017. // Copyright © 2017 codesplice. All rights reserved. // import Foundation public struct StorageConfiguration { let encoder: Encoder let decoder: Decoder let serializer: Serializer let deserializer: Deserializer public init(encoder: Encoder = EncryptorDecryptor(), decoder: Decoder = EncryptorDecryptor(), serializer: Serializer = SerializerDeserializer(), deserializer: Deserializer = SerializerDeserializer()) { self.encoder = encoder self.decoder = decoder self.serializer = serializer self.deserializer = deserializer } }
25.241379
72
0.668033
4859b1cc0e670db726578b8450f0c68413247f4f
2,813
// // BallView.swift // Ball // // Created by Domenico on 02/05/15. // Copyright (c) 2015 Domenico. All rights reserved. // import UIKit import CoreMotion class BallView: UIView { var acceleration = CMAcceleration(x: 0, y: 0, z: 0) fileprivate let image = UIImage(named : "ball")! var currentPoint : CGPoint = CGPoint.zero { didSet { var newX = currentPoint.x var newY = currentPoint.y if newX < 0 { newX = 0 ballXVelocity = -(ballXVelocity / 2.0) } else if newX > bounds.size.width - image.size.width { newX = bounds.size.width - image.size.width ballXVelocity = -(ballXVelocity / 2.0) } if newY < 0 { newY = 0 ballYVelocity = -(ballYVelocity / 2.0) } else if newY > bounds.size.height - image.size.height { newY = bounds.size.height - image.size.height ballYVelocity = -(ballYVelocity / 2.0) } currentPoint = CGPoint(x: newX, y: newY) let currentRect = CGRect(x: newX, y: newY, width: newX + image.size.width, height: newY + image.size.height) let prevRect = CGRect(x: oldValue.x, y: oldValue.y, width: oldValue.x + image.size.width, height: oldValue.y + image.size.height) setNeedsDisplay(currentRect.union(prevRect)) } } fileprivate var ballXVelocity = 0.0 fileprivate var ballYVelocity = 0.0 fileprivate var lastUpdateTime = Date() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() -> Void { currentPoint = CGPoint(x: (bounds.size.width / 2.0) + (image.size.width / 2.0), y: (bounds.size.height / 2.0) + (image.size.height / 2.0)) } override func draw(_ rect: CGRect) { // Drawing code image.draw(at: currentPoint) } func update() -> Void { let now = Date() let secondsSinceLastDraw = now.timeIntervalSince(lastUpdateTime) ballXVelocity = ballXVelocity + (acceleration.x * secondsSinceLastDraw) ballYVelocity = ballYVelocity - (acceleration.y * secondsSinceLastDraw) let xDelta = secondsSinceLastDraw * ballXVelocity * 500 let yDelta = secondsSinceLastDraw * ballYVelocity * 500 currentPoint = CGPoint(x: currentPoint.x + CGFloat(xDelta), y: currentPoint.y + CGFloat(yDelta)) lastUpdateTime = now } }
31.965909
72
0.552435
b923062fba1de44fca8c0eccf74bda7a363e77ed
1,346
import Foundation public enum HTTPBinAPI { static let baseURL = URL(string: "https://httpbin.org")! public enum Endpoint { case bytes(count: Int) case get case getWithIndex(index: Int) case headers case image case post var toString: String { switch self { case .bytes(let count): return "bytes/\(count)" case .get, .getWithIndex: return "get" case .headers: return "headers" case .image: return "image/jpeg" case .post: return "post" } } var queryParams: [URLQueryItem]? { switch self { case .getWithIndex(let index): return [URLQueryItem(name: "index", value: "\(index)")] default: return nil } } public var toURL: URL { var components = URLComponents(url: HTTPBinAPI.baseURL, resolvingAgainstBaseURL: false)! components.path = "/\(self.toString)" components.queryItems = self.queryParams return components.url! } } } public struct HTTPBinResponse: Codable { public let headers: [String: String] public let url: String public let json: [String: String]? public let args: [String: String]? public init(data: Data) throws { self = try JSONDecoder().decode(Self.self, from: data) } }
22.433333
94
0.59584
bbe7d1299eb0aa274da62ec5cd8c8e493b607530
2,150
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit class AKFaderTests: AKTestCase { func testDefault() { output = AKFader(input, gain: 1.0) AKTestNoEffect() } func testBypass() { let fader = AKFader(input, gain: 2.0) fader.bypass() output = fader AKTestNoEffect() } func testMany() { let initialFader = AKFader(input, gain: 1.0) var nextFader = initialFader for _ in 0 ..< 200 { let fader = AKFader(nextFader, gain: 1.0) nextFader = fader } output = nextFader AKTestNoEffect() } let flippedMD5 = "8c774ff60ef1a5c47f8beec155d25f11" func testFlipStereo() { let pan = AKPanner(input, pan: 1.0) let fader = AKFader(pan, gain: 1.0) fader.flipStereo = true output = fader AKTestMD5(flippedMD5) } func testFlipStereoTwice() { let pan = AKPanner(input, pan: 1.0) let fader = AKFader(pan, gain: 1.0) fader.flipStereo = true let fader2 = AKFader(fader, gain: 1.0) fader2.flipStereo = true output = fader2 AKTestMD5("6b75baedc4700e335f665785e8648c14") } func testFlipStereoThrice() { let pan = AKPanner(input, pan: 1.0) let fader = AKFader(pan, gain: 1.0) fader.flipStereo = true let fader2 = AKFader(fader, gain: 1.0) fader2.flipStereo = true let fader3 = AKFader(fader2, gain: 1.0) fader3.flipStereo = true output = fader3 AKTestMD5(flippedMD5) } func testMixToMono() { let pan = AKPanner(input, pan: 1.0) let fader = AKFader(pan, gain: 1.0) fader.mixToMono = true output = fader AKTestMD5("986675abd9c15378e8f4eb581bf90857") } func testParameters() { output = AKFader(input, gain: 2.0) AKTestMD5("09fdb24adb3181f6985eba4b408d8c6d") } func testParameters2() { output = AKFader(input, gain: 0.5) AKTestMD5("79972090508032a146d806185f9bc871") } }
26.875
100
0.591163
f9200a7bc4c174a67ebe431c55a3a4e7caac3b92
514
// // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. // import Cocoa final class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
20.56
66
0.657588
14c84c0b7fa420c8b7a89158e9685f44dcdc286f
11,239
// MOHUD.swift // Created by Moath_Othman on 6/27/15. import UIKit /** MOHUD Simple HUD the looks like the Mac status alert view . can be used to indicate a process, like API request, and for status, like Success and failure. and you can add continue and cancel handlers so user can cancel the request or continue without blocking the screen. @auther Moath OTjman */ public class MOHUD: UIViewController { static var me:MOHUD? //MARK: Outlets @IBOutlet weak var loaderContainer: UIVisualEffectView? @IBOutlet weak var errorLabel: UILabel? @IBOutlet weak var statusLabel: UILabel? @IBOutlet weak var titleLabel: UILabel? @IBOutlet weak var activityIndicator: UIActivityIndicatorView? @IBOutlet weak var buttonsContainer: UIView? @IBOutlet weak var continueButton: UIButton? @IBOutlet weak var cancelButton: UIButton? @IBOutlet weak var successLabcel: UILabel? @IBOutlet weak var subTitleLabel: UILabel? // Closures /// executed when user taps on Continue button open static var onContinoue: (() -> Void)? /// executed when user taps on Cancel button open static var onCancel: (() -> Void)? /// viewwillappear override override open func viewWillAppear(_ animated: Bool) { if MOHUD.me != nil { self.commonSetup(MOHUD.me!) } } //MARK: Constructor class func ME(_ _me:MOHUD?) -> MOHUD?{ // dismiss() // if any there dismiss it me = _me if let me = _me { // me.commonSetup(me) return me } return nil }//0x7ff102d7e410 //MARK: Factory class func MakeProgressHUD() { ME(self.make(.progress) as? MOHUD) } class func MakeSuccessHUD() { ME(self.make(.success) as? MOHUD) } class func MakeFailureHUD() { ME(self.make(.failure) as? MOHUD) } class func MakeSubtitleHUD() { ME(self.make(.subtitle) as? MOHUD) } // MARK: - Public // MARK: Subtitle /// SHOW SUBTITLE HUD WITH TITLE AND SUBTITLE open class func showSubtitle(title:String, subtitle:String, withCancelAndContinue: Bool = false) { MakeSubtitleHUD() MOHUDTexts.subtitleStyleSubtitlePleaseWait = subtitle MOHUDTexts.subtitleStyleTitleConnecting = title MOHUD.me?.show() me?.buttonsContainer?.isHidden = !withCancelAndContinue } //MARK: Fail /// SHOW FAILURE HUD WITH MESSAGE open class func showWithError(_ errorString:String) { MakeFailureHUD() MOHUDTexts.errorTitle = errorString MOHUD.me?.show() MOHUD.me?.hide(afterDelay: 2) } //MARK: Success /// SHOW SUCCESS HUD WITH MESSAGE open class func showSuccess(_ successString: String) { MakeSuccessHUD() MOHUDTexts.successTitle = successString MOHUD.me?.show() MOHUD.me?.hide(afterDelay: 2) } //MARK: Default show /// SHOW THE DEFAUL HUD WITH LOADING MESSAGE open class func show(_ withCancelAndContinue: Bool = false) { MakeProgressHUD() MOHUD.me?.show() me?.buttonsContainer?.isHidden = !withCancelAndContinue } /// Show with Status open class func showWithStatus(_ status: String, withCancelAndContinue: Bool = false) { MakeProgressHUD() MOHUDTexts.defaultLoadingTitle = status MOHUD.me?.show() me?.buttonsContainer?.isHidden = !withCancelAndContinue } /// Dismiss the HUD open class func dismiss() { // MOHUD.onCancel = nil // MOHUD.onContinoue = nil // MOHUDTexts.resetDefaults() if let _me = me { UIView.animate(withDuration: 0.45, delay: 0, options: UIViewAnimationOptions(), animations: { () -> Void in _me.view.alpha = 0; }) { (finished) -> Void in _me.view.removeFromSuperview() } } } //MARK: Show/hide and timer fileprivate func show() { MOHUD.me?.view.alpha = 0; //NOTE: Keywindow should be shown first if let keywindow = UIApplication.shared.windows.last { keywindow.addSubview(self.view) UIView.animate(withDuration: 1.55, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: UIViewAnimationOptions(), animations: { () -> Void in MOHUD.me?.view.alpha = 1; }) { (finished) -> Void in } } } /// Change the Style of the Hud LIGHT/DARK/EXTRALIGHT open class func setBlurStyle(_ style: UIBlurEffectStyle) { me?.loaderContainer?.effect = UIBlurEffect(style: style) let isDark = style == .dark let darkColor = UIColor ( red: 0.04, green: 0.0695, blue: 0.061, alpha: 0.6 ) let lightColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 ) me?.subTitleLabel?.textColor = isDark ? UIColor.white : UIColor.black me?.statusLabel?.textColor = isDark ? UIColor.white : UIColor.black me?.titleLabel?.textColor = isDark ? UIColor.white : UIColor.black me?.activityIndicator?.activityIndicatorViewStyle = isDark ? .whiteLarge : .gray me?.buttonsContainer?.backgroundColor = isDark ? darkColor : lightColor me?.continueButton?.setTitleColor(isDark ? UIColor.white : UIColor.black, for: UIControlState()) me?.cancelButton?.setTitleColor(isDark ? UIColor.white : UIColor.black, for: UIControlState()) } /// hide Timer used when waiting for a hud to hide open static func hideAfter(_ delay: TimeInterval) { MOHUD.me?.hide(afterDelay: delay) } fileprivate var hideTimer: Timer? fileprivate func hide(afterDelay delay: TimeInterval) { hideTimer?.invalidate() hideTimer = Timer.scheduledTimer(timeInterval: delay, target: self.classForCoder, selector: #selector(MOHUD.dismiss), userInfo: nil, repeats: false) } } // MARK: - IBActions extension MOHUD { @IBAction fileprivate func hideHud(_ sender: AnyObject? = nil) { MOHUD.dismiss() } @IBAction func cancelProcess(_ sender: AnyObject) { MOHUD.onCancel?() hideHud() } @IBAction func continueWithoutCancelling(_ sender: AnyObject) { MOHUD.onContinoue?() hideHud() } } extension MOHUD { func commonSetup(_ hud: MOHUD) { hud.titleLabel?.adjustsFontSizeToFitWidth = true // Set labels texts hud.errorLabel?.text = MOHUDTexts.errorTitle hud.titleLabel?.text = MOHUDTexts.subtitleStyleTitleConnecting hud.subTitleLabel?.text = MOHUDTexts.subtitleStyleSubtitlePleaseWait hud.successLabcel?.text = MOHUDTexts.successTitle hud.continueButton?.setTitle(MOHUDTexts.continueButtonTitle, for: UIControlState()) hud.cancelButton?.setTitle(MOHUDTexts.cancelButtonTitle, for: UIControlState()) hud.statusLabel?.text = MOHUDTexts.defaultLoadingTitle } } // MARK: - UTILITIES /// set of view inpectables extension UIView { /// border color inspectable prop. @IBInspectable public var borderColor: UIColor { set { self.layer.borderColor = newValue.cgColor } get { return UIColor(cgColor: self.layer.borderColor!) } } /// modify self.layer.borderWidth @IBInspectable public var borderWidth: CGFloat { set { self.layer.borderWidth = newValue } get { return self.layer.borderWidth } } /// modify self.cornerRadius and set clipsTobounds to true @IBInspectable public var cornerRadius: CGFloat { set { self.layer.cornerRadius = newValue self.clipsToBounds = true } get { return self.layer.cornerRadius } } } //MARK: - Scenses organizing //MARK: - struct MOStoryBoardID { static let progress = "Default" static let subtitle = "subtitle" static let success = "success" static let failure = "failure" } enum MOSceneType { case progress,success,failure,subtitle } extension MOHUD { class func make(_ type : MOSceneType) -> AnyObject { let mainStoryBoard: UIStoryboard = UIStoryboard(name: "MOHUD", bundle: Bundle(for: MOHUD.self)) switch type { case .progress: return mainStoryBoard.instantiateViewController(withIdentifier: MOStoryBoardID.progress) case .success: return mainStoryBoard.instantiateViewController(withIdentifier: MOStoryBoardID.success) case .failure: return mainStoryBoard.instantiateViewController(withIdentifier: MOStoryBoardID.failure) case .subtitle: return mainStoryBoard.instantiateViewController(withIdentifier: MOStoryBoardID.subtitle) } } } /** Default Texts Used by the HUDs These Can be changed before showing the HUD. They are also localization ready . @auther Moath Othman */ public struct MOHUDTexts { public static var continueButtonTitle = MOHUDDefaultTexts.continueButtonTitle public static var cancelButtonTitle = MOHUDDefaultTexts.cancelButtonTitle public static var defaultLoadingTitle = MOHUDDefaultTexts.defaultLoadingTitle public static var subtitleStyleTitleConnecting = MOHUDDefaultTexts.subtitleStyleTitleConnecting public static var subtitleStyleSubtitlePleaseWait = MOHUDDefaultTexts.subtitleStyleSubtitlePleaseWait public static var successTitle = MOHUDDefaultTexts.successTitle public static var errorTitle = MOHUDDefaultTexts.errorTitle /// mark texts to be reset to their default value after the HUD is dismissed public static var isResetable = true /// reset To Defaults if the texts are resettable fileprivate static func resetDefaults() { if isResetable { continueButtonTitle = MOHUDDefaultTexts.continueButtonTitle cancelButtonTitle = MOHUDDefaultTexts.cancelButtonTitle defaultLoadingTitle = MOHUDDefaultTexts.defaultLoadingTitle subtitleStyleTitleConnecting = MOHUDDefaultTexts.subtitleStyleTitleConnecting subtitleStyleSubtitlePleaseWait = MOHUDDefaultTexts.subtitleStyleSubtitlePleaseWait successTitle = MOHUDDefaultTexts.successTitle errorTitle = MOHUDDefaultTexts.errorTitle } } fileprivate struct MOHUDDefaultTexts { static var continueButtonTitle = NSLocalizedString("Continue", comment: "Continue button label") static var cancelButtonTitle = NSLocalizedString("Cancel", comment: "Cancel button label") static var defaultLoadingTitle = NSLocalizedString("Loading", comment: "Normal Loading label") static var subtitleStyleTitleConnecting = NSLocalizedString("Connecting", comment: "Subtitle type Title Text") static var subtitleStyleSubtitlePleaseWait = NSLocalizedString("Please wait", comment: "Subtitle type subTitle Text") static var successTitle = NSLocalizedString("Success", comment: "Success HUD Label Default Text") static var errorTitle = NSLocalizedString("Error", comment: "Error HUD Label Default Text") } }
38.098305
176
0.665451
29d36b5be57144b210fbf5106e466aa8a11a21d0
1,136
// // UrlSessionRestClient.swift // TinyNetworking // // Created by Ismail on 05/01/2017. // Copyright © 2017 Ismail Bozkurt. All rights reserved. // import Foundation public class UrlSessionRestClient: NSObject, RestClient { let defaultSession = URLSession(configuration: URLSessionConfiguration.default) @discardableResult public func GET(url: URL, headers: [String : String]?, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { var request = URLRequest(url: url) if let headers = headers { for key in headers.keys { let value = headers[key] request.addValue(value!, forHTTPHeaderField: key) } } let dataTask = defaultSession.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in var error = error ResponseSerializer().validate(response: response, data: data, error: &error) completion(data, response, error) }) dataTask.resume() return dataTask } }
31.555556
143
0.623239
d5fa15c864340372dd77934d8481391dab4af228
6,926
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. @_exported import AWSSDKSwiftCore import NIO /** Client object for interacting with AWS Macie service. Amazon Macie Amazon Macie is a security service that uses machine learning to automatically discover, classify, and protect sensitive data in AWS. Macie recognizes sensitive data such as personally identifiable information (PII) or intellectual property, and provides you with dashboards and alerts that give visibility into how this data is being accessed or moved. For more information, see the Macie User Guide. */ public struct Macie { //MARK: Member variables public let client: AWSClient public let serviceConfig: ServiceConfig //MARK: Initialization /// Initialize the Macie client /// - parameters: /// - credentialProvider: Object providing credential to sign requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - retryPolicy: Object returning whether retries should be attempted. Possible options are NoRetry(), ExponentialRetry() or JitterRetry() /// - middlewares: Array of middlewares to apply to requests and responses /// - httpClientProvider: HTTPClient to use. Use `createNew` if the client should manage its own HTTPClient. public init( credentialProvider: CredentialProviderFactory? = nil, region: AWSSDKSwiftCore.Region? = nil, partition: AWSSDKSwiftCore.Partition = .aws, endpoint: String? = nil, retryPolicy: RetryPolicy = JitterRetry(), middlewares: [AWSServiceMiddleware] = [], httpClientProvider: AWSClient.HTTPClientProvider = .createNew ) { self.serviceConfig = ServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "MacieService", service: "macie", serviceProtocol: .json(version: "1.1"), apiVersion: "2017-12-19", endpoint: endpoint, possibleErrorTypes: [MacieErrorType.self] ) self.client = AWSClient( credentialProviderFactory: credentialProvider ?? .runtime, serviceConfig: serviceConfig, retryPolicy: retryPolicy, middlewares: middlewares, httpClientProvider: httpClientProvider ) } public func syncShutdown() throws { try client.syncShutdown() } //MARK: API Calls /// Associates a specified AWS account with Amazon Macie as a member account. @discardableResult public func associateMemberAccount(_ input: AssociateMemberAccountRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return client.send(operation: "AssociateMemberAccount", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Associates specified S3 resources with Amazon Macie for monitoring and data classification. If memberAccountId isn't specified, the action associates specified S3 resources with Macie for the current master account. If memberAccountId is specified, the action associates specified S3 resources with Macie for the specified member account. public func associateS3Resources(_ input: AssociateS3ResourcesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AssociateS3ResourcesResult> { return client.send(operation: "AssociateS3Resources", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Removes the specified member account from Amazon Macie. @discardableResult public func disassociateMemberAccount(_ input: DisassociateMemberAccountRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<Void> { return client.send(operation: "DisassociateMemberAccount", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Removes specified S3 resources from being monitored by Amazon Macie. If memberAccountId isn't specified, the action removes specified S3 resources from Macie for the current master account. If memberAccountId is specified, the action removes specified S3 resources from Macie for the specified member account. public func disassociateS3Resources(_ input: DisassociateS3ResourcesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociateS3ResourcesResult> { return client.send(operation: "DisassociateS3Resources", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Lists all Amazon Macie member accounts for the current Amazon Macie master account. public func listMemberAccounts(_ input: ListMemberAccountsRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListMemberAccountsResult> { return client.send(operation: "ListMemberAccounts", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Lists all the S3 resources associated with Amazon Macie. If memberAccountId isn't specified, the action lists the S3 resources associated with Amazon Macie for the current master account. If memberAccountId is specified, the action lists the S3 resources associated with Amazon Macie for the specified member account. public func listS3Resources(_ input: ListS3ResourcesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListS3ResourcesResult> { return client.send(operation: "ListS3Resources", path: "/", httpMethod: "POST", input: input, on: eventLoop) } /// Updates the classification types for the specified S3 resources. If memberAccountId isn't specified, the action updates the classification types of the S3 resources associated with Amazon Macie for the current master account. If memberAccountId is specified, the action updates the classification types of the S3 resources associated with Amazon Macie for the specified member account. public func updateS3Resources(_ input: UpdateS3ResourcesRequest, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateS3ResourcesResult> { return client.send(operation: "UpdateS3Resources", path: "/", httpMethod: "POST", input: input, on: eventLoop) } }
61.839286
415
0.714698
08e24a51621e454e61208a42dab80f17d9b4cf34
5,223
// // UIColor+Extension.swift // XUIKit // // Created by FITZ on 2022/4/24. // import UIKit extension UIColor: XUIKitCompatible {} private extension Int64 { func duplicate4bits() -> Int64 { return (self << 4) + self } } private extension UIColor { private convenience init?(hex3: Int64, alpha: Float) { self.init(red: CGFloat(((hex3 & 0xF00) >> 8).duplicate4bits()) / 255.0, green: CGFloat(((hex3 & 0x0F0) >> 4).duplicate4bits()) / 255.0, blue: CGFloat(((hex3 & 0x00F) >> 0).duplicate4bits()) / 255.0, alpha: CGFloat(alpha)) } private convenience init?(hex4: Int64, alpha: Float?) { self.init(red: CGFloat(((hex4 & 0xF000) >> 12).duplicate4bits()) / 255.0, green: CGFloat(((hex4 & 0x0F00) >> 8).duplicate4bits()) / 255.0, blue: CGFloat(((hex4 & 0x00F0) >> 4).duplicate4bits()) / 255.0, alpha: alpha.map(CGFloat.init(_:)) ?? CGFloat(((hex4 & 0x000F) >> 0).duplicate4bits()) / 255.0) } private convenience init?(hex6: Int64, alpha: Float) { self.init(red: CGFloat((hex6 & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex6 & 0x00FF00) >> 8) / 255.0, blue: CGFloat((hex6 & 0x0000FF) >> 0) / 255.0, alpha: CGFloat(alpha)) } private convenience init?(hex8: Int64, alpha: Float?) { self.init(red: CGFloat((hex8 & 0xFF000000) >> 24) / 255.0, green: CGFloat((hex8 & 0x00FF0000) >> 16) / 255.0, blue: CGFloat((hex8 & 0x0000FF00) >> 8) / 255.0, alpha: alpha.map(CGFloat.init(_:)) ?? CGFloat((hex8 & 0x000000FF) >> 0) / 255.0) } /** Create non-autoreleased color with in the given hex string and alpha. - parameter hexString: The hex string, with or without the hash character. - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: A color with the given hex string and alpha. */ convenience init?(hexString: String, alpha: Float? = nil) { var hex = hexString // Check for hash and remove the hash if hex.hasPrefix("#") { hex = String(hex[hex.index(after: hex.startIndex)...]) } guard let hexVal = Int64(hex, radix: 16) else { self.init() return nil } switch hex.count { case 3: self.init(hex3: hexVal, alpha: alpha ?? 1.0) case 4: self.init(hex4: hexVal, alpha: alpha) case 6: self.init(hex6: hexVal, alpha: alpha ?? 1.0) case 8: self.init(hex8: hexVal, alpha: alpha) default: // Note: // The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases, // so it disallows formation of a situation where it would have to. We consider this a bug to be fixed // in future releases, not a feature. -- Apple Forum self.init() return nil } } /** Create non-autoreleased color with in the given hex value and alpha - parameter hex: The hex value. For example: 0xff8942 (no quotation). - parameter alpha: The alpha value, a floating value between 0 and 1. - returns: color with the given hex value and alpha */ convenience init?(hex: Int, alpha: Float = 1.0) { if (0x000000 ... 0xFFFFFF) ~= hex { self.init(hex6: Int64(hex), alpha: alpha) } else { self.init() return nil } } } public extension XUIKitWrapper where Base: UIColor { /// 通过HEX值生成UIColor static func color(hexString: String, alpha: Float? = nil) -> UIColor { return UIColor(hexString: hexString, alpha: alpha) ?? .clear } /// 生成渐变色 /// - Parameters: /// - colors: 渐变色颜色数组 /// - width: 宽度 /// - height: 高度 /// - axis: 坐标轴 /// - Returns: 渐变色 static func gradient(colors: [UIColor], width: CGFloat, height: CGFloat, axis: NSLayoutConstraint.Axis = .vertical) -> UIColor? { let size = CGSize(width: width, height: height) UIGraphicsBeginImageContextWithOptions(size, false, 0) defer { UIGraphicsEndImageContext() } guard let context = UIGraphicsGetCurrentContext() else { return nil } let colorSpace = CGColorSpaceCreateDeviceRGB() let cgColors = colors.map { $0.cgColor } guard let gradient = CGGradient(colorsSpace: colorSpace, colors: cgColors as CFArray, locations: nil) else { return nil } switch axis { case .vertical: context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: height), options: .drawsBeforeStartLocation) case .horizontal: context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: width, y: 0), options: .drawsBeforeStartLocation) @unknown default: fatalError() } guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return nil } return UIColor(patternImage: image) } }
35.290541
133
0.573234
0162aaa6b91a64b57c5c8f7c036daf59c6663149
4,554
/// /// Copyright (c) 2019 Tjek. All rights reserved. /// import Foundation import UIKit extension IncitoDocument { enum DecodingError: Error { case missingId case missingVersion case missingRootView case invalidJSON } enum JSONKeys: String { case id, version, theme, locale, meta case rootView = "root_view" } public init(jsonData: Data) throws { guard let jsonStr = String(data: jsonData, encoding: .utf8) else { throw DecodingError.invalidJSON } let jsonObj = try JSONSerialization.jsonObject(with: jsonData, options: []) guard let jsonDict = jsonObj as? [String: Any] else { throw DecodingError.invalidJSON } try self.init(jsonDict: jsonDict, jsonStr: jsonStr) } public init(jsonDict: [String: Any], jsonStr: String) throws { self.json = jsonStr self.id = try jsonDict.getValueAs(JSONKeys.id, throwing: DecodingError.missingId) self.version = try jsonDict.getValueAs(JSONKeys.version, throwing: DecodingError.missingVersion) let rootViewDict: [String: Any] = try jsonDict.getValueAs(JSONKeys.rootView, throwing: DecodingError.missingRootView) self.elements = IncitoDocument.Element.allElements(in: rootViewDict) self.locale = jsonDict.getValueAs(JSONKeys.locale) var meta: [String: JSONValue] = [:] (jsonDict.getValue(JSONKeys.meta, as: [String: Any?].self) ?? [:]) .forEach({ meta[$0.key] = JSONValue($0.value) }) self.meta = meta let bgColorStr = jsonDict.getValue(JSONKeys.theme, as: [String: Any].self)?["background_color"] as? String self.backgroundColor = bgColorStr.flatMap(UIColor.init(webString:)) } } extension IncitoDocument.Element { enum JSONKeys: String { case id, role, meta, link, title, src case featureLabels = "feature_labels" } init?(jsonDict: [String: Any]) { // if there is no id, then fall back to the guard let id: Identifier = jsonDict.getValueAs(JSONKeys.id) else { return nil } self.id = id self.role = jsonDict.getValueAs(JSONKeys.role) self.meta = { var meta: [String: JSONValue] = [:] (jsonDict.getValue(JSONKeys.meta, as: [String: Any?].self) ?? [:]) .forEach({ meta[$0.key] = JSONValue($0.value) }) return meta }() self.featureLabels = jsonDict.getValue(JSONKeys.featureLabels, as: [String].self) ?? [] self.link = jsonDict.getValue(JSONKeys.link, as: String.self).flatMap(URL.init(string:)) self.title = jsonDict.getValueAs(JSONKeys.title) } static func allElements(in elementDict: [String: Any]) -> [IncitoDocument.Element] { var foundElements: [IncitoDocument.Element] = [] recurseAllElements(in: elementDict, foundElements: &foundElements) return foundElements } static func recurseAllElements(in elementDict: [String: Any], foundElements: inout [IncitoDocument.Element]) { if let element = IncitoDocument.Element(jsonDict: elementDict) { foundElements.append(element) } if let kids = elementDict["child_views"] as? [[String: Any]] { kids.forEach({ recurseAllElements(in: $0, foundElements: &foundElements) }) } } } // MARK: - Utils extension Dictionary { func getValueMap<K: RawRepresentable, T>(_ key: K, _ transform: (Value) -> T) -> T? where K.RawValue == Key { return self[key.rawValue].map(transform) } func getValueFlatMap<K: RawRepresentable, T>(_ key: K, _ transform: (Value) -> T?) -> T? where K.RawValue == Key { return self[key.rawValue].flatMap(transform) } func getValueAs<K: RawRepresentable, T>(_ key: K) -> T? where K.RawValue == Key { return getValue(key, as: T.self) } func getValue<K: RawRepresentable, T>(_ key: K, as: T.Type) -> T? where K.RawValue == Key { return getValueFlatMap(key, { $0 as? T }) } func getValueAs<K: RawRepresentable, T>(_ key: K, throwing error: Error) throws -> T where K.RawValue == Key { guard let v = getValue(key, as: T.self) else { throw error } return v } }
33.240876
125
0.592227
690817ae8c9a2c76d6f1508f57618d87d4d60db2
1,314
import Foundation import UIKit protocol AttendeeCellCustomizationProtocol { func customizeCellWithAttendee(_ attendee: Attendee?, _ order: Int) } /* Cell for representing Attendee object in the Attendee List */ class AttendeeListCell: UITableViewCell, AttendeeCellCustomizationProtocol { @IBOutlet weak var orderLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ageLabel: UILabel! @IBOutlet weak var companyLabel: UILabel! override func prepareForReuse() { super.prepareForReuse() customizeCellWithAttendee(nil, 0) } func customizeCellWithAttendee(_ attendee: Attendee?, _ order: Int) { nameLabel.text = "\(attendee?.firstName ?? "-") \(attendee?.lastName ?? "-")" if let age = attendee?.age { ageLabel.text = "\(age.description) years old" } else { ageLabel.text = "" } companyLabel.text = "\(attendee?.company ?? "")" orderLabel.text = "\(order)" } } // Basicly this should be an extension for UIView, but here it's used only for that cell, thats why it's extension for a AttendeeListCell extension AttendeeListCell { @nonobjc static var defaultReuseIdentifier : String { return String(describing: self) } }
27.957447
137
0.660578
5d35229056bfba7fcb833dc65ed293bbc45154f3
12,282
// // Copyright (c) 2018 Related Code - http://relatedcode.com // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //------------------------------------------------------------------------------------------------------------------------------------------------- class EditProfileView: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, CountriesDelegate { @IBOutlet var tableView: UITableView! @IBOutlet var viewHeader: UIView! @IBOutlet var imageUser: UIImageView! @IBOutlet var labelInitials: UILabel! @IBOutlet var cellFirstname: UITableViewCell! @IBOutlet var cellLastname: UITableViewCell! @IBOutlet var cellCountry: UITableViewCell! @IBOutlet var cellLocation: UITableViewCell! @IBOutlet var cellPhone: UITableViewCell! @IBOutlet var fieldFirstname: UITextField! @IBOutlet var fieldLastname: UITextField! @IBOutlet var labelPlaceholder: UILabel! @IBOutlet var labelCountry: UILabel! @IBOutlet var fieldLocation: UITextField! @IBOutlet var fieldPhone: UITextField! private var isOnboard = false //--------------------------------------------------------------------------------------------------------------------------------------------- func myInit(isOnboard isOnboard_: Bool) { isOnboard = isOnboard_ } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() title = "Edit Profile" navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(actionCancel)) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(actionDone)) let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tableView.addGestureRecognizer(gestureRecognizer) gestureRecognizer.cancelsTouchesInView = false tableView.tableHeaderView = viewHeader imageUser.layer.cornerRadius = imageUser.frame.size.width / 2 imageUser.layer.masksToBounds = true loadUser() } //--------------------------------------------------------------------------------------------------------------------------------------------- override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) dismissKeyboard() } //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func dismissKeyboard() { view.endEditing(true) } // MARK: - Backend actions //--------------------------------------------------------------------------------------------------------------------------------------------- func loadUser() { let user = FUser.currentUser() labelInitials.text = user.initials() if let picture = user[FUSER_PICTURE] as? String { DownloadManager.image(link: picture) { path, error, network in if (error == nil) { self.imageUser.image = UIImage(contentsOfFile: path!) self.labelInitials.text = nil } } } fieldFirstname.text = user[FUSER_FIRSTNAME] as? String fieldLastname.text = user[FUSER_LASTNAME] as? String labelCountry.text = user[FUSER_COUNTRY] as? String fieldLocation.text = user[FUSER_LOCATION] as? String fieldPhone.text = user[FUSER_PHONE] as? String let loginMethod = user[FUSER_LOGINMETHOD] as? String fieldPhone.isUserInteractionEnabled = (loginMethod != LOGIN_PHONE) updateDetails() } //--------------------------------------------------------------------------------------------------------------------------------------------- func saveUser(firstname: String, lastname: String, country: String, location: String, phone: String) { let user = FUser.currentUser() user[FUSER_FIRSTNAME] = firstname user[FUSER_LASTNAME] = lastname user[FUSER_FULLNAME] = "\(firstname) \(lastname)" user[FUSER_COUNTRY] = country user[FUSER_LOCATION] = location user[FUSER_PHONE] = phone user.saveInBackground(block: { error in if (error == nil) { Account.update() } else { ProgressHUD.showError("Network error.") } }) } //--------------------------------------------------------------------------------------------------------------------------------------------- func saveUserPicture(link: String) { let user = FUser.currentUser() user[FUSER_PICTURE] = link user.saveInBackground(block: { error in if (error == nil) { Account.update() } else { ProgressHUD.showError("Network error.") } }) } //--------------------------------------------------------------------------------------------------------------------------------------------- func saveUserThumbnail(link: String) { let user = FUser.currentUser() user[FUSER_THUMBNAIL] = link user.saveInBackground(block: { error in if (error != nil) { ProgressHUD.showError("Network error.") } }) } // MARK: - User actions //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionCancel() { if (isOnboard) { LogoutUser(delAccount: DEL_ACCOUNT_ALL) } dismiss(animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- @objc func actionDone() { let firstname = fieldFirstname.text ?? "" let lastname = fieldLastname.text ?? "" let country = labelCountry.text ?? "" let location = fieldLocation.text ?? "" let phone = fieldPhone.text ?? "" if (firstname.count == 0) { ProgressHUD.showError("Firstname must be set."); return } if (lastname.count == 0) { ProgressHUD.showError("Lastname must be set."); return } if (country.count == 0) { ProgressHUD.showError("Country must be set."); return } if (location.count == 0) { ProgressHUD.showError("Location must be set."); return } if (phone.count == 0) { ProgressHUD.showError("Phone number must be set."); return } saveUser(firstname: firstname, lastname: lastname, country: country, location: location, phone: phone) dismiss(animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- @IBAction func actionPhoto(_ sender: Any) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Open Camera", style: .default, handler: { action in PresentPhotoCamera(target: self, edit: true) })) alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { action in PresentPhotoLibrary(target: self, edit: true) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- func actionCountries() { let countriesView = CountriesView() countriesView.delegate = self let navController = NavigationController(rootViewController: countriesView) present(navController, animated: true) } // MARK: - UIImagePickerControllerDelegate //--------------------------------------------------------------------------------------------------------------------------------------------- func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let image = info[.editedImage] as? UIImage { uploadUserPicture(image: image) uploadUserThumbnail(image: image) } picker.dismiss(animated: true) } //--------------------------------------------------------------------------------------------------------------------------------------------- func uploadUserPicture(image: UIImage) { let squared = Image.square(image: image, size: 300) if let data = image.jpegData(compressionQuality: 0.6) { UploadManager.upload(data: data, name: "profile_picture", ext: "jpg", completion: { link, error in if (error == nil) { self.labelInitials.text = nil self.imageUser.image = squared DownloadManager.saveImage(data: data, link: link!) self.saveUserPicture(link: link!) } else { ProgressHUD.showError("Picture upload error.") } }) } } //--------------------------------------------------------------------------------------------------------------------------------------------- func uploadUserThumbnail(image: UIImage) { let squared = Image.square(image: image, size: 100) if let data = squared.jpegData(compressionQuality: 0.6) { UploadManager.upload(data: data, name: "profile_thumbnail", ext: "jpg", completion: { link, error in if (error == nil) { DownloadManager.saveImage(data: data, link: link!) self.saveUserThumbnail(link: link!) } else { ProgressHUD.showError("Thumbnail upload error.") } }) } } // MARK: - CountriesDelegate //--------------------------------------------------------------------------------------------------------------------------------------------- func didSelectCountry(name: String, code: String) { labelCountry.text = name fieldLocation.becomeFirstResponder() updateDetails() } // MARK: - Table view data source //--------------------------------------------------------------------------------------------------------------------------------------------- func numberOfSections(in tableView: UITableView) -> Int { return 2 } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 4 } if (section == 1) { return 1 } return 0 } //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath.section == 0) && (indexPath.row == 0) { return cellFirstname } if (indexPath.section == 0) && (indexPath.row == 1) { return cellLastname } if (indexPath.section == 0) && (indexPath.row == 2) { return cellCountry } if (indexPath.section == 0) && (indexPath.row == 3) { return cellLocation } if (indexPath.section == 1) && (indexPath.row == 0) { return cellPhone } return UITableViewCell() } // MARK: - Table view delegate //--------------------------------------------------------------------------------------------------------------------------------------------- func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if (indexPath.section == 0) && (indexPath.row == 2) { actionCountries() } } // MARK: - UITextField delegate //--------------------------------------------------------------------------------------------------------------------------------------------- func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == fieldFirstname) { fieldLastname.becomeFirstResponder() } if (textField == fieldLastname) { actionCountries() } if (textField == fieldLocation) { fieldPhone.becomeFirstResponder() } if (textField == fieldPhone) { actionDone() } return true } // MARK: - Helper methods //--------------------------------------------------------------------------------------------------------------------------------------------- func updateDetails() { labelPlaceholder.isHidden = labelCountry.text != nil } }
38.261682
190
0.523205
28324c8e6589d18b0c165ad3d0bf98e355552e01
297
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Device", products: [ .library(name: "Device", targets: ["Device"]) ], targets: [ .target(name: "Device"), .testTarget(name: "DeviceTests", dependencies: ["Device"]) ] )
21.214286
66
0.585859
2229f16274e60b15393b2e31a8db9870be164faa
1,354
// // AppDelegate.swift // Prework // // Created by Shad Gabrielle Reyes on 8/21/21. // 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.594595
179
0.745938
2f6752075b74cba2f44c30b4c56efdc696079e84
2,424
// // DetailTourViewController.swift // AudioTour // // Created by Максим Сурков on 27.03.2021. // import Foundation import UIKit import AVFoundation class DetailTourViewController: UIViewController{ var player: AVAudioPlayer? var detailTourModel: DetailTourModel! var detailTourView: DetailTourView { view as! DetailTourView } override func loadView() { view = DetailTourView(handleContinue: showAudioAlert) view.backgroundColor = .white } override func viewDidLoad() { super.viewDidLoad() setupViews() detailTourModel.loadRoute() } private func setupViews() { detailTourView.nameLabel.text = detailTourModel.tour.title detailTourView.organizationNameLabel.text = detailTourModel.tour.contentProvider.name } func updateView(with route: Route, tour: Tour, viewModel: DetailViewModel) { detailTourView.updateViewModel(viewModel: viewModel) detailTourView.descriptionView.text = route.content[0].desc let rating = Int(tour.reviews?.ratingAverage ?? 0) let filledStarsCount = (rating/2) let halfFilledStarsCount = (rating % 2) == 0 ? 0 : 1 for i in 0..<filledStarsCount { detailTourView.starImageViewsArray[i].image = UIImage(systemName: "star.fill") } for i in 0..<halfFilledStarsCount { detailTourView.starImageViewsArray[filledStarsCount + i].image = UIImage(systemName: "star.leadinghalf.fill") } } private func showAudioAlert(){ let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Продолжить с аудиогидом", style: .default, handler: { _ in self.showMapVC() })) alert.addAction(UIAlertAction(title: "Оставьте меня в тишине!", style: .default, handler: { _ in self.showMapVC() })) alert.addAction(UIAlertAction(title: "Отмена", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } private func showMapVC() { let vc = MapViewController() let model = MapModel(vc: vc, selectedRoute: detailTourModel.route!, selectedTour: detailTourModel.tour) vc.mapModel = model navigationController?.pushViewController(vc, animated: true) } }
32.756757
121
0.656353
087d7ec9f20a891fa678055d157744d63260f00b
11,494
import XCTest @testable import Apollo import ApolloTestSupport import StarWarsAPI class ParseQueryResponseTests: XCTestCase { func testHeroNameQuery() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "name": "R2-D2"] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "R2-D2") } func testHeroNameQueryWithMissingValue() { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid"] ] ]) XCTAssertThrowsError(try response.parseResult().await()) { error in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["hero", "name"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testHeroNameQueryWithDifferentType() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "name": 10] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "10") } func testHeroNameQueryWithWrongType() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "name": 10.0] ] ]) XCTAssertThrowsError(try response.parseResult().await()) { error in if let error = error as? GraphQLResultError, case JSONDecodingError.couldNotConvert(let value, let expectedType) = error.underlying { XCTAssertEqual(error.path, ["hero", "name"]) XCTAssertEqual(value as? Double, 10.0) XCTAssertTrue(expectedType == String.self) } else { XCTFail("Unexpected error: \(error)") } } } func testHeroAppearsInQuery() throws { let query = HeroAppearsInQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "appearsIn": ["NEWHOPE", "EMPIRE", "JEDI"]] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.appearsIn, [.newhope, .empire, .jedi]) } func testHeroAppearsInQueryWithEmptyList() throws { let query = HeroAppearsInQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "appearsIn": []] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.appearsIn, []) } func testHeroAndFriendsNamesQuery() throws { let query = HeroAndFriendsNamesQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": [ "name": "R2-D2", "__typename": "Droid", "friends": [ ["__typename": "Human", "name": "Luke Skywalker"], ["__typename": "Human", "name": "Han Solo"], ["__typename": "Human", "name": "Leia Organa"] ] ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "R2-D2") let friendsNames = result.data?.hero?.friends?.compactMap { $0?.name } XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"]) } func testHeroAndFriendsNamesQueryWithEmptyList() throws { let query = HeroAndFriendsNamesQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": [ "name": "R2-D2", "__typename": "Droid", "friends": [] ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "R2-D2") XCTAssertEqual(result.data?.hero?.friends?.isEmpty, true) } func testHeroAndFriendsNamesWithFragmentQuery() throws { let query = HeroAndFriendsNamesWithFragmentQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": [ "name": "R2-D2", "__typename": "Droid", "friends": [ ["__typename": "Human", "name": "Luke Skywalker"], ["__typename": "Human", "name": "Han Solo"], ["__typename": "Human", "name": "Leia Organa"] ] ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "R2-D2") let friendsNames = result.data?.hero?.fragments.friendsNames.friends?.compactMap { $0?.name } XCTAssertEqual(friendsNames, ["Luke Skywalker", "Han Solo", "Leia Organa"]) } func testTwoHeroesQuery() throws { let query = TwoHeroesQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "r2": ["__typename": "Droid", "name": "R2-D2"], "luke": ["__typename": "Human", "name": "Luke Skywalker"] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.r2?.name, "R2-D2") XCTAssertEqual(result.data?.luke?.name, "Luke Skywalker") } func testHeroDetailsQueryDroid() throws { let query = HeroDetailsQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "name": "R2-D2", "primaryFunction": "Astromech"] ] ]) let (result, _) = try response.parseResult().await() let droid = try XCTUnwrap(result.data?.hero?.asDroid, "Wrong type") XCTAssertEqual(droid.primaryFunction, "Astromech") } func testHeroDetailsQueryHuman() throws { let query = HeroDetailsQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Human", "name": "Luke Skywalker", "height": 1.72] ] ]) let (result, _) = try response.parseResult().await() let human = try XCTUnwrap(result.data?.hero?.asHuman, "Wrong type") XCTAssertEqual(human.height, 1.72) } func testHeroDetailsQueryUnknownTypename() throws { let query = HeroDetailsQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Pokemon", "name": "Charmander"] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.hero?.name, "Charmander") } func testHeroDetailsQueryMissingTypename() throws { let query = HeroDetailsQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["name": "Luke Skywalker", "height": 1.72] ] ]) XCTAssertThrowsError(try response.parseResult().await()) { error in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["hero", "__typename"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } func testHeroDetailsWithFragmentQueryDroid() throws { let query = HeroDetailsWithFragmentQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Droid", "name": "R2-D2", "primaryFunction": "Astromech"] ] ]) let (result, _) = try response.parseResult().await() let droid = try XCTUnwrap(result.data?.hero?.fragments.heroDetails.asDroid, "Wrong type") XCTAssertEqual(droid.primaryFunction, "Astromech") } func testHeroDetailsWithFragmentQueryHuman() throws { let query = HeroDetailsWithFragmentQuery() let response = GraphQLResponse(operation: query, body: [ "data": [ "hero": ["__typename": "Human", "name": "Luke Skywalker", "height": 1.72] ] ]) let (result, _) = try response.parseResult().await() let human = try XCTUnwrap(result.data?.hero?.fragments.heroDetails.asHuman, "Wrong type") XCTAssertEqual(human.height, 1.72) } func testHumanQueryWithNullResult() throws { let query = HumanQuery(id: "9999") let response = GraphQLResponse(operation: query, body: [ "data": [ "human": NSNull() ] ]) let (result, _) = try response.parseResult().await() XCTAssertNil(result.data?.human) } func testHumanQueryWithMissingResult() throws { let query = HumanQuery(id: "9999") let response = GraphQLResponse(operation: query, body: [ "data": [:] ]) XCTAssertThrowsError(try response.parseResult().await()) { error in if case let error as GraphQLResultError = error { XCTAssertEqual(error.path, ["human"]) XCTAssertMatch(error.underlying, JSONDecodingError.missingValue) } else { XCTFail("Unexpected error: \(error)") } } } // MARK: Mutations func testCreateReviewForEpisode() throws { let mutation = CreateReviewForEpisodeMutation(episode: .jedi, review: ReviewInput(stars: 5, commentary: "This is a great movie!")) let response = GraphQLResponse(operation: mutation, body: [ "data": [ "createReview": [ "__typename": "Review", "stars": 5, "commentary": "This is a great movie!" ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertEqual(result.data?.createReview?.stars, 5) XCTAssertEqual(result.data?.createReview?.commentary, "This is a great movie!") } // MARK: - Error responses func testErrorResponseWithoutLocation() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "errors": [ [ "message": "Some error", ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertNil(result.data) XCTAssertEqual(result.errors?.first?.message, "Some error") XCTAssertNil(result.errors?.first?.locations) } func testErrorResponseWithLocation() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "errors": [ [ "message": "Some error", "locations": [ ["line": 1, "column": 2] ] ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertNil(result.data) XCTAssertEqual(result.errors?.first?.message, "Some error") XCTAssertEqual(result.errors?.first?.locations?.first?.line, 1) XCTAssertEqual(result.errors?.first?.locations?.first?.column, 2) } func testErrorResponseWithCustomError() throws { let query = HeroNameQuery() let response = GraphQLResponse(operation: query, body: [ "errors": [ [ "message": "Some error", "userMessage": "Some message" ] ] ]) let (result, _) = try response.parseResult().await() XCTAssertNil(result.data) XCTAssertEqual(result.errors?.first?.message, "Some error") XCTAssertEqual(result.errors?.first?["userMessage"] as? String, "Some message") } }
28.807018
139
0.596398
bb8ba376703eb098561f333a2e0cb1592b9c48fd
1,881
// // Copyright (c) Chris Bartley 2020. Licensed under the MIT license. See LICENSE file. // import XCTest @testable import BuzzBLE class NoOpDelegate: BuzzDelegate { let testCase: XCTestCase init(_ testCase: XCTestCase) { self.testCase = testCase } func buzz(_ device: Buzz, isCommunicationEnabled: Bool, error: Error?) { print("NoOpDelegate.isCommunicationEnabled: \(isCommunicationEnabled)") } func buzz(_ device: Buzz, isAuthorized: Bool, errorMessage: String?) { print("NoOpDelegate.isAuthorized: \(isAuthorized) errorMessage=\(String(describing: errorMessage))") } func buzz(_ device: Buzz, batteryInfo: Buzz.BatteryInfo) { print("NoOpDelegate.batteryInfo: \(batteryInfo)") } func buzz(_ device: Buzz, deviceInfo: Buzz.DeviceInfo) { print("NoOpDelegate.deviceInfo: \(deviceInfo)") } func buzz(_ device: Buzz, isMicEnabled: Bool) { print("NoOpDelegate.isMicEnabled: \(isMicEnabled)") } func buzz(_ device: Buzz, areMotorsEnabled: Bool) { print("NoOpDelegate.areMotorsEnabled: \(areMotorsEnabled)") } func buzz(_ device: Buzz, isMotorsQueueCleared: Bool) { print("NoOpDelegate.isMotorsQueueCleared: \(isMotorsQueueCleared)") } func buzz(_ device: Buzz, responseError error: Error) { print("NoOpDelegate.responseError: \(error)") } func buzz(_ device: Buzz, unknownCommand command: String) { print("NoOpDelegate.unknownCommand: \(command)") } func buzz(_ device: Buzz, badRequestFor command: Buzz.Command, errorMessage: String?) { print("NoOpDelegate.badRequestFor: \(command) error message = [\(String(describing: errorMessage))]") } func buzz(_ device: Buzz, failedToParse responseMessage: String, forCommand command: Buzz.Command) { print("NoOpDelegate.failedToParse: \(responseMessage) forCommand \(command)") } }
32.431034
107
0.701223
d746762bcfb489e91b91e0fe3979462e8d2017fe
2,401
// // RunningColorVector.swift // Biots // // Created by Robert Silverman on 9/21/18. // Copyright © 2018 fep. All rights reserved. // import Foundation class RunningColorVector { var memory: Int = 100 var values: [ColorVector] = [] var decayedSum: ColorVector = .zero init(memory: Int = 100) { self.memory = memory } func addValue(_ value: ColorVector) { if values.count == memory { values.remove(at: 0) } values.append(value) decayedSum += value } var sum: ColorVector { var sum: ColorVector = .zero values.forEach({ sum += $0 }) return sum } var average: ColorVector { return values.count == 0 ? .zero : sum / CGFloat(values.count) } var maximum: ColorVector { guard values.count > 0 else { return .zero } guard values.count > 1 else { return values[0] } var maxRed: CGFloat = .zero var maxGreen: CGFloat = .zero var maxBlue: CGFloat = .zero values.forEach({ colorVector in maxRed = max(colorVector.red, maxRed) maxGreen = max(colorVector.green, maxGreen) maxBlue = max(colorVector.blue, maxBlue) }) return ColorVector(red: maxRed, green: maxGreen, blue: maxBlue) } func averageOfMostRecent(memory: Int) -> ColorVector { guard values.count > 0 else { return .zero } guard values.count > 1 else { return values[0] } guard values.count > memory else { return average } // there are more than `memory` values let suffix = values.count - memory let memoryValues = values.suffix(from: suffix) var sum: ColorVector = .zero memoryValues.forEach({ sum += $0 }) return memoryValues.count == 0 ? .zero : sum / CGFloat(memoryValues.count) } func maxOfMostRecent(memory: Int) -> ColorVector { guard values.count > 0 else { return .zero } guard values.count > 1 else { return values[0] } guard values.count > memory else { return maximum } // there are more than `memory` values let suffix = values.count - memory let memoryValues = values.suffix(from: suffix) var maxRed: CGFloat = .zero var maxGreen: CGFloat = .zero var maxBlue: CGFloat = .zero memoryValues.forEach({ colorVector in maxRed = max(colorVector.red, maxRed) maxGreen = max(colorVector.green, maxGreen) maxBlue = max(colorVector.blue, maxBlue) }) return ColorVector(red: maxRed, green: maxGreen, blue: maxBlue) } func decay(by amount: CGFloat = 0.9) { decayedSum *= amount } }
24.252525
76
0.676385
9150dba79322a313533ec2d5ff9fc4b3c62519bf
7,240
// // MonalUITests.swift // MonalUITests // // Created by Friedrich Altheide on 06.03.21. // Copyright © 2021 Monal.im. All rights reserved. // import XCTest class MonalUITests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func intro(app: XCUIApplication) { // wait for launch sleep(1) let elementsQuery = app.scrollViews["intro_scroll"].otherElements elementsQuery.buttons["Welcome to Monal, Chat for free with your friends, colleagues and family!"].swipeLeft() sleep(1) elementsQuery.buttons["Choices Galore, Use your existing account or make a new one on the many servers around the world"].swipeLeft() sleep(1) elementsQuery.buttons["Escape The Garden, You are not trapped in a garden. Talk to anyone else without anyone tracking you."].swipeLeft() sleep(1) elementsQuery.buttons["Spread The Word, If you like Monal, please let others know and leave a review"].swipeLeft() sleep(1) } func introSkip(app: XCUIApplication) { // wait for launch sleep(1) app.buttons["Skip"].tap() sleep(1) } func test_0001_DBInit() throws { let app = XCUIApplication() app.launchArguments = ["--reset"] app.launch() } func test_0002_Intro() throws { let app = XCUIApplication() app.launchArguments = ["--reset"] app.launch() intro(app: app) let elementsQuery2 = app.scrollViews.otherElements elementsQuery2.textFields["[email protected]"].tap() elementsQuery2.secureTextFields["Password"].tap() } func test_0003_IntroSkip() throws { let app = XCUIApplication() app.launchArguments = ["--reset"] app.launch() introSkip(app: app) app.scrollViews.otherElements.buttons["Set up an account later"].tap() let chatsNavigationBar = app.navigationBars["Chats"] chatsNavigationBar.buttons["Add"].tap() let closeButton = app.alerts["No enabled account found"].scrollViews.otherElements.buttons["Close"] closeButton.tap() chatsNavigationBar.buttons["Compose"].tap() closeButton.tap() } func test_0004_ResetTime() throws { let app = XCUIApplication() app.launchArguments = ["--reset"] if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { app.launch() } } } func test_0005_Register() throws { let app = XCUIApplication() app.launchArguments = ["--reset"] app.launch() introSkip(app: app) let elementsQuery = app.scrollViews.otherElements let registerStaticText = elementsQuery.buttons["Register"] registerStaticText.tap() app.scrollViews.otherElements.buttons["Terms of service"].tap() // wait for safari window to open sleep(5) app.buttons["Done"].tap() elementsQuery.textFields["Username"].tap() // create random username elementsQuery.textFields["Username"].typeText(String(format: "MonalTestclient-%d", Int.random(in: 1000..<999999))) elementsQuery.secureTextFields["Password"].tap() sleep(1) elementsQuery.secureTextFields["Password"].typeText(randomPassword()) registerStaticText.tap() // wait for register hud sleep(10) let startChattingStaticText = app.buttons["Start Chatting"] startChattingStaticText.tap() sleep(1) app.navigationBars["Privacy Settings"].buttons["Close"].tap() startChattingStaticText.tap() } func test_0006_LaunchPerformance() throws { if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) { XCUIApplication().launch() } } } func test_0007_PlusAndContactsButtons() throws { let app = XCUIApplication() app.launch() let chatsNavigationBar = app.navigationBars["Chats"] chatsNavigationBar.buttons["Add"].tap() let tablesQuery = app.tables tablesQuery.staticTexts["Add a New Contact"].tap() app.navigationBars["Add Contact"].buttons["New"].tap() tablesQuery.staticTexts["Join a Group Chat"].tap() app.navigationBars["Join Group Chat"].buttons["New"].tap() tablesQuery.staticTexts["View Contact Requests"].tap() app.navigationBars["Contact Requests"].buttons["New"].tap() app.navigationBars["New"].buttons["Close"].tap() chatsNavigationBar.buttons["Compose"].tap() let contactsNavigationBar = app.navigationBars["Contacts"] contactsNavigationBar.children(matching: .button).element(boundBy: 1).tap() app.navigationBars["Group Chat"].buttons["Contacts"].tap() contactsNavigationBar.buttons["Close"].tap() } func sendMsg(txt: String) { let app = XCUIApplication() XCTAssertTrue(app.buttons["microphone"].exists) XCTAssertFalse(app.buttons["Send"].exists) app.textViews["NewChatMessageTextField"].tap() app.textViews["NewChatMessageTextField"].typeText(txt) // send button should appeared XCTAssertTrue(app.buttons["Send"].exists) XCTAssertFalse(app.buttons["microphone"].exists) app.buttons["Send"].tap() // send button should be hidden XCTAssertFalse(app.buttons["Send"].exists) XCTAssertTrue(app.buttons["microphone"].exists) } func test_0007_AddContact() throws { let app = XCUIApplication() app.launch() app.navigationBars["Chats"].buttons["Add"].tap() let tablesQuery = app.tables tablesQuery.staticTexts["Add a New Contact"].tap() tablesQuery.textFields["Contact Jid"].tap() tablesQuery.textFields["Contact Jid"].typeText("[email protected]") tablesQuery.staticTexts["Add Contact"].tap() app.alerts["Permission Requested"].scrollViews.otherElements.buttons["Close"].tap() // wait for segue to chatView sleep(2) XCTAssertFalse(app.buttons["Send"].exists) app.textViews["NewChatMessageTextField"].tap() sendMsg(txt: "ping") sendMsg(txt: randomString(length: 100)) sendMsg(txt: randomString(length: 1000)) sendMsg(txt: randomString(length: 2000)) } }
35.317073
182
0.639917
ff8816c2f9f93f1613334b15734250e66d834fe6
1,578
// // Copyright © 2021 DHSC. All rights reserved. // import Interface import Scenarios import XCTest class HubButtonCellComponentTests: XCTestCase { @Propped private var runner: ApplicationRunner<HubButtonCellComponentScenario> func testBasics() throws { try runner.run { app in XCTAssert(app.firstHubButtonCell.exists) XCTAssert(app.secondHubButtonCell.exists) } } func testFirstHubButtonCellTapped() throws { try runner.run { app in app.firstHubButtonCell.tap() XCTAssert(app.firstHubButtoCellAlert.exists) } } func testSecondHubButtonCellTapped() throws { try runner.run { app in app.secondHubButtonCell.tap() XCTAssert(app.secondHubButtoCellAlert.exists) } } } private extension XCUIApplication { var firstHubButtonCell: XCUIElement { buttons[HubButtonCellComponentScenario.firstHubButtonCellTitle + ", " + HubButtonCellComponentScenario.firstHubButtonCellDescription] } var firstHubButtoCellAlert: XCUIElement { staticTexts[HubButtonCellComponentScenario.Alerts.firstHubButtoCellAlert.rawValue] } var secondHubButtonCell: XCUIElement { links[HubButtonCellComponentScenario.secondHubButtonCellTitle + ", " + HubButtonCellComponentScenario.secondHubButtonCellDescription] } var secondHubButtoCellAlert: XCUIElement { staticTexts[HubButtonCellComponentScenario.Alerts.secondHubButtonCellAlert.rawValue] } }
28.178571
141
0.698352
21c1bfad91b80d4b873c52daa1f2546c94e5654f
4,083
// // Dog.swift // PupVaccines // // Created by Cliff Anderson on 10/19/17. // Copyright © 2017 ArenaK9. All rights reserved. // import UIKit import os.log class Dog: NSObject, NSCoding { //MARK: Properties var name: String var dob: Date? var sex: String? var photo: UIImage? //DICTIONARIES unordered pair of key, value pairs of vaccines var vaccineDates: [String: Array<Date>?]? = [:] //MARK: Types struct PropertyKey { static let name = "name" static let dob = "dob" static let sex = "sex" static let photo = "photo" static let vaccineDates = "vaccineDates" } //MARK: Initialization init?(name: String, dob: Date?, sex: String?, photo: UIImage?, vaccineDates: Dictionary<String, Array<Date>?>?) { //let formatter = DateFormatter() //formatter.dateFormat = "yyyy/MM/dd" //let day1 = formatter.date(from: "2016/10/08") //let day2 = formatter.date(from: "2017/11/09") //let day3 = formatter.date(from: "2018/12/010") //let vDates = ["Rabies": day1!, "HeartGuard": day2!, "Flea & Tick": day3!] //The name must not be empty guard !name.isEmpty else { return nil } guard (sex == "Male") || (sex == "Female") || (sex == nil) else{ return nil } // Initialize stored properties. self.name = name self.dob = dob self.sex = sex self.photo = photo self.vaccineDates = vaccineDates //self.vaccineDates = ["": [day1!]] //print("DEBUG (Init) When creating a new dog the vaccine dictionary is: ") //print(self.vaccineDates) } convenience init?(name: String, dob: Date?, sex: String?, photo: UIImage?){ let vDates: [String: Array<Date>?] = [:] //print("DEBUG (Convenience) When creating a new dog the vaccine dictionary is: ") //print(vDates) self.init(name: name, dob: dob, sex: sex, photo: photo, vaccineDates: vDates) //os_log("These dogs were initialized with a Vaccine Dictionary.", log: OSLog.default, type: .debug) } //MARK: Archiving Paths static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first! static let ArchiveURL = DocumentsDirectory.appendingPathComponent("dogs") //MARK: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.name) aCoder.encode(dob, forKey: PropertyKey.dob) aCoder.encode(sex, forKey: PropertyKey.sex) aCoder.encode(photo, forKey: PropertyKey.photo) aCoder.encode(vaccineDates, forKey: PropertyKey.vaccineDates) //os_log("Encoding the Vaccine Dictionary was successful.", log: OSLog.default, type: .debug) } required convenience init?(coder aDecoder: NSCoder) { // The name is required. If we cannot decode a name string, the initializer should fail. guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else { //os_log("Unable to decode the name for a Dog object.", log: OSLog.default, type: .debug) return nil } // Because photo, dob and sex are optional properties of Dog, use conditional cast. let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage let dob = aDecoder.decodeObject(forKey: PropertyKey.dob) as? Date let sex = aDecoder.decodeObject(forKey: PropertyKey.sex) as? String let vaccineDates = aDecoder.decodeObject(forKey: PropertyKey.vaccineDates) as? Dictionary<String, Array<Date>> //os_log("Decoding the Vaccine Dictionary was successful.>", log: OSLog.default, type: .debug) //print(vaccineDates) // Must call designated initializer. self.init(name: name, dob: dob, sex: sex, photo: photo, vaccineDates: vaccineDates) } }
35.198276
118
0.607886
5b8f9aa4a6b6f441fe0361e3f880c755809d68e1
3,070
// // BackgroundParallax.swift // Time Fighter // // Created by Paulo Henrique Favero Pereira on 7/1/17. // Copyright © 2017 Fera. All rights reserved. // import UIKit import SpriteKit public class BackgroundParallax: SKNode { var currentSprite: SKSpriteNode var nextSprite: SKSpriteNode public init(spriteName: String) { self.currentSprite = SKSpriteNode(imageNamed: spriteName) self.nextSprite = self.currentSprite.copy() as! SKSpriteNode super.init() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// - speed: Speed of left moviment public func moveSprite(withSpeed speed: Float, deltaTime: TimeInterval, scene: SKScene) -> Void { var newPosition = CGPoint.zero //FIX ME: Passar a camera como parametro let camera = scene.childNode(withName: "mainCamera") // For both the sprite and its duplicate: for spriteToMove in [currentSprite, nextSprite] { // Shift the sprite leftward based on the speed newPosition = spriteToMove.position newPosition.x -= CGFloat(speed * Float(deltaTime)) spriteToMove.position = newPosition // If this sprite is now offscreen (i.e., its rightmost edge is // farther left than the scene's leftmost edge): if spriteToMove.frame.maxX < camera!.frame.minX + scene.frame.minX { // Shift it over so that it's now to the immediate right // of the other sprite. // This means that the two sprites are effectively // leap-frogging each other as they both move. spriteToMove.position = CGPoint(x: spriteToMove.position.x + spriteToMove.size.width * 2, y: spriteToMove.position.y) } } } /// Set the configuration for spriteNode and add it on Scene Background /// /// - Parameters: /// - sprite: Sprite to configurate /// - zpostion: Position on z axes on the scene /// - anchorPoint: anchor point of sprite /// - screenPosition: Desired postion to set on screen /// - spriteSize: Sprite size value public func createBackgroundNode(zpostion: CGFloat, anchorPoint: CGPoint, screenPosition:CGPoint, spriteSize: CGSize, scene:SKScene) { //set z position of sprite currentSprite.zPosition = zpostion //Set the anchor point currentSprite.anchorPoint = anchorPoint //Set the sprite position currentSprite.position = screenPosition currentSprite.size = spriteSize scene.addChild(currentSprite) nextSprite = (currentSprite.copy() as? SKSpriteNode)! nextSprite.position = CGPoint(x: screenPosition.x + (currentSprite.size.width), y: screenPosition.y) scene.addChild(nextSprite) } }
33.736264
139
0.614007
8936952573666500cc6df13d5cf2b00f1ca5c536
674
// // ProductVC.swift // ShopApp // // Created by Hesham Salama on 3/4/19. // Copyright © 2019 hesham. All rights reserved. // import UIKit class ProductVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
21.741935
106
0.652819
23ff2a98891b156b7be069fd8a90791a70b165bd
2,193
/** * Copyright IBM Corporation 2017 * * 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 SwiftMetrics import Foundation import Dispatch let sm = try SwiftMetrics() let monitoring = sm.monitor() public class AlarmClock { private let alarmTime: Date private var snoozeInterval : Int private var endAlarm = false private struct SnoozeData: SMData { let cycleCount: Int } private func snoozeMessage(data: SnoozeData) { print("\nAlarm has been ignored for \(data.cycleCount * snoozeInterval) seconds!\n") } public init(time: Date, snooze: Int) { self.snoozeInterval = snooze self.alarmTime = time monitoring.on(snoozeMessage) } public convenience init(time: Date) { self.init(time: time, snooze: 5) } public func stop() { print("Stopping alarm") endAlarm=true } public func waitForAlarm() { print("Waiting for alarm to go off....") var timeNow = Date() while timeNow.compare(alarmTime) == ComparisonResult.orderedAscending { sleep(1) timeNow = Date() } soundTheAlarm() snooze() } private func soundTheAlarm() { print("\nALARM! ALARM! ALARM! ALARM!\n") print("Press Enter to stop the alarm") } private func snooze() { var i = 1 while !endAlarm { sleep(UInt32(snoozeInterval)) sm.emitData(SnoozeData(cycleCount: i)) i += 1 } print("Alarm stopped - have a nice day!") } } let myAC = AlarmClock(time: Date(timeIntervalSinceNow: 5)) DispatchQueue.global(qos: .background).async { myAC.waitForAlarm() } let response = readLine(strippingNewline: true) myAC.stop()
25.206897
90
0.670315
fb0b844feae2512aed56aa41dbb7d0d9627e6bd7
1,166
// // NewsViewController.swift // SpaceDash // // Created by akhigbe benjamin on 15/12/2020. // Copyright © 2020 Pushpinder Pal Singh. All rights reserved. // import UIKit class NewsViewController: UIViewController{ @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.register(FeedCell.self) if let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { collectionViewLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize } } } extension NewsViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 3 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: FeedCell = collectionView.dequeueReusableCell(for: indexPath) return cell } }
25.347826
121
0.700686
7a4900b64f3f53b459cc6e4fe0c6b8babcaed656
4,660
// // UIAlertControllerExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/23/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit #if canImport(AudioToolbox) import AudioToolbox #endif // MARK: - Methods public extension UIAlertController { /// SwifterSwift: Present alert view controller in the current view controller. /// /// - Parameters: /// - animated: set true to animate presentation of alert controller (default is true). /// - vibrate: set true to vibrate the device while presenting the alert (default is false). /// - completion: an optional completion handler to be called after presenting alert controller (default is nil). func show(animated: Bool = true, vibrate: Bool = false, completion: (() -> Void)? = nil) { #if targetEnvironment(macCatalyst) let window = UIApplication.shared.windows.last #else let window = UIApplication.shared.keyWindow #endif window?.rootViewController?.present(self, animated: animated, completion: completion) if vibrate { #if canImport(AudioToolbox) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate) #endif } } /// SwifterSwift: Add an action to Alert /// /// - Parameters: /// - title: action title /// - style: action style (default is UIAlertActionStyle.default) /// - isEnabled: isEnabled status for action (default is true) /// - handler: optional action handler to be called when button is tapped (default is nil) /// - Returns: action created by this method @discardableResult func addAction(title: String, style: UIAlertAction.Style = .default, isEnabled: Bool = true, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction { let action = UIAlertAction(title: title, style: style, handler: handler) action.isEnabled = isEnabled addAction(action) return action } /// SwifterSwift: Add a text field to Alert /// /// - Parameters: /// - text: text field text (default is nil) /// - placeholder: text field placeholder text (default is nil) /// - editingChangedTarget: an optional target for text field's editingChanged /// - editingChangedSelector: an optional selector for text field's editingChanged func addTextField(text: String? = nil, placeholder: String? = nil, editingChangedTarget: Any?, editingChangedSelector: Selector?) { addTextField { textField in textField.text = text textField.placeholder = placeholder if let target = editingChangedTarget, let selector = editingChangedSelector { textField.addTarget(target, action: selector, for: .editingChanged) } } } } // MARK: - Initializers public extension UIAlertController { /// SwifterSwift: Create new alert view controller with default OK action. /// /// - Parameters: /// - title: alert controller's title. /// - message: alert controller's message (default is nil). /// - defaultActionButtonTitle: default action button title (default is "OK") /// - tintColor: alert controller's tint color (default is nil) convenience init(title: String, message: String? = nil, defaultActionButtonTitle: String = "OK", tintColor: UIColor? = nil) { self.init(title: title, message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil) addAction(defaultAction) if let color = tintColor { view.tintColor = color } } /// SwifterSwift: Create new error alert view controller from Error with default OK action. /// /// - Parameters: /// - title: alert controller's title (default is "Error"). /// - error: error to set alert controller's message to it's localizedDescription. /// - defaultActionButtonTitle: default action button title (default is "OK") /// - tintColor: alert controller's tint color (default is nil) convenience init(title: String = "Error", error: Error, defaultActionButtonTitle: String = "OK", preferredStyle: UIAlertController.Style = .alert, tintColor: UIColor? = nil) { self.init(title: title, message: error.localizedDescription, preferredStyle: preferredStyle) let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil) addAction(defaultAction) if let color = tintColor { view.tintColor = color } } } #endif
41.607143
179
0.663734
d5e114ec09c48cc2238a8a0e28648755d8837b0a
2,208
// // IpfsStorage.swift // DMASDK // // Created by Zhangxz& on 2019/3/25. // Copyright © 2019 Zhangxz&. All rights reserved. // import UIKit import SwiftIpfsApi import SwiftBase58 import SwiftMultihash public class IpfsStorage: NSObject { var url:String! var port:String! func add(filePath:String) -> String { do { let api = try IpfsApi(host: url, port: Int(port)!) var b58string:String? let group = DispatchGroup() group.enter() try api.add(filePath) { (m) in b58string = b58String((m.first?.hash!)!) group.leave() } group.wait() return b58string ?? "" } catch { return error.localizedDescription } } func add(fileData:Data) -> String { do { let api = try IpfsApi(host: url, port: Int(port)!) let group = DispatchGroup() var b58string:String? group.enter() try api.add(fileData) { (m) in b58string = b58String((m.first?.hash!)!) group.leave() } group.wait() return b58string ?? "" } catch { return error.localizedDescription } } func getBytes(hash:String) -> Array<UInt8> { let api = try!IpfsApi(host: url, port: Int(port)!) var uint8:Array<UInt8> = Array() let group = DispatchGroup() if let multihash = try?fromB58String(hash){ group.enter() try! api.get(multihash) { (result) in uint8 = result group.leave() } group.wait() } return uint8 } func getString(hash:String) -> String{ let api = try!IpfsApi(host: url, port: Int(port)!) let multihash = try!fromB58String(hash) let group = DispatchGroup() group.enter() var uint8:Array<UInt8>? try! api.get(multihash) { (result) in uint8 = result group.leave() } group.wait() return String.init(bytes: uint8!, encoding: .utf8)! } }
26.926829
62
0.508152
4a1e7396dccbb41d91a66025ac0519f920991093
1,608
// // SourceRequest.swift // News // // Created by Abhishek Kumar on 25/02/22. // import Foundation enum SourceRequest: URLRequestConvertible { case getNewsSource(code: String, pageNo: Int) func asURLRequest() throws -> URLRequest { var method: HTTPMethod { switch self { case .getNewsSource: return .get } } var params: Parameters { switch self { case .getNewsSource(let code, let page): return [NetworkConstants.countryKey: code, NetworkConstants.page: page] } } var httpHeader: HTTPHeaders { switch self { case .getNewsSource: return [NetworkConstants.auth: NetworkConstants.apiKey, NetworkConstants.requestHeaderContentTypeKey : NetworkConstants.requestHeaderContentTypeValue] } } var url: URL { let url = URL(string: NetworkConstants.baseurl)! switch self { case .getNewsSource: return url.appendingPathComponent(NetworkConstants.sourcePath) } } var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0) urlRequest.httpMethod = method.rawValue urlRequest.allHTTPHeaderFields = httpHeader try Utility.encode(urlRequest: &urlRequest, with: params) return urlRequest } }
29.777778
118
0.557836
db4468af959a3bb05b9ba9811137a954d228e0fd
3,543
// // ViewController.swift // HexCalc // // Created by Mattia Righetti on 02/05/2019. // Copyright © 2019 Mattia Righetti. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var valueOneTextField: UITextField! @IBOutlet var valueTwoTextField: UITextField! @IBOutlet var operationLabel: UILabel! @IBOutlet var calcButton: UIButton! @IBOutlet var resultLabel: UILabel! let operations = ["+", "-", "*", "%"] var opIndex = 0; override func viewDidLoad() { super.viewDidLoad() setupButtonView() setupOperationLabel() setupDismissKeyboardWhenTappedAround() } @IBAction func calcResult(_ sender: Any) { if let firstValueAsString = valueOneTextField.text, let secondValueAsString = valueTwoTextField.text { if !(firstValueAsString.isEmpty || secondValueAsString.isEmpty) { if let firstValue = UInt64(firstValueAsString, radix: 16), let secondValue = UInt64(secondValueAsString, radix: 16) { let result: UInt64 if (opIndex == 0) { result = firstValue + secondValue } else if (opIndex == 1) { result = firstValue - secondValue } else if (opIndex == 2) { result = firstValue * secondValue } else if (opIndex == 3) { result = firstValue / secondValue } else { result = 0 } resultLabel.text = "0x" + String(format: "%X", result) } else { launchAllert(withTitle: "Out Of Scope Values", "Values are not hexadecimal numbers") } } else { launchAllert(withTitle: "Value Missing", "Please fill in all the values") } } } } extension ViewController { func setupButtonView() { calcButton.layer.cornerRadius = 10 } func launchAllert(withTitle title: String, _ message: String) { let alertMissingValues = UIAlertController(title: title, message: message, preferredStyle: .alert) alertMissingValues.addAction(UIAlertAction(title: "Ok", style: .default)) present(alertMissingValues, animated: true, completion: nil) } func setupOperationLabel() { operationLabel.text = operations[opIndex] let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.updateOperation)) tapGestureRecognizer.cancelsTouchesInView = false operationLabel.addGestureRecognizer(tapGestureRecognizer) operationLabel.isUserInteractionEnabled = true } func setupDismissKeyboardWhenTappedAround() { let tapAround = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tapAround.cancelsTouchesInView = false view.addGestureRecognizer(tapAround) view.isUserInteractionEnabled = true } @objc func updateOperation() { opIndex = (opIndex + 1) % 4 operationLabel.text = operations[opIndex] } @objc func dismissKeyboard() { view.endEditing(true) } }
33.424528
122
0.56534
3afc248cf8652b71286fdad8f1004ae1d2a65ef6
7,517
// // IssuerIntroductionRequestTests.swift // cert-wallet // // Created by Chris Downie on 9/2/16. // Copyright © 2016 Digital Certificates Project. All rights reserved. // import XCTest @testable import Blockcerts class IssuerIntroductionRequestTests: XCTestCase { func testSuccessfulIntroductionRequest() { let itShouldCallTheCallback = expectation(description: "The request's callback handler will be called.") let itShouldCallTheServer = expectation(description: "Mocking framework should call our fake server function.") let expectedAddress = BlockchainAddress(string: "FakeRecipientPublicKey") let expectedEmail = "[email protected]" let expectedName = "Johnny Strong" let introductionURL = URL(string: "https://blockcerts.org/introduce/")! let issuer = IssuerV1(name: "BlockCerts Issuer", email: "[email protected]", image: "data:image/png;base64,".data(using: .utf8)!, id: URL(string: "https://blockcerts.org/issuer.json")!, url: URL(string: "https://blockcerts.org")!, publicIssuerKeys: [ KeyRotation(on: Date(timeIntervalSince1970: 0), key: BlockchainAddress(string: "FAKE_ISSUER_KEY")) ], publicRevocationKeys: [ KeyRotation(on: Date(timeIntervalSince1970: 0), key: BlockchainAddress(string: "FAKE_REVOCATION_KEY")) ], introductionURL: introductionURL) let recipient = Recipient(name: expectedName, identity: expectedEmail, identityType: "email", isHashed: false, publicAddress: expectedAddress, revocationAddress: nil) // Mock out the network let session = MockURLSession() session.respond(to: introductionURL) { request in let body = request.httpBody XCTAssertNotNil(body, "Request to the issuer should have a body.") let json = try? JSONSerialization.jsonObject(with: body!, options: []) XCTAssertNotNil(json, "Body of the request should be parsable as json") let map = json as? [String: String] XCTAssertNotNil(map, "Currently, the json is always String:String type") XCTAssertEqual(map!["bitcoinAddress"], expectedAddress.value) XCTAssertEqual(map!["email"], expectedEmail) XCTAssertEqual(map!["name"], expectedName) itShouldCallTheServer.fulfill() return ( data: "Success".data(using: .utf8), response: HTTPURLResponse(url: introductionURL, statusCode: 200, httpVersion: nil, headerFields: nil), error: nil ) } // Create the request let request = IssuerIntroductionRequest(introduce: recipient, to: issuer, loggingTo: DefaultLogger(), session: session) { (possibleError) in XCTAssertNil(possibleError) itShouldCallTheCallback.fulfill() } request.start() waitForExpectations(timeout: 20.0, handler: nil) } func testSuccessfulIntroductionRequestWithExtraJSONData() { let itShouldCallTheCallback = expectation(description: "The request's callback handler will be called.") let itShouldCallTheServer = expectation(description: "Mocking framework should call our fake server function.") let expectedAddress = "FakeRecipientPublicKey" let expectedEmail = "[email protected]" let expectedFirstName = "Johnny" let expectedLastName = "Strong" let extraDataKey = "favoriteEmoji" let extraDataValue = "🐼" let introductionURL = URL(string: "https://blockcerts.org/introduce/")! let issuer = IssuerV1(name: "BlockCerts Issuer", email: "[email protected]", image: "data:image/png;base64,".data(using: .utf8)!, id: URL(string: "https://blockcerts.org/issuer.json")!, url: URL(string: "https://blockcerts.org")!, publicIssuerKeys: [ KeyRotation(on: Date(timeIntervalSince1970: 0), key: "FAKE_ISSUER_KEY") ], publicRevocationKeys: [ KeyRotation(on: Date(timeIntervalSince1970: 0), key: "FAKE_REVOCATION_KEY") ], introductionURL: introductionURL) let recipient = Recipient(givenName: expectedFirstName, familyName: expectedLastName, identity: expectedEmail, identityType: "email", isHashed: false, publicAddress: expectedAddress, revocationAddress: nil) class TestDelegate : IssuerIntroductionRequestDelegate { let extraDataKey = "favoriteEmoji" let extraDataValue = "🐼" public func introductionData(for issuer: Issuer, from recipient: Recipient) -> [String : Any] { var data = [String: Any]() data["email"] = recipient.identity data[extraDataKey] = extraDataValue return data } } // Mock out the network let session = MockURLSession() session.respond(to: introductionURL) { request in let body = request.httpBody XCTAssertNotNil(body, "Request to the issuer should have a body.") let json = try? JSONSerialization.jsonObject(with: body!, options: []) XCTAssertNotNil(json, "Body of the request should be parsable as json") let map = json as? [String: String] XCTAssertNotNil(map, "Currently, the json is always String:String type") XCTAssertEqual(map!["bitcoinAddress"], expectedAddress) XCTAssertEqual(map!["email"], expectedEmail) XCTAssertNil(map!["firstName"], expectedFirstName) XCTAssertNil(map!["lastName"], expectedLastName) XCTAssertNotNil(map![extraDataKey]) XCTAssertEqual(map![extraDataKey], extraDataValue) itShouldCallTheServer.fulfill() return ( data: "Success".data(using: .utf8), response: HTTPURLResponse(url: introductionURL, statusCode: 200, httpVersion: nil, headerFields: nil), error: nil ) } // Create the request let request = IssuerIntroductionRequest(introduce: recipient, to: issuer, loggingTo: DefaultLogger(), session: session) { (error) in XCTAssertNil(error) itShouldCallTheCallback.fulfill() } request.delegate = TestDelegate() request.start() waitForExpectations(timeout: 20.0, handler: nil) } }
46.98125
148
0.556871
db4a034e8a1836cef37e0c57fb01b3f97a4080a7
946
// // RootProtocols.swift // SBBOL // // Created by MAXIM DOROSHENKO on 04.11.2020. // import UIKit protocol RootModule: BaseTabBarDelegate { // Module protocol. } protocol RootDelegate: class { // Delegate protocol. } protocol RootViewToPresenter: class { // View calls, Presenter listens. } protocol RootPresenterToView: class, AbleToShowError, AbleToShowActivityIndicator { // Presenter calls, View listens. Presenter receives a reference from this protocol to access View. View conforms to the protocol. } protocol RootPresenterToRouter: class { // Presenter calls, Router listens. func navigate(to destination: RootNavigation, completion: RootRouterClosure?) } protocol RootControllerToRouter: class { func present(viewController: UIViewController) } protocol RootPresenterToInteractor: class { // Presenter calls, Interactor listens. func fetchLanguages(completion: @escaping (Result<Void, Error>) -> Void) }
26.277778
215
0.763214
d9d8c71a3920c2e68f05a141e94c08ec930caf82
106
public struct OttoComms { public private(set) var text = "Hello, World!" public init() { } }
15.142857
50
0.603774
796c8246d915e03d856539850bddae248c96611d
15,520
// // SideMenuVC.swift // PatricksStore // // Created by Admin on 03/09/21. // import UIKit class SideMenuVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.initialSetup() } //MARK: - Initial Setup func initialSetup() { // Set status bar color Helper.StatusBarColor(view: self.view) } //MARK: - Button Actions // Close Button Action @IBAction func closeButtonTapped(_ sender: UIButton) { dismiss(animated: true, completion: nil) } } //MARK: - Side Menu Table View Logic extension SideMenuVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 23 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // SideMenuCategoryTableViewCell if indexPath.row == 0 || indexPath.row == 8 { return 60.0 // SideMenuSeparatorTableViewCell } else if indexPath.row == 7 || indexPath.row == 22 { return 20.0 // SideMenuCategoryItemTableViewCell } else { return 40.0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // SideMenuCategoryTableViewCell if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryTableViewCell") as! SideMenuCategoryTableViewCell cell.selectionStyle = .none cell.lblCategoryName.text = "Services" return cell // SideMenuCategoryItemTableViewCell } else if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 3 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 4 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 5 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 6 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuViewAllCategoryTableViewCell") as! SideMenuViewAllCategoryTableViewCell cell.selectionStyle = .none return cell // SideMenuSeparatorTableViewCell } else if indexPath.row == 7 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuSeparatorTableViewCell") as! SideMenuSeparatorTableViewCell cell.selectionStyle = .none return cell // SideMenuCategoryTableViewCell } else if indexPath.row == 8 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryTableViewCell") as! SideMenuCategoryTableViewCell cell.selectionStyle = .none cell.lblCategoryName.text = "Products" return cell // SideMenuCategoryItemTableViewCell } else if indexPath.row == 9 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Food & Beverages" return cell } else if indexPath.row == 10 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Mobile & Laptop" return cell } else if indexPath.row == 11 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Bags and Shoes" return cell } else if indexPath.row == 12 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Electronics" return cell } else if indexPath.row == 13 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Fashion Accessories" return cell } else if indexPath.row == 14 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Grocery" return cell } else if indexPath.row == 15 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Health and Beauty" return cell } else if indexPath.row == 16 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Home Appliances" return cell } else if indexPath.row == 17 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Kids Clothing" return cell } else if indexPath.row == 18 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Books & Stationary" return cell } else if indexPath.row == 19 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Mens Clothing" return cell } else if indexPath.row == 20 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCategoryItemTableViewCell") as! SideMenuCategoryItemTableViewCell cell.selectionStyle = .none cell.lblCategoryItem.text = "Womens Clothing" return cell } else if indexPath.row == 21 { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuViewAllCategoryTableViewCell") as! SideMenuViewAllCategoryTableViewCell cell.selectionStyle = .none return cell // SideMenuSeparatorTableViewCell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuSeparatorTableViewCell") as! SideMenuSeparatorTableViewCell cell.selectionStyle = .none return cell } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let route = indexPath.item switch route { case 0: break case 1: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 0 self.navigationController?.pushViewController(vc, animated: true) case 2: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 0 self.navigationController?.pushViewController(vc, animated: true) case 3: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 0 self.navigationController?.pushViewController(vc, animated: true) case 4: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 0 self.navigationController?.pushViewController(vc, animated: true) case 5: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 0 self.navigationController?.pushViewController(vc, animated: true) case 6: let strybd = UIStoryboard(name: "Shops", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "ShopsVC") as! ShopsVC vc.passedClvIndexValue = 2 self.navigationController?.pushViewController(vc, animated: true) case 7: break case 8: break case 9: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 0 self.navigationController?.pushViewController(vc, animated: true) case 10: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 1 self.navigationController?.pushViewController(vc, animated: true) case 11: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 2 self.navigationController?.pushViewController(vc, animated: true) case 12: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 3 self.navigationController?.pushViewController(vc, animated: true) case 13: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 4 self.navigationController?.pushViewController(vc, animated: true) case 14: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 5 self.navigationController?.pushViewController(vc, animated: true) case 15: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 6 self.navigationController?.pushViewController(vc, animated: true) case 16: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 7 self.navigationController?.pushViewController(vc, animated: true) case 17: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 8 self.navigationController?.pushViewController(vc, animated: true) case 18: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 9 self.navigationController?.pushViewController(vc, animated: true) case 19: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 10 self.navigationController?.pushViewController(vc, animated: true) case 20: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC vc.indexSelected = 11 self.navigationController?.pushViewController(vc, animated: true) case 21: let strybd = UIStoryboard(name: "HomeCategories", bundle: nil) let vc = strybd.instantiateViewController(withIdentifier: "AllCategoriesVC") as! AllCategoriesVC self.navigationController?.pushViewController(vc, animated: true) default: break } } }
46.746988
149
0.611469
4617636b3d848b70eeb09354157e41c931123739
5,693
// // Atom.swift // Atom Attack // // Created by Veljko Tekelerovic on 7.10.19. // Copyright © 2019 Vladislav Jevremovic. All rights reserved. // import SpriteKit /// Class encapsulating Atom entity class Atom { private let atomShape: SKShapeNode private var atomColor: ColorTheme private var inMotion: Bool = false private let actionName = "attackingAction" private var attackingSpeed: TimeInterval = 5.0 //TODO: experiment w/ this value public var motionSpeed: TimeInterval { willSet { assert(newValue > 0) attackingSpeed = newValue } } /// Creates new `Atom` with given base color theme required init(color: ColorTheme = .white) { //variable initialization atomColor = color motionSpeed = attackingSpeed //easier to experiment atomShape = SKShapeNode(circleOfRadius: 10) atomShape.name = "Atom" if atomColor == .black { atomShape.fillColor = SKColor.black atomShape.strokeColor = SKColor.black } else { atomShape.fillColor = SKColor.white atomShape.strokeColor = SKColor.white } atomShape.lineWidth = 0.1 atomShape.position = CGPoint(x: 0, y: 0) atomShape.physicsBody = SKPhysicsBody(circleOfRadius: 10) atomShape.physicsBody?.isDynamic = true atomShape.physicsBody?.categoryBitMask = PhysicsBitmask.RayBitmask atomShape.physicsBody?.contactTestBitMask = PhysicsBitmask.CoreBitmask } /// Creates new `Atom` with default (white) base color theme convenience init() { self.init(color: .white) } /// Returns `true` if the atom is in motion (attacking), `false` otherwise public var isAttacking: Bool { return inMotion } } // MARK: - Public methods extension Atom { /** Places the atom on the given `SKScene`. Positioning is fixed on Y axis, while randomized on X axis. Top-most part of the screen is taken as base Y. If the passed scene object isn't valid or had expired in the meantime, the function will `fatalError()` immediatelly. - parameters: - scene: Valid `SKScene` object. */ func position(in scene: SKScene) { guard let sceneBounds = scene.view?.bounds else { fatalError("Unable to get scene bounds") } //adjust our X and Y and add us to root scene let screenWidth = sceneBounds.minX...sceneBounds.maxX let randomizedX = CGFloat.random(in: screenWidth) atomShape.position.x = randomizedX atomShape.position.y = sceneBounds.maxY scene.addChild(atomShape) } /// Starts moving the Atom to a given point func attack(point: CGPoint) { let attackAnimation = setupAttackAnimation(target: point) //update our flag inMotion = true atomShape.run(attackAnimation) { [weak self] in self?.inMotion = false } } /// Starts moving the Atom to a given point after specified delay func attack(point: CGPoint, after: TimeInterval) { let delay = SKAction.wait(forDuration: after) let attackAnimation = setupAttackAnimation(target: point) let deleyedAttackAnimation = SKAction.sequence([delay, attackAnimation]) atomShape.run(deleyedAttackAnimation) } /// Stops the Atom immediatelly. Atom remains on its last poistion where it has beed stopped. func stopAttacking() { atomShape.removeAllActions() } /// Removes the Atom from the scene. func removeFromScene() { atomShape.removeAllChildren() atomShape.removeAllActions() atomShape.removeFromParent() } } // MARK: - Animation methods & utilities extension Atom { private func setupAttackAnimation(target: CGPoint) -> SKAction { let attachRay = SKAction.run { self.attachRay() } let attackTarget = buildAttackAction(target: target) let removalAction = SKAction.run { self.removeFromScene() } let attackingSequence = SKAction.sequence([ attachRay, attackTarget, removalAction ]) return attackingSequence } /// Attaches atom ray to the current atom private func attachRay() { let rayNode = SKShapeNode(rect: CGRect(x: -10, y: 0, width: 20, height: 3_000)) let whiteFactor: CGFloat = atomColor == .black ? 0.2 : 1.0 rayNode.fillColor = SKColor(white: whiteFactor, alpha: 0.2) rayNode.strokeColor = SKColor.clear rayNode.lineWidth = 0.1 rayNode.zPosition = 1 //side effect of following the path motion is the rotation towards the target followed //as a result, we need to (re)rotate the ray by 180 degrees to make it look as desired (oriented outwards of the screen) let rotationAngle = SKAction.rotate(byAngle: .pi, duration: 0.01) rayNode.run(rotationAngle) atomShape.addChild(rayNode) } /// Creates `SKAction` that follows a path to a given target private func buildAttackAction(target: CGPoint) -> SKAction { let animationPath = CGMutablePath() //UIBezierPath insted ? animationPath.move(to: atomShape.position) animationPath.addLine(to: target) animationPath.closeSubpath() return SKAction.follow(animationPath, asOffset: false, orientToPath: true, duration: attackingSpeed) //orienting to path (orientToPath = true) during follow() causes the atom ray to be (mis)rotated directly towards the Core //as the side effect, actuall ray has to be rotated properly during creation (see lines 143+) } }
35.360248
130
0.656771
21911143a3993c91df92c9475f82990cdcc60c24
2,233
// // ViewController.swift // HapticSample // // Created by hanwe on 2020/12/10. // import UIKit class ViewController: UIViewController { var feedbackGenerator: UINotificationFeedbackGenerator? var impactFeedbackGenerator: UIImpactFeedbackGenerator? var selectionFeedbackHenerator: UISelectionFeedbackGenerator? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setGenerator() } private func setGenerator() { self.feedbackGenerator = UINotificationFeedbackGenerator() self.feedbackGenerator?.prepare() } @IBAction func action1(_ sender: Any) { self.feedbackGenerator?.notificationOccurred(.success) } @IBAction func action2(_ sender: Any) { self.feedbackGenerator?.notificationOccurred(.warning) } @IBAction func action3(_ sender: Any) { self.feedbackGenerator?.notificationOccurred(.error) } @IBAction func action4(_ sender: Any) { self.impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy) self.impactFeedbackGenerator?.impactOccurred() } @IBAction func action5(_ sender: Any) { self.impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light) self.impactFeedbackGenerator?.impactOccurred() } @IBAction func action6(_ sender: Any) { self.impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .medium) self.impactFeedbackGenerator?.impactOccurred() } @IBAction func action7(_ sender: Any) { self.impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .rigid) self.impactFeedbackGenerator?.impactOccurred() } @IBAction func action8(_ sender: Any) { self.impactFeedbackGenerator = UIImpactFeedbackGenerator(style: .soft) self.impactFeedbackGenerator?.impactOccurred() } @IBAction func action9(_ sender: Any) { self.impactFeedbackGenerator?.impactOccurred() } @IBAction func actionA(_ sender: Any) { self.selectionFeedbackHenerator = UISelectionFeedbackGenerator() self.selectionFeedbackHenerator?.selectionChanged() } }
30.589041
80
0.691894
f462e81bc12bbf274417a3a13bbea585404e4e1d
371
import Foundation public extension URLRequest { /// Sets a HTTP header. mutating func setHTTPHeader(_ header: HTTPHeader) { self.setValue(header.value, forHTTPHeaderField: header.name) } /// Sets a HTTP headers. mutating func setHTTPHeaders(_ headers: [HTTPHeader]) { headers.forEach { self.setHTTPHeader($0) } } }
23.1875
68
0.649596
397708eb36f83f946c651e40cc60f1531e33b568
205
// // Created by Jacob Morris on 3/19/18. // Copyright (c) 2018 Jacob Morris. All rights reserved. // import Foundation public enum Ligature: Int { case noLigature = 0 case defaultLigature = 1 }
17.083333
56
0.687805
26e07346693d43009473eb5ead39984ec1db7e56
3,677
/** * Copyright (c) 2017 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit @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 invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
51.788732
285
0.763938
e6ccccfcf76d160f0d73f5de5f4806760e1dc2fd
659
// // EmptyStateCellTests.swift // UnsplashTests // // Created by Ivan Rodrigues de Martino on 03/07/21. // import XCTest @testable import Unsplash class EmptyStateCellTests: BaseSnapshotTest { func testEmptyStateCell() { let sut = makeSUT() verifySnapshotView { sut } } private func makeSUT() -> EmptyStateCell { let size = CGSize(width: 414, height: 400) let frame = CGRect(origin: .zero, size: size) let view = EmptyStateCell(frame: frame) view.setUp(title: Localizable.emptyStateTitle.localize, description: Localizable.emptyStateDescription.localize) return view } }
25.346154
120
0.667678
ed819337d652aa2708a8e2b4a57abeeb8250167e
519
// // TileViewControllerDataSource.swift // Swift Reuse Code // // Created by Oliver Klemenz on 26.06.14. // // import Foundation import UIKit protocol TileViewControllerDataSource: class { func tileName() -> String? func tileShowNameInitials() -> Bool func tileImage() -> UIImage? func tilePositioned() -> Bool func setTilePositioned(_ tilePositioned: Bool) func tileRow() -> Int func setTileRow(_ tileRow: Int) func tileColumn() -> Int func setTileColumn(_ tileColumn: Int) }
22.565217
50
0.693642
118b7684967705c06a5b540889fe3c0799c75c1b
3,467
// // SupportAgentLogEntryCapabilityLegacy.swift // // Generated on 20/09/18 /* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import PromiseKit import RxSwift // MARK: Legacy Support public class SupportAgentLogEntryCapabilityLegacy: NSObject, ArcusSupportAgentLogEntryCapability, ArcusPromiseConverter { public var disposeBag: DisposeBag = DisposeBag() private static let capability: SupportAgentLogEntryCapabilityLegacy = SupportAgentLogEntryCapabilityLegacy() public static func getCreated(_ model: SupportAgentLogEntryModel) -> Date? { guard let created: Date = capability.getSupportAgentLogEntryCreated(model) else { return nil } return created } public static func getAgentId(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryAgentId(model) } public static func getAccountId(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryAccountId(model) } public static func getAction(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryAction(model) } public static func getParameters(_ model: SupportAgentLogEntryModel) -> [String]? { return capability.getSupportAgentLogEntryParameters(model) } public static func getUserId(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryUserId(model) } public static func getPlaceId(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryPlaceId(model) } public static func getDeviceId(_ model: SupportAgentLogEntryModel) -> String? { return capability.getSupportAgentLogEntryDeviceId(model) } public static func createAgentLogEntry(_ model: SupportAgentLogEntryModel, agentId: String, accountId: String, action: String, parameters: [String], userId: String, deviceId: String, placeId: String) -> PMKPromise { do { return try capability.promiseForObservable(capability .requestSupportAgentLogEntryCreateAgentLogEntry(model, agentId: agentId, accountId: accountId, action: action, parameters: parameters, userId: userId, deviceId: deviceId, placeId: placeId)) } catch { return PMKPromise.new { (_: PMKFulfiller?, rejecter: PMKRejecter?) in rejecter?(error) } } } public static func listAgentLogEntries(_ model: SupportAgentLogEntryModel, agentId: String, startDate: String, endDate: String) -> PMKPromise { do { return try capability.promiseForObservable(capability .requestSupportAgentLogEntryListAgentLogEntries(model, agentId: agentId, startDate: startDate, endDate: endDate)) } catch { return PMKPromise.new { (_: PMKFulfiller?, rejecter: PMKRejecter?) in rejecter?(error) } } } }
32.707547
218
0.736083
ed4b881c8b06f12d5d88df40d23bfa7d98962283
31,872
// // AHFMShowPageVC.swift // Pods // // Created by Andy Tong on 7/25/17. // // import UIKit import AHAudioPlayer import SVProgressHUD import AHDownloader import AHDownloadTool fileprivate let ScreenSize = UIScreen.main.bounds.size fileprivate let NavBarHeight: CGFloat = 64.0 fileprivate let ShowHeaderHeight: CGFloat = NavBarHeight + 150.0 + 40.0 fileprivate let ShowHeaderOriginY: CGFloat = 0.0 fileprivate let SectionViewHeight: CGFloat = 38.0 fileprivate let SectionOriginY: CGFloat = ShowHeaderOriginY + ShowHeaderHeight fileprivate let Y_Inset: CGFloat = SectionOriginY + SectionViewHeight @objc public protocol AHFMShowPageVCDelegate: class { /// Call localInitialShow(_ data: [String: Any]?) func showPageVCShouldLoadInitialShow(_ vc: UIViewController) /// Call loadEpisodes(_ data: [[String: Any]]?) func showPageVC(_ vc: UIViewController, shouldLoadEpisodesForShow showId: Int) /// Call shouldLoadRecommendedShows(_ data: [[String: Any]]?) func showPageVC(_ vc: UIViewController, shouldLoadRecommendedShowsForShow showId: Int) /// Did select show's episode func showPageVCDidSelectEpisode(_ vc: UIViewController, show showId: Int, currentEpisode episodeId: Int) /// Did select recommended show func showPageVCDidSelectRecommendedShow(_ vc: UIViewController, recommendedShow showId: Int) /// Call loadSubscribeOrUnSubcribeShow(_ data: [String:Any]?) /// data example: ["showId": Int, "isSubcribed": Bool] /// isSubcribed is the current state after this method is called. func showPageVC(_ vc: UIViewController, shouldSubscribeOrUnSubcribeShow showId: Int, shouldSubscribed: Bool) /// This method should lead to some other VC page func showPageVCDidTappDownloadBtnTapped(_ vc: UIViewController, forshow showId: Int) func showPageVCWillPresentIntroVC(_ showVC: UIViewController) func showPageVCWillDismissIntroVC(_ showVC: UIViewController) func viewWillAppear(_ vc: UIViewController) func viewWillDisappear(_ vc: UIViewController) } //MARK:- public final class AHFMShowPageVC: UIViewController { public var manager: AHFMShowPageVCDelegate? var show: Show? { didSet { if let show = show { showHeader.show = show titleLabel.text = show.title showHeader.isSubscribed = show.isSubscribed } } } var episodes: [Episode]? { didSet { if let episodes = episodes { showPageCellDataSource.episodes = episodes } } } fileprivate let titleLabel = UILabel() fileprivate weak var navBar: UINavigationBar! fileprivate weak var showHeader: AHFMShowHeader! fileprivate var recommendedShows: [Show]? { didSet{ if let recommendedShows = recommendedShows { showRecommendDataSource.shows = recommendedShows } } } /// For current shows' episodes fileprivate var currentTableView: UITableView! /// For recommended episodes fileprivate var recommendedTableView: UITableView! fileprivate weak var sectionView: AHSectionView! fileprivate var epSectionleft = UIButton(type: .custom) fileprivate var epSectionRight = UIButton(type: .custom) fileprivate let showPageCellDataSource = AHFMShowPageDataSource() fileprivate let showRecommendDataSource = AHFMShowRecomendDataSource() // when there's playing episode in this show fileprivate var playingMode = false fileprivate var playingModeOffsetY = Y_Inset // determine wether or not to call checkCurrentEpisode() fileprivate var shouldCheckCurrentEpisode = true } //MARK:- Loading Methods extension AHFMShowPageVC { /// Call localInitialShow(_ data: [String: Any]?) public func localInitialShow(_ data: [String: Any]?) { guard let data = data else { return } self.show = Show(data) manager?.showPageVC(self, shouldLoadEpisodesForShow: self.show!.id) } public func loadEpisodes(_ data: [[String: Any]]?) { guard let data = data else { return } var eps = [Episode]() for epDict in data { let ep = Episode(epDict) eps.append(ep) } self.episodes = eps self.currentTableView.reloadData() SVProgressHUD.dismiss() } /// Call loadSubscribeOrUnSubcribeShow(_ data: [String:Any]?) /// data example: ["showId": Int, "isSubcribed": Bool] /// isSubcribed is the current state after this method is called. public func loadSubscribeOrUnSubcribeShow(_ data: [String:Any]?) { SVProgressHUD.dismiss() guard let data = data, let showId = data["showId"] as? Int, let isSubcribed = data["isSubcribed"] as? Bool, let show = self.show, show.id == showId else { showHeader.isSubscribed = false return } showHeader.isSubscribed = isSubcribed } /// Call shouldLoadRecommendedShows(_ data: [[String: Any]]?) public func shouldLoadRecommendedShows(_ data: [[String: Any]]?) { guard let data = data else { return } var shows = [Show]() for showDict in data { let show = Show(showDict) shows.append(show) } self.recommendedShows = shows SVProgressHUD.dismiss() } } //MARK:- VC Life Cycle extension AHFMShowPageVC { override public func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false setup() sectionView.select(index: 0, sendEvent: true) AHDownloader.addDelegate(self) } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // by default, hide navbar navBar.setBackgroundImage(UIImage(), for: .default) navBar.shadowImage = UIImage() navBar.barStyle = .black manager?.viewWillAppear(self) if self.presentedViewController != nil { // there's a vc presented by this vc // it could be a episodelistVC from bottomPlayer, or a introVC from this VC. }else{ SVProgressHUD.show() manager?.showPageVCShouldLoadInitialShow(self) } } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if shouldCheckCurrentEpisode { checkCurrentEpisode() }else{ shouldCheckCurrentEpisode = true } } public override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if self.presentedViewController != nil { // there's a vc presented by this vc // it could be a episodelistVC from bottomPlayer, or a introVC from this VC. shouldCheckCurrentEpisode = false }else{ navBar.setBackgroundImage(nil, for: .default) navBar.shadowImage = nil navBar.barStyle = .default } manager?.viewWillDisappear(self) } public override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle.lightContent } } //MARK:- AHDownloaderDelegate extension AHFMShowPageVC: AHDownloaderDelegate { public func downloaderDidStartDownload(url:String){ updateDownloadState(forUrl: url) } public func downloaderDidFinishDownload(url:String, localFilePath: String){ updateDownloadState(forUrl: url) } public func downloaderDidPaused(url: String){ updateDownloadState(forUrl: url) } public func downloaderDidPausedAll(){ guard let eps = self.episodes else { return } for ep in eps { updateDownloadState(forUrl: ep.remoteURL ?? "") } } public func downloaderDidResumedAll(){ guard let eps = self.episodes else { return } for ep in eps { updateDownloadState(forUrl: ep.remoteURL ?? "") } } public func downloaderDidResume(url:String){ updateDownloadState(forUrl: url) } public func downloaderCancelAll(){ guard let eps = self.episodes else { return } for ep in eps { updateDownloadState(forUrl: ep.remoteURL ?? "") } } public func downloaderDidCancel(url:String){ updateDownloadState(forUrl: url) } } //MARK:- TableView Delegate extension AHFMShowPageVC: UITableViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { guard navBar != nil else { return } if scrollView === currentTableView { handleEpisodeShowHeader(scrollView) handleEpisodeSectionView(scrollView) }else{ handleRecommendShowHeader(scrollView) handleRecommendSectionView(scrollView) } } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if playingMode { if scrollView.contentOffset.y < playingModeOffsetY { playingModeOffsetY = scrollView.contentOffset.y } } } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let cell = cell as? AHFMShowPageCell else { return } guard let eps = self.episodes else { return } let ep = eps[indexPath.row] let state = ep.downloadState switch state { case .notStarted: cell.normal() case .pausing: cell.pause() case .downloading: cell.downloading() case .succeeded: cell.downloaded() case .failed: cell.normal() } } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView === self.currentTableView, let cell = tableView.cellForRow(at: indexPath) as? AHFMShowPageCell { guard let show = self.show else { return } if let ep = cell.episode { manager?.showPageVCDidSelectEpisode(self, show: show.id, currentEpisode: ep.id) } }else if tableView === self.recommendedTableView, let cell = tableView.cellForRow(at: indexPath) as? AHFMShowRecommendCell{ guard let show = cell.show else { print("cell.show is nil ????") return } manager?.showPageVCDidSelectRecommendedShow(self, recommendedShow: show.id) } } } //MARK:- Control Events extension AHFMShowPageVC { /// Adjust tableviews when switching. private func adjustment(_ tableView: UITableView) { tableView.contentInset.top = sectionView.frame.maxY tableView.contentOffset.y = -sectionView.frame.maxY self.view.insertSubview(tableView, belowSubview: showHeader) tableView.contentInset.top = Y_Inset } @objc func sectionBtnsTapped(_ button: UIButton) { if button == epSectionleft { // epBtn left recommendedTableView.removeFromSuperview() adjustment(currentTableView) }else{ // epBtn right playingMode = false currentTableView.removeFromSuperview() adjustment(recommendedTableView) // check if there's data, // if recommendedShows.count > 0 means the related shows are already being retrived. if let recommendedShows = self.recommendedShows, recommendedShows.count > 0{ recommendedTableView.reloadData() }else{ // Retrive related eps based current playing episode if any // or pick the first ep of the show for it. guard let show = show else { return } SVProgressHUD.show() manager?.showPageVC(self, shouldLoadRecommendedShowsForShow: show.id) } } } @objc func backBtnTapped(_ sender: UIBarButtonItem) { if self.navigationController == nil { self.dismiss(animated: true, completion: nil) }else{ self.navigationController?.popViewController(animated: true) } } } //MARK:- Recommend TableView Scrolling extension AHFMShowPageVC { func handleRecommendShowHeader(_ scrollView: UIScrollView) { let toolView = showHeader.toolBar if scrollView.contentOffset.y >= -Y_Inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = (Y_Inset + scrollView.contentOffset.y) showHeader.frame.origin.y = ShowHeaderOriginY - delta let toolDelta = showHeader.frame.maxY - navBar.frame.maxY let toolTotal = ShowHeaderOriginY + ShowHeaderHeight //###### var alpha = toolDelta / toolTotal // A quick fix for toolView?.alpha remaining at 0.748, but reaching 1. var fixMe: Any? if alpha > 0.74 { alpha = 1.0 } toolView?.alpha = alpha //###### if showHeader.frame.maxY <= NavBarHeight { showHeader.frame.origin.y = -ShowHeaderHeight + NavBarHeight } }else{ toolView?.alpha = 1.0 // Scrolling too far, stick to its originY showHeader.frame.origin.y = ShowHeaderOriginY } } func handleRecommendSectionView(_ scrollView: UIScrollView) { if scrollView.contentOffset.y >= -Y_Inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = (Y_Inset + scrollView.contentOffset.y) sectionView.frame.origin.y = SectionOriginY - delta if sectionView.frame.origin.y <= NavBarHeight { // sticking at 64.0 sectionView.frame.origin.y = NavBarHeight } }else{ // Scrolling too far, stick to its originY sectionView.frame.origin.y = SectionOriginY } } } //MARK:- Episode TableView Scrolling extension AHFMShowPageVC { func handleEpisodeShowHeader(_ scrollView: UIScrollView) { let toolView = showHeader.toolBar var y_inset = Y_Inset if playingMode && scrollView === currentTableView { y_inset = playingModeOffsetY if scrollView.contentOffset.y > y_inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = scrollView.contentOffset.y - y_inset showHeader.frame.origin.y = ShowHeaderOriginY - delta // print("offsetY:\(scrollView.contentOffset.y) y_inset:\(y_inset) delta:\(delta) SectionOriginY - delta:\(SectionOriginY - delta)") let toolDelta = showHeader.frame.maxY - navBar.frame.maxY let toolTotal = ShowHeaderOriginY + ShowHeaderHeight //###### var alpha = toolDelta / toolTotal // A quick fix for toolView?.alpha remaining at 0.748, but reaching 1. var fixMe: Any? if alpha > 0.74 { alpha = 1.0 } toolView?.alpha = alpha //###### if showHeader.frame.maxY <= NavBarHeight { // origin.y is realdy negative since showHeader's top edge is alrady out of screen, so use -ShowHeaderHeight and then take out NavBarHeight. showHeader.frame.origin.y = -ShowHeaderHeight + NavBarHeight playingMode = false } }else{ // Scrolling too far, stick to its originY showHeader.frame.origin.y = ShowHeaderOriginY toolView?.alpha = 1.0 if scrollView.contentOffset.y <= -Y_Inset { playingMode = false scrollView.contentInset.top = Y_Inset } } }else{ if scrollView.contentOffset.y >= -Y_Inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = (Y_Inset + scrollView.contentOffset.y) showHeader.frame.origin.y = ShowHeaderOriginY - delta let toolDelta = showHeader.frame.maxY - navBar.frame.maxY let toolTotal = ShowHeaderOriginY + ShowHeaderHeight //###### var alpha = toolDelta / toolTotal // A quick fix for toolView?.alpha remaining at 0.748, but reaching 1. var fixMe: Any? if alpha > 0.74 { alpha = 1.0 } toolView?.alpha = alpha //###### if showHeader.frame.maxY <= NavBarHeight { showHeader.frame.origin.y = -ShowHeaderHeight + NavBarHeight } }else{ toolView?.alpha = 1.0 // Scrolling too far, stick to its originY showHeader.frame.origin.y = ShowHeaderOriginY } } } func handleEpisodeSectionView(_ scrollView: UIScrollView) { var y_inset = Y_Inset if playingMode && scrollView === currentTableView { y_inset = playingModeOffsetY if scrollView.contentOffset.y > y_inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = scrollView.contentOffset.y - y_inset sectionView.frame.origin.y = SectionOriginY - delta // print("offsetY:\(scrollView.contentOffset.y) y_inset:\(y_inset) delta:\(delta) SectionOriginY - delta:\(SectionOriginY - delta)") if sectionView.frame.origin.y <= NavBarHeight { // sticking at 64.0 sectionView.frame.origin.y = NavBarHeight playingMode = false } }else{ // Scrolling too far, stick to its originY sectionView.frame.origin.y = SectionOriginY if scrollView.contentOffset.y <= -Y_Inset { playingMode = false scrollView.contentInset.top = Y_Inset } } }else{ if scrollView.contentOffset.y >= -Y_Inset { // Position Y // yOffset is negative within Y_Inset!! // following tableView scrolling up // delta is the distance tableView scrolling up, is positive let delta = (Y_Inset + scrollView.contentOffset.y) sectionView.frame.origin.y = SectionOriginY - delta if sectionView.frame.origin.y <= NavBarHeight { // sticking at 64.0 sectionView.frame.origin.y = NavBarHeight } }else{ // Scrolling too far, stick to its originY sectionView.frame.origin.y = SectionOriginY } } } } //MARK:- AHFMShowHeaderDelegate extension AHFMShowPageVC: AHFMShowHeaderDelegate { public func showHeaderLikeBtnTapped(_ header: AHFMShowHeader) { guard let show = self.show else { return } if header.isSubscribed { self.manager?.showPageVC(self, shouldSubscribeOrUnSubcribeShow: show.id, shouldSubscribed: false) }else{ SVProgressHUD.show() // fake networking delay DispatchQueue.main.asyncAfter(deadline: .now() + 3) { self.manager?.showPageVC(self, shouldSubscribeOrUnSubcribeShow: show.id, shouldSubscribed: true) } } } public func showHeaderShareBtnTapped(_ header: AHFMShowHeader){ print("showHeaderShareBtnTapped") } public func showHeaderDownloadBtnTapped(_ header: AHFMShowHeader){ guard let show = self.show else { return } manager?.showPageVCDidTappDownloadBtnTapped(self, forshow: show.id) } public func showHeaderIntroTapped(_ header: AHFMShowHeader){ let vc = AHFMShowIntroVC() vc.show = show vc.dismissBlock = { self.manager?.showPageVCWillDismissIntroVC(self) } manager?.showPageVCWillPresentIntroVC(self) present(vc, animated: false, completion: nil) } } //MARK:- Helpers extension AHFMShowPageVC { fileprivate func urlToIndexPath(url: String) -> IndexPath? { guard let eps = self.episodes else { return nil } let filteredEps = eps.filter { (ep) -> Bool in return ep.remoteURL == url } guard filteredEps.count > 0, let targetEp = filteredEps.first else { return nil } let index = eps.index { (ep) -> Bool in return ep.id == targetEp.id } guard index != nil else { return nil } let indexPath = IndexPath(row: index!, section: 0) return indexPath } fileprivate func updateDownloadState(forUrl url: String) { guard let indexPath = urlToIndexPath(url: url) else { return } let state = AHDownloader.getState(url) self.episodes?[indexPath.row].downloadState = state print("AAAA") updateEpisodeCell(for: indexPath, state: state) } fileprivate func updateEpisodeCell(for indexPath: IndexPath, state: AHDataTaskState) { guard let cell = currentTableView.cellForRow(at: indexPath) as? AHFMShowPageCell else { return } print("BBB") switch state { case .notStarted: cell.normal() case .pausing: cell.pause() case .downloading: cell.downloading() case .succeeded: cell.downloaded() case .failed: cell.normal() } } /// The gateway for 'playingMoe'. /// Check if there's any episode that audioPlayer is playing and scroll to that playing episode and other sticky header related operations. fileprivate func checkCurrentEpisode() { guard let episodes = self.episodes else { return } if let playingTrackId = AHAudioPlayerManager.shared.playingTrackId { var index: Int? = nil for i in 0..<episodes.count { let ep = episodes[i] if ep.id == playingTrackId { index = i } } if index != nil { adjustForPlayingMode(forEpisodeAtIndex: index!) } } } func adjustForPlayingMode(forEpisodeAtIndex index: Int) { let playingIndexPath = IndexPath(row: index, section: 0) // you have scroll it first in order to get the cell self.currentTableView.scrollToRow(at: playingIndexPath, at: .top, animated: false) if let cell = self.currentTableView.cellForRow(at: playingIndexPath) { // positioning the cell right below sectionView + 20.0 var offsetY = cell.frame.origin.y - Y_Inset - 20.0 if offsetY < 0 { offsetY = -Y_Inset } // check if the add-up offsetY + one screen height is larger than contentSize.height else if offsetY + ScreenSize.height > self.currentTableView.contentSize.height { // assign the last screen to offsetY //TODO: figure out how/why that extra 1.0 prevent the header flip the top when the currentEpisdoe the in last screen. Take it off and assign the last ep, and see what happen. Then do research here. offsetY = self.currentTableView.contentSize.height - ScreenSize.height - 1.0 } // check if it will be too far down below the inset for first several cells which already in display. else if offsetY < -Y_Inset{ offsetY = -Y_Inset } playingModeOffsetY = offsetY playingMode = true self.currentTableView.contentOffset.y = offsetY } } } //MARK:- Setups extension AHFMShowPageVC { fileprivate func setup() { // All sizes and frames are based on ScreenSize and they are fixed. // TableView, on the bottom of the view hierarchy let tableViewRect = CGRect(x: 0, y: 0, width: ScreenSize.width, height: ScreenSize.height) let tableView = UITableView(frame: tableViewRect, style: .plain) tableView.delegate = self tableView.dataSource = showPageCellDataSource tableView.backgroundColor = UIColor.white tableView.separatorStyle = .none tableView.estimatedRowHeight = 50.0 tableView.contentInset = .init(top: Y_Inset, left: 0, bottom: 49.0, right: 0) showPageCellDataSource.tablView = tableView self.currentTableView = tableView // recommendedTableView let recommendedTableView = UITableView(frame: tableViewRect, style: .plain) recommendedTableView.delegate = self recommendedTableView.dataSource = showRecommendDataSource recommendedTableView.backgroundColor = UIColor.white recommendedTableView.separatorStyle = .none recommendedTableView.estimatedRowHeight = 60.0 recommendedTableView.contentInset = .init(top: Y_Inset, left: 0, bottom: 49.0, right: 0) showRecommendDataSource.tablView = recommendedTableView self.recommendedTableView = recommendedTableView // Show Header let showHeader = AHFMShowHeader.loadNib() showHeader.frame = CGRect(x: 0, y: 0.0, width: ScreenSize.width, height: ShowHeaderHeight) showHeader.backgroundColor = UIColor.white showHeader.delegate = self self.view.addSubview(showHeader) self.showHeader = showHeader // SectionView let sectionView = AHSectionView() sectionView.frame = CGRect(x: 0, y: SectionOriginY, width: ScreenSize.width, height: SectionViewHeight) sectionView.backgroundColor = UIColor.white self.view.addSubview(sectionView) self.sectionView = sectionView // add section buttons epSectionleft.frame = .init(x: 0, y: 0, width: sectionView.bounds.width * 0.5, height: sectionView.bounds.height) epSectionleft.addTarget(self, action: #selector(sectionBtnsTapped(_:)), for: .touchUpInside) epSectionleft.setTitle("Episodes", for: .normal) epSectionleft.setTitleColor(UIColor.black, for: .normal) sectionView.addSection(epSectionleft) epSectionRight.frame = .init(x: sectionView.bounds.width * 0.5, y: 0, width: sectionView.bounds.width * 0.5, height: sectionView.bounds.height) epSectionRight.addTarget(self, action: #selector(sectionBtnsTapped(_:)), for: .touchUpInside) epSectionRight.setTitle("Recoomended", for: .normal) epSectionRight.setTitleColor(UIColor.black, for: .normal) sectionView.addSection(epSectionRight) // NavBar, on the top of the view hierarchy let navBar = self.navigationController!.navigationBar // navBar.setBackgroundImage(UIImage(), for: .default) // navBar.shadowImage = UIImage() // navBar.isTranslucent = true let backImage = UIImage(name: "back", user: self)?.withRenderingMode(.alwaysOriginal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(backBtnTapped(_:))) titleLabel.frame.size = CGSize(width: 200, height: 64) titleLabel.text = "" titleLabel.textColor = UIColor.white titleLabel.textAlignment = .center titleLabel.font = UIFont.systemFont(ofSize: 17.0) self.navigationItem.titleView = titleLabel self.navBar = navBar } } struct Episode { var id: Int var remoteURL: String? var title: String? var createdAt: String? var duration: TimeInterval? var downloadedProgress: Double? var downloadState: AHDataTaskState = .notStarted init(_ dict: [String: Any]) { self.id = dict["id"] as! Int self.remoteURL = dict["remoteURL"] as? String self.title = dict["title"] as? String self.duration = dict["duration"] as? TimeInterval self.createdAt = dict["createdAt"] as? String self.downloadedProgress = dict["downloadedProgress"] as? Double if let remoteURL = self.remoteURL{ if let isDownloaded = dict["isDownloaded"] as? Bool, isDownloaded == true { self.downloadState = .succeeded }else if let progress = self.downloadedProgress, progress > 0, AHDownloader.getState(remoteURL) == .notStarted{ // the task is not started yet there's a downloaded progress -- this is an archived task. self.downloadState = .pausing }else{ self.downloadState = AHDownloader.getState(remoteURL) } }else{ self.downloadState = .failed } } } struct Show: Equatable { var id: Int var title: String var detail: String var fullCover: String var thumbCover: String var isSubscribed: Bool init(_ dict: [String: Any]) { self.id = dict["id"] as! Int self.title = dict["title"] as! String self.fullCover = dict["fullCover"] as! String self.thumbCover = dict["thumbCover"] as! String self.detail = dict["detail"] as! String self.isSubscribed = dict["isSubscribed"] as! Bool } public static func ==(lhs: Show, rhs: Show) -> Bool { return lhs.id == rhs.id } }
35.611173
213
0.587475
7663a68fbb228192ef5345f3fba04534c1536f20
1,165
// // Copyright 2017-2018 Amazon.com, Inc. or its affiliates. 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. // A copy of the License is located at // // http://aws.amazon.com/apache2.0 // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // import Foundation typealias AWSAsyncBlockDoneClosure = () -> Void typealias AWSAsyncBlockClosure = (@escaping AWSAsyncBlockDoneClosure) -> Void class AWSAsyncBlockOperation: AWSAsyncOperation { private let asyncBlock: AWSAsyncBlockClosure init(asyncBlock: @escaping AWSAsyncBlockClosure) { self.asyncBlock = asyncBlock super.init() } override func main() { let done: AWSAsyncBlockDoneClosure = { [weak self] in guard let self = self else { fatalError() } self.finish() } asyncBlock(done) } }
30.657895
79
0.701288
b9f812100dd6597632c5a074007e28e7b0d2b4bf
16,766
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2019-2020 Datadog, Inc. */ import Foundation /// Datadog SDK configuration object. public class Datadog { /// Provides information about the app. public struct AppContext { internal let bundleType: BundleType internal let bundleIdentifier: String? /// Executable version (i.e. application version or app extension version) internal let bundleVersion: String? /// Executable name (i.e. application name or app extension name) internal let bundleName: String? /// Process info internal let processInfo: ProcessInfo public init(mainBundle: Bundle = Bundle.main, processInfo: ProcessInfo = ProcessInfo.processInfo) { let bundleVersion = mainBundle.object(forInfoDictionaryKey: "CFBundleVersion") as? String let bundleShortVersion = mainBundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String self.init( bundleType: mainBundle.bundlePath.hasSuffix(".appex") ? .iOSAppExtension : .iOSApp, bundleIdentifier: mainBundle.bundleIdentifier, bundleVersion: bundleShortVersion ?? bundleVersion, bundleName: mainBundle.object(forInfoDictionaryKey: "CFBundleExecutable") as? String, processInfo: processInfo ) } internal init( bundleType: BundleType, bundleIdentifier: String?, bundleVersion: String?, bundleName: String?, processInfo: ProcessInfo ) { self.bundleType = bundleType self.bundleIdentifier = bundleIdentifier self.bundleVersion = bundleVersion self.bundleName = bundleName self.processInfo = processInfo } } /// Initializes the Datadog SDK. /// - Parameters: /// - appContext: context passing information about the app. /// - configuration: the SDK configuration obtained using `Datadog.Configuration.builderUsing(...)`. @available(*, deprecated, message: """ This method is deprecated and uses the `TrackingConsent.granted` value as a default privacy consent. This means that the SDK will start recording and sending data immediately after initialisation without waiting for the user's consent to be given. Use `Datadog.initialize(appContext:trackingConsent:configuration:)` and set consent to `.granted` to preserve previous behaviour. """) public static func initialize(appContext: AppContext, configuration: Configuration) { initialize( appContext: appContext, trackingConsent: .granted, configuration: configuration ) } /// Initializes the Datadog SDK. /// - Parameters: /// - appContext: context passing information about the app. /// - trackingConsent: the initial state of the Data Tracking Consent given by the user of the app. /// - configuration: the SDK configuration obtained using `Datadog.Configuration.builderUsing(...)`. public static func initialize( appContext: AppContext, trackingConsent: TrackingConsent, configuration: Configuration ) { // TODO: RUMM-511 remove this warning #if targetEnvironment(macCatalyst) consolePrint("⚠️ Catalyst is not officially supported by Datadog SDK: some features may NOT be functional!") #endif do { try initializeOrThrow( initialTrackingConsent: trackingConsent, configuration: try FeaturesConfiguration( configuration: configuration, appContext: appContext ) ) // Now that RUM is potentially initialized, override the debugRUM value let debugRumOverride = appContext.processInfo.arguments.contains(LaunchArguments.DebugRUM) if debugRumOverride { consolePrint("⚠️ Overriding RUM debugging due to \(LaunchArguments.DebugRUM) launch argument") Datadog.debugRUM = true } } catch { consolePrint("\(error)") } } /// Verbosity level of Datadog SDK. Can be used for debugging purposes. /// If set, internal events occuring inside SDK will be printed to debugger console if their level is equal or greater than `verbosityLevel`. /// Default is `nil`. public static var verbosityLevel: LogLevel? = nil /// Utility setting to inspect the active RUM View. /// If set, a debugging outline will be displayed on top of the application, describing the name of the active RUM View. /// May be used to debug issues with RUM instrumentation in your app. /// Default is `false`. public static var debugRUM = false { didSet { (Global.rum as? RUMMonitor)?.enableRUMDebugging(debugRUM) } } /// Returns `true` if the Datadog SDK is already initialized, `false` otherwise. public static var isInitialized: Bool { return instance != nil } /// Sets current user information. /// Those will be added to logs, traces and RUM events automatically. /// - Parameters: /// - id: User ID, if any /// - name: Name representing the user, if any /// - email: User's email, if any /// - extraInfo: User's custom attributes, if any public static func setUserInfo( id: String? = nil, name: String? = nil, email: String? = nil, extraInfo: [AttributeKey: AttributeValue] = [:] ) { instance?.userInfoProvider.value = UserInfo( id: id, name: name, email: email, extraInfo: extraInfo ) } /// Sets the tracking consent regarding the data collection for the Datadog SDK. /// - Parameter trackingConsent: new consent value, which will be applied for all data collected from now on public static func set(trackingConsent: TrackingConsent) { instance?.consentProvider.changeConsent(to: trackingConsent) } /// Clears all data that has not already been sent to Datadog servers. public static func clearAllData() { instance?.clearAllData() } // MARK: - Internal internal struct LaunchArguments { static let Debug = "DD_DEBUG" static let DebugRUM = "DD_DEBUG_RUM" } internal static var instance: Datadog? internal let consentProvider: ConsentProvider internal let userInfoProvider: UserInfoProvider internal let launchTimeProvider: LaunchTimeProviderType private static func initializeOrThrow( initialTrackingConsent: TrackingConsent, configuration: FeaturesConfiguration ) throws { guard Datadog.instance == nil else { throw ProgrammerError(description: "SDK is already initialized.") } let kronosMonitor: KronosMonitor? #if DD_SDK_ENABLE_INTERNAL_MONITORING // Collect Kronos telemetry only if internal monitoring is compiled and enabled kronosMonitor = configuration.internalMonitoring != nil ? KronosInternalMonitor() : nil #else kronosMonitor = nil #endif let consentProvider = ConsentProvider(initialConsent: initialTrackingConsent) let dateProvider = SystemDateProvider() let dateCorrector = DateCorrector( deviceDateProvider: dateProvider, serverDateProvider: NTPServerDateProvider(kronosMonitor: kronosMonitor) ) let userInfoProvider = UserInfoProvider() let networkConnectionInfoProvider = NetworkConnectionInfoProvider() let carrierInfoProvider = CarrierInfoProvider() let launchTimeProvider = LaunchTimeProvider() // First, initialize internal loggers: let internalLoggerConfiguration = InternalLoggerConfiguration( sdkVersion: configuration.common.sdkVersion, applicationVersion: configuration.common.applicationVersion, environment: configuration.common.environment, userInfoProvider: userInfoProvider, networkConnectionInfoProvider: networkConnectionInfoProvider, carrierInfoProvider: carrierInfoProvider ) userLogger = createSDKUserLogger(configuration: internalLoggerConfiguration) // Then, initialize features: var internalMonitoring: InternalMonitoringFeature? var logging: LoggingFeature? var tracing: TracingFeature? var rum: RUMFeature? var crashReporting: CrashReportingFeature? var urlSessionAutoInstrumentation: URLSessionAutoInstrumentation? var rumInstrumentation: RUMInstrumentation? let commonDependencies = FeaturesCommonDependencies( consentProvider: consentProvider, performance: configuration.common.performance, httpClient: HTTPClient(proxyConfiguration: configuration.common.proxyConfiguration), mobileDevice: MobileDevice(), sdkInitDate: dateProvider.currentDate(), dateProvider: dateProvider, dateCorrector: dateCorrector, userInfoProvider: userInfoProvider, networkConnectionInfoProvider: networkConnectionInfoProvider, carrierInfoProvider: carrierInfoProvider, launchTimeProvider: launchTimeProvider, appStateListener: AppStateListener(dateProvider: dateProvider), encryption: configuration.common.encryption ) if let internalMonitoringConfiguration = configuration.internalMonitoring { internalMonitoring = InternalMonitoringFeature( logDirectories: try obtainInternalMonitoringFeatureLogDirectories(), configuration: internalMonitoringConfiguration, commonDependencies: commonDependencies ) } if let loggingConfiguration = configuration.logging { logging = LoggingFeature( directories: try obtainLoggingFeatureDirectories(), configuration: loggingConfiguration, commonDependencies: commonDependencies, internalMonitor: internalMonitoring?.monitor ) } if let tracingConfiguration = configuration.tracing { tracing = TracingFeature( directories: try obtainTracingFeatureDirectories(), configuration: tracingConfiguration, commonDependencies: commonDependencies, loggingFeatureAdapter: logging.flatMap { LoggingForTracingAdapter(loggingFeature: $0) }, tracingUUIDGenerator: DefaultTracingUUIDGenerator(), internalMonitor: internalMonitoring?.monitor ) } if let rumConfiguration = configuration.rum { rum = RUMFeature( directories: try obtainRUMFeatureDirectories(), configuration: rumConfiguration, commonDependencies: commonDependencies, internalMonitor: internalMonitoring?.monitor ) if let instrumentationConfiguration = rumConfiguration.instrumentation { rumInstrumentation = RUMInstrumentation( configuration: instrumentationConfiguration, dateProvider: dateProvider ) } } if let crashReportingConfiguration = configuration.crashReporting { crashReporting = CrashReportingFeature( configuration: crashReportingConfiguration, commonDependencies: commonDependencies ) } if let urlSessionAutoInstrumentationConfiguration = configuration.urlSessionAutoInstrumentation { urlSessionAutoInstrumentation = URLSessionAutoInstrumentation( configuration: urlSessionAutoInstrumentationConfiguration, commonDependencies: commonDependencies ) } InternalMonitoringFeature.instance = internalMonitoring LoggingFeature.instance = logging TracingFeature.instance = tracing RUMFeature.instance = rum CrashReportingFeature.instance = crashReporting RUMInstrumentation.instance = rumInstrumentation RUMInstrumentation.instance?.enable() URLSessionAutoInstrumentation.instance = urlSessionAutoInstrumentation URLSessionAutoInstrumentation.instance?.enable() // Only after all features were initialized with no error thrown: self.instance = Datadog( consentProvider: consentProvider, userInfoProvider: userInfoProvider, launchTimeProvider: launchTimeProvider ) // After everything is set up, if the Crash Reporting feature was enabled, // register crash reporter and send crash report if available: if let crashReportingFeature = CrashReportingFeature.instance { Global.crashReporter = CrashReporter(crashReportingFeature: crashReportingFeature) Global.crashReporter?.sendCrashReportIfFound() } // If Internal Monitoring is enabled and Kronos internal monitor is configured, // export result of NTP sync to IM. if let internalMonitoringFeature = InternalMonitoringFeature.instance { kronosMonitor?.export(to: internalMonitoringFeature.monitor) } } internal init( consentProvider: ConsentProvider, userInfoProvider: UserInfoProvider, launchTimeProvider: LaunchTimeProviderType ) { self.consentProvider = consentProvider self.userInfoProvider = userInfoProvider self.launchTimeProvider = launchTimeProvider } internal func clearAllData() { LoggingFeature.instance?.storage.clearAllData() TracingFeature.instance?.storage.clearAllData() RUMFeature.instance?.storage.clearAllData() InternalMonitoringFeature.instance?.logsStorage.clearAllData() } /// Flushes all authorised data for each feature, tears down and deinitializes the SDK. /// - It flushes all data authorised for each feature by performing its arbitrary upload (without retrying). /// - It completes all pending asynchronous work in each feature. /// /// This is highly experimental API and only supported in tests. #if DD_SDK_COMPILED_FOR_TESTING public static func flushAndDeinitialize() { internalFlushAndDeinitialize() } #endif internal static func internalFlushAndDeinitialize() { assert(Datadog.instance != nil, "SDK must be first initialized.") // Tear down and deinitialize all features: LoggingFeature.instance?.deinitialize() TracingFeature.instance?.deinitialize() RUMFeature.instance?.deinitialize() InternalMonitoringFeature.instance?.deinitialize() CrashReportingFeature.instance?.deinitialize() RUMInstrumentation.instance?.deinitialize() URLSessionAutoInstrumentation.instance?.deinitialize() // Reset Globals: Global.sharedTracer = DDNoopGlobals.tracer Global.rum = DDNoopRUMMonitor() Global.crashReporter?.deinitialize() Global.crashReporter = nil // Deinitialize `Datadog`: Datadog.instance = nil // Reset internal loggers: userLogger = createNoOpSDKUserLogger() } } /// Convenience typealias. internal typealias AppContext = Datadog.AppContext /// An exception thrown due to programmer error when calling SDK public API. /// It makes the SDK non-functional and print the error to developer in debugger console.. /// When thrown, check if configuration passed to `Datadog.initialize(...)` is correct /// and if you do not call any other SDK methods before it returns. internal struct ProgrammerError: Error, CustomStringConvertible { init(description: String) { self.description = "🔥 Datadog SDK usage error: \(description)" } let description: String } /// An exception thrown internally by SDK. /// It is always handled by SDK (keeps it functional) and never passed to the user until `Datadog.verbosity` is set (then it might be printed in debugger console). /// `InternalError` might be thrown due to programmer error (API misuse) or SDK internal inconsistency or external issues (e.g. I/O errors). The SDK /// should always recover from that failures. internal struct InternalError: Error, CustomStringConvertible { let description: String }
41.915
163
0.676428
29ace8b699f337a6716f5b5c03ab074ef9fd60c0
10,396
///// Copyright (c) 2021 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 Foundation import OpenSSL import UIKit enum ReceiptStatus: String { case validationSuccess = "This receipt is valid." case noReceiptPresent = "A receipt was not found on this device." case unknownFailure = "An unexpected failure occurred during verification." case unknownReceiptFormat = "The receipt is not in PKCS7 format." case invalidPKCS7Signature = "Invalid PKCS7 Signature." case invalidPKCS7Type = "Invalid PKCS7 Type." case invalidAppleRootCertificate = "Public Apple root certificate not found." case failedAppleSignature = "Receipt not signed by Apple." case unexpectedASN1Type = "Unexpected ASN1 Type." case missingComponent = "Expected component was not found." case invalidBundleIdentifier = "Receipt bundle identifier does not match application bundle identifier." case invalidVersionIdentifier = "Receipt version identifier does not match application version." case invalidHash = "Receipt failed hash check." case invalidExpired = "Receipt has expired." } class AppleReceipt { var receiptStatus: ReceiptStatus? var bundleIdString: String? var bundleIdData: Data? var bundleVersionString: String? var opaqueData: Data? var hashData: Data? var receiptCreationDate: Date? var originalAppVersion: String? var expirationDate: Date? var purchases = [PurchaseDetails]() init() { guard let payload = loadReceipt() else { return } guard validateSigning(payload) else { return } readReceipt(payload) validateReceipt() } static public func isReceiptPresent() -> Bool { if let receiptUrl = Bundle.main.appStoreReceiptURL, let canReach = try? receiptUrl.checkResourceIsReachable(), canReach { return true } return false } private func validateReceipt() { guard let idString = bundleIdString, let version = bundleVersionString, let _ = opaqueData, let hash = hashData else { receiptStatus = .missingComponent return } guard let appBundleId = Bundle.main.bundleIdentifier else { receiptStatus = .unknownFailure return } guard idString == appBundleId else { receiptStatus = .invalidBundleIdentifier return } guard let appVersionString = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String else { receiptStatus = .unknownFailure return } guard version == appVersionString else { receiptStatus = .invalidVersionIdentifier return } let guidHash = computeHash() guard hash == guidHash else { receiptStatus = .invalidHash return } let currentDate = Date() if let expirationDate = expirationDate { if expirationDate < currentDate { receiptStatus = .invalidExpired return } } receiptStatus = .validationSuccess } private func computeHash() -> Data { let identifierData = getDeviceIdentifier() var ctx = SHA_CTX() SHA1_Init(&ctx) let identifierBytes: [UInt8] = .init(identifierData) SHA1_Update(&ctx, identifierBytes, identifierData.count) let opaqueBytes: [UInt8] = .init(opaqueData!) SHA1_Update(&ctx, opaqueBytes, opaqueData!.count) let bundleBytes: [UInt8] = .init(bundleIdData!) SHA1_Update(&ctx, bundleBytes, bundleIdData!.count) var hash: [UInt8] = .init(repeating: 0, count: 20) SHA1_Final(&hash, &ctx) return Data(bytes: hash, count: 20) } private func getDeviceIdentifier() -> Data { let device = UIDevice.current var uuid = device.identifierForVendor!.uuid let addr = withUnsafePointer(to: &uuid) { p -> UnsafeRawPointer in UnsafeRawPointer(p) } return Data(bytes: addr, count: 16) } private func readReceipt(_ receiptPKCS7: UnsafeMutablePointer<PKCS7>?) { let receiptSignature = receiptPKCS7?.pointee.d.sign let receiptData = receiptSignature?.pointee.contents.pointee.d.data var ptr = UnsafePointer(receiptData?.pointee.data) let end = ptr!.advanced(by: Int(receiptData!.pointee.length)) var type: Int32 = 0 var xclass: Int32 = 0 var length: Int = 0 ASN1_get_object(&ptr, &length, &type, &xclass, ptr!.distance(to: end)) guard type == V_ASN1_SET else { receiptStatus = .unexpectedASN1Type return } while ptr! < end { ASN1_get_object(&ptr, &length, &type, &xclass, ptr!.distance(to: end)) guard type == V_ASN1_SEQUENCE else { receiptStatus = .unexpectedASN1Type return } guard let attributeType = readASN1Integer(ptr: &ptr, maxLength: length) else { receiptStatus = .unexpectedASN1Type return } guard let _ = readASN1Integer(ptr: &ptr, maxLength: ptr!.distance(to: end)) else { receiptStatus = .unexpectedASN1Type return } ASN1_get_object(&ptr, &length, &type, &xclass, ptr!.distance(to: end)) guard type == V_ASN1_OCTET_STRING else { receiptStatus = .unexpectedASN1Type return } switch attributeType { case 2: // bundle identifier var p = ptr bundleIdString = readASN1String(ptr: &p, maxLength: length) bundleIdData = readASN1Data(ptr: ptr!, length: length) case 3: // bundle version var p = ptr bundleVersionString = readASN1String(ptr: &p, maxLength: length) case 4: // opaque value let p = ptr! opaqueData = readASN1Data(ptr: p, length: length) case 5: // computed guid (sha1 hash) let p = ptr! hashData = readASN1Data(ptr: p, length: length) case 12: // receipt creation date var p = ptr receiptCreationDate = readASN1Date(ptr: &p, maxLength: length) case 17: // IAP details var p = ptr if let purchase = PurchaseDetails(with: &p, payloadLength: length) { purchases.append(purchase) } case 19: // original app version var p = ptr originalAppVersion = readASN1String(ptr: &p, maxLength: length) case 21: // expiration date var p = ptr expirationDate = readASN1Date(ptr: &p, maxLength: length) default: // ignore other attributes print("not processing attribute type: \(attributeType)") } ptr = ptr!.advanced(by: length) } } private func validateSigning(_ receipt: UnsafeMutablePointer<PKCS7>?) -> Bool { #if DEBUG let certificate = "StoreKitTestCertificate" #else let certificate = "AppleIncRootCertificate" #endif guard let rootCertUrl = Bundle.main.url(forResource: certificate, withExtension: "cer"), let rootCertData = try? Data(contentsOf: rootCertUrl) else { receiptStatus = .invalidAppleRootCertificate return false } let rootCertBIO = BIO_new(BIO_s_mem()) let rootCertBytes: [UInt8] = .init(rootCertData) BIO_write(rootCertBIO, rootCertBytes, Int32(rootCertData.count)) let rootCertX509 = d2i_X509_bio(rootCertBIO, nil) BIO_free(rootCertBIO) let store = X509_STORE_new() X509_STORE_add_cert(store, rootCertX509) OPENSSL_init_crypto(UInt64(OPENSSL_INIT_ADD_ALL_DIGESTS), nil) #if DEBUG let verificationResult = PKCS7_verify(receipt, nil, store, nil, nil, PKCS7_NOCHAIN) #else let verificationResult = PKCS7_verify(receipt, nil, store, nil, nil, 0) #endif X509_STORE_free(store) guard verificationResult == 1 else { receiptStatus = .failedAppleSignature return false } return true } private func loadReceipt() -> UnsafeMutablePointer<PKCS7>? { guard let receiptUrl = Bundle.main.appStoreReceiptURL, let receiptData = try? Data(contentsOf: receiptUrl) else { receiptStatus = .noReceiptPresent return nil } let receiptBIO = BIO_new(BIO_s_mem()) let receiptBytes: [UInt8] = .init(receiptData) BIO_write(receiptBIO, receiptBytes, Int32(receiptData.count)) let receiptPKCS7 = d2i_PKCS7_bio(receiptBIO, nil) BIO_free(receiptBIO) guard receiptPKCS7 != nil else { receiptStatus = .unknownReceiptFormat return nil } guard OBJ_obj2nid(receiptPKCS7!.pointee.type) == NID_pkcs7_signed else { receiptStatus = .invalidPKCS7Signature return nil } let receiptContents = receiptPKCS7!.pointee.d.sign.pointee.contents guard OBJ_obj2nid(receiptContents?.pointee.type) == NID_pkcs7_data else { receiptStatus = .invalidPKCS7Type return nil } return receiptPKCS7 } }
37.395683
110
0.691901
0af3e5eae02b54c989e12dae40daca74275015f2
2,080
/*: # 441. Arranging Coins [Easy] https://leetcode.com/problems/arranging-coins/ --- ### Problem Statement: You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. ### Example 1: ``` n = 5 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ Because the 3rd row is incomplete, we return 2. ``` ### Example 2: ``` n = 8 The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤ Because the 4th row is incomplete, we return 3. ``` */ import UIKit class Solution { // Brute force solution // 1336 / 1336 test cases passed. // Status: Accepted // Runtime: 40 ms // Memory Usage: 20.5 MB func arrangeCoinsBruteForce(_ n: Int) -> Int { var count = 0 var increment = 1 var n = n while n >= 0 { n = n-increment count += 1 increment += 1 } return count - 1 } // 1336 / 1336 test cases passed. // Status: Accepted // Runtime: 8 ms // Memory Usage: 20.4 MB // Time complexity: O(logN) // Space complexity: O(1) func arrangeCoins(_ n: Int) -> Int { var left = 0 var right = n var mid:Int var curr:Int while left <= right { mid = (left + right) / 2 curr = mid * (mid + 1) / 2 if curr == n { return mid } if (n < curr) { right = mid - 1 } else { left = mid + 1 } } return right } // Time complexity: O(1) // Space complexity: O(1) func arrangeCoins2(_ n: Int) -> Int { return Int(sqrt(2 * Double(n) + 0.25) - 0.5) } } let sol = Solution() sol.arrangeCoins2(5) // 2 sol.arrangeCoins2(8) // 3 sol.arrangeCoins2(10) // 4
18.909091
120
0.511538
e857c0199eaeabd138d8727529ee6873427e9d7d
748
// // TaskListView.swift // TodoRealmSwiftUI // // Created by Hafiz on 26/09/2021. // import SwiftUI struct TaskListView: View { @EnvironmentObject private var viewModel: TaskViewModel var body: some View { ScrollView { LazyVStack (alignment: .leading) { ForEach(viewModel.tasks, id: \.id) { task in NavigationLink (destination: TaskView(task: task)) { TaskRowView(task: task) } Divider().padding(.leading, 20) } .animation(.default) } } } } struct TaskListView_Previews: PreviewProvider { static var previews: some View { TaskListView() } }
23.375
72
0.536096
67da1e8eb6016bd7b06ba12869bcb290479344c3
1,563
// // DetailsViewController.swift // Yelp // // Created by Josh Gebbeken on 2/13/16. // Copyright © 2016 Timothy Lee. All rights reserved. // import UIKit class DetailsViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var ratingsImageView: UIImageView! @IBOutlet weak var reviewsLabel: UILabel! var business: Business! override func viewDidLoad() { super.viewDidLoad() nameLabel.text = business.name categoriesLabel.text = business.categories addressLabel.text = business.address reviewsLabel.text = "\(business.reviewCount!) Reviews" ratingsImageView.setImageWithURL(business.ratingImageURL!) distanceLabel.text = business.distance nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
30.647059
106
0.699936
6700e35b23ffd2b25cc681d7efa4952adc57b382
3,656
// // HomeViewController.swift // Parsetagram // // Created by Avinash Singh on 07/12/17. // Copyright © 2017 Avinash Singh. All rights reserved. // import UIKit import Parse class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { var posts : [PFObject]? @IBOutlet weak var photosTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() photosTableView.delegate = self photosTableView.dataSource = self photosTableView.rowHeight = UITableViewAutomaticDimension photosTableView.estimatedRowHeight = 100 let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) photosTableView.insertSubview(refreshControl, at: 0) makeNetworkRequest() // Do any additional setup after loading the view. } func makeNetworkRequest(){ let query = PFQuery(className: "Post") query.order(byDescending: "createdAt") query.includeKey("author") query.limit = 20 // fetch data asynchronously query.findObjectsInBackground { (posts: [PFObject]?, error: Error?) in if let posts = posts { self.posts = posts self.photosTableView.reloadData() // print(self.posts) } else { print(error!.localizedDescription) } } } func refreshControlAction(_ refreshControl: UIRefreshControl) { makeNetworkRequest() refreshControl.endRefreshing() // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let posts = posts { return posts.count } else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PhotoCell", for: indexPath) as! PhotosTableViewCell if posts != nil{ let post = posts![indexPath.row] cell.post = post // print("caption labels") print(cell.captionLabel) } return cell } override func viewWillAppear(_ animated: Bool) { let query = PFQuery(className: "Post") query.order(byDescending: "createdAt") query.includeKey("author") query.limit = 20 // fetch data asynchronously query.findObjectsInBackground { (posts: [PFObject]?, error: Error?) in if let posts = posts { self.posts = posts self.photosTableView.reloadData() // print(self.posts) } else { print(error!.localizedDescription) } } //self.photosTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
28.787402
122
0.596007
08a21affb80e041aa3dd998fd77b96a881eaa1c4
1,512
// // Presentation.swift // Navigator_Example // // Created by liuxc on 2019/7/3. // Copyright © 2019 CocoaPods. All rights reserved. // import Foundation import PageNavigator enum Presentation { case modal case push case modalNavigation case set([SceneName]) case transition case dismissFirst case dismissScene case dismissAll case pop case popToRoot case deeplink case preview case popover case rootModal case rootModalNav case rootModalNavPush var value: String { switch self { case .pop: return "pop" case .popToRoot: return "popToRoot" case .dismissScene: return "dismissScene" case .dismissFirst: return "dismissFirst" case .dismissAll: return "dismissAll" case .deeplink: return "deeplink" case .preview: return "preview" case .modal: return "modal" case .push: return "push" case .modalNavigation: return "modalNav" case .transition: return "transition" case .popover: return "popover" case .rootModal: return "root modal" case .rootModalNav: return "root modalNav" case .rootModalNavPush: return "root modalNav push" case .set(let scenes): return "root set \(scenes.count) scenes" } } }
22.235294
52
0.563492
6a11e5f2bc046575a5766f4a52155ed62ebf3fd7
1,369
// // NSNumber+Utilites.swift // WhatToCook // // Created by Vitaliy Kuzmenko on 08/10/14. // Copyright (c) 2014 KuzmenkoFamily. All rights reserved. // import Foundation let kStringToNumberFormatter = NumberFormatter() extension NSNumber { convenience public init(string value: String?) { guard let value = value else { self.init(value: 0 as Double) return } let formatter = kStringToNumberFormatter formatter.numberStyle = .decimal var separator = "." if let safeSeparator = formatter.decimalSeparator { separator = safeSeparator } var safeValue = value if separator == "," { safeValue = value.replacingOccurrences(of: ".", with: ",", options: [], range: nil) } else { safeValue = value.replacingOccurrences(of: ",", with: ".", options: [], range: nil) } if safeValue.isEmpty { safeValue = "0" } let number = formatter.number(from: safeValue) if let double = number?.doubleValue { self.init(value: double as Double) } else { self.init(value: 0 as Double) } } public var roundDoubleValue: Double { return floor(100 * doubleValue) / 100 } }
25.351852
95
0.553689
1d6a4457fcdfe0964cda57d95affe5362635aa20
212
// // VectorApp.swift // Vector // // Created by 石玉龙 on 2021/1/7. // import SwiftUI @main struct VectorApp: App { var body: some Scene { WindowGroup { ContentView() } } }
11.777778
31
0.533019
d5afeff3f3379be1d91f1503bca84a13d1b760da
1,361
// // ContentView.swift // SwiftUI-MVVM // // Created by M.Waqas on 25/3/20. // Copyright © 2020 M.Waqas. All rights reserved. // import SwiftUI struct ForecastListView : View { @ObservedObject var viewModel: ForecastViewModel var body: some View { NavigationView { LoadingView(isShowing: $viewModel.isLoading) { List { ForEach(self.viewModel.forecast) { forecast in Section(header: Text(forecast.weekDay).fontWeight(.bold)) { ForEach(forecast.forecast) { item in ForecastListRow(forecast: item) } } } }.listStyle(GroupedListStyle()).padding(EdgeInsets(top: 10, leading: -10, bottom: 10, trailing: 10)) .alert(isPresented: self.$viewModel.isErrorShown, content: { () -> Alert in Alert(title: Text("Error"), message: Text(self.viewModel.errorMessage)) }) } .navigationBarTitle(Text(viewModel.forecast.first?.name ?? "")) } .onAppear(perform: { self.viewModel.apply(.onAppear) }) } } #if DEBUG struct RepositoryListView_Previews : PreviewProvider { static var previews: some View { ForecastListView(viewModel: .init()) } } #endif
30.931818
116
0.562087
0a974aeda8e0edf65f7627fe0992f487b1b4bb4c
1,540
// // EmployeeSearch.swift // Colleagues // // Created by lanjing on 3/11/16. // Copyright © 2016 Razeware LLC. All rights reserved. // import Foundation import CoreSpotlight import MobileCoreServices extension Employee{ public static let domainIdentifier = "com.raywenderlich.colleagues.employee" public var userActivityUserInfo: [NSObject: AnyObject] { return ["id": objectId] } public var userActivity: NSUserActivity { let activity = NSUserActivity(activityType: Employee.domainIdentifier) activity.title = name activity.userInfo = userActivityUserInfo activity.keywords = [email, department] activity.contentAttributeSet = attributeSet return activity } public var attributeSet: CSSearchableItemAttributeSet { let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeContact as String) attributeSet.title = name attributeSet.contentDescription = "\(department), \(title)\n\(phone)" attributeSet.thumbnailData = UIImageJPEGRepresentation( loadPicture(), 0.9) attributeSet.supportsPhoneCall = true attributeSet.phoneNumbers = [phone] attributeSet.emailAddresses = [email] attributeSet.keywords = skills attributeSet.relatedUniqueIdentifier = objectId return attributeSet } var searchableItem: CSSearchableItem { let item = CSSearchableItem(uniqueIdentifier: objectId, domainIdentifier: Employee.domainIdentifier, attributeSet: attributeSet) return item } }
18.117647
134
0.731818
f7fecb60cf5c189619be8657cafb99b797ecf25b
7,831
// File created from ScreenTemplate // $ createScreen.sh SideMenu SideMenu /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit final class SideMenuViewController: UIViewController { // MARK: - Constants private enum Constants { static let sideMenuActionViewHeight: CGFloat = 44.0 } // MARK: - Properties // MARK: Outlets @IBOutlet weak var spaceListContainerView: UIView! // User info @IBOutlet private weak var userAvatarView: UserAvatarView! @IBOutlet private weak var userDisplayNameLabel: UILabel! @IBOutlet private weak var userIdLabel: UILabel! // Bottom menu items @IBOutlet private weak var menuItemsStackView: UIStackView! // MARK: Private private var viewModel: SideMenuViewModelType! private var theme: Theme! private var keyboardAvoider: KeyboardAvoider? private var errorPresenter: MXKErrorPresentation! private var activityPresenter: ActivityIndicatorPresenter! private var sideMenuActionViews: [SideMenuActionView] = [] private weak var sideMenuVersionView: SideMenuVersionView? // MARK: - Setup class func instantiate(with viewModel: SideMenuViewModelType) -> SideMenuViewController { let viewController = StoryboardScene.SideMenuViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.activityPresenter = ActivityIndicatorPresenter() self.errorPresenter = MXKErrorAlertPresentation() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) self.viewModel.viewDelegate = self self.viewModel.process(viewAction: .loadData) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.view.backgroundColor = theme.colors.background self.userAvatarView.update(theme: theme) self.userDisplayNameLabel.textColor = theme.textPrimaryColor self.userDisplayNameLabel.font = theme.fonts.title3SB self.userIdLabel.textColor = theme.textSecondaryColor for sideMenuActionView in self.sideMenuActionViews { sideMenuActionView.update(theme: theme) } self.sideMenuVersionView?.update(theme: theme) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { } private func render(viewState: SideMenuViewState) { switch viewState { case .loading: self.renderLoading() case .loaded(let viewData): self.renderLoaded(viewData: viewData) case .error(let error): self.render(error: error) } } private func renderLoading() { self.activityPresenter.presentActivityIndicator(on: self.view, animated: true) } private func renderLoaded(viewData: SideMenuViewData) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.updateUserInformation(with: viewData.userAvatarViewData) self.updateBottomMenuItems(with: viewData) } private func updateUserInformation(with userAvatarViewData: UserAvatarViewData) { self.userIdLabel.text = userAvatarViewData.userId self.userDisplayNameLabel.text = userAvatarViewData.displayName self.userDisplayNameLabel.isHidden = userAvatarViewData.displayName.isEmptyOrNil self.userAvatarView.fill(with: userAvatarViewData) } private func updateBottomMenuItems(with viewData: SideMenuViewData) { self.menuItemsStackView.vc_removeAllSubviews() self.sideMenuActionViews = [] for sideMenuItem in viewData.sideMenuItems { let sideMenuActionView = SideMenuActionView.instantiate() sideMenuActionView.translatesAutoresizingMaskIntoConstraints = false let heightConstraint = sideMenuActionView.heightAnchor.constraint(equalToConstant: 0) heightConstraint.priority = .defaultLow heightConstraint.isActive = true sideMenuActionView.update(theme: self.theme) sideMenuActionView.fill(with: sideMenuItem) sideMenuActionView.delegate = self self.menuItemsStackView.addArrangedSubview(sideMenuActionView) sideMenuActionView.widthAnchor.constraint(equalTo: menuItemsStackView.widthAnchor).isActive = true self.sideMenuActionViews.append(sideMenuActionView) } if let appVersion = viewData.appVersion { let sideMenuVersionView = SideMenuVersionView.instantiate() sideMenuVersionView.translatesAutoresizingMaskIntoConstraints = false sideMenuVersionView.update(theme: self.theme) sideMenuVersionView.fill(with: appVersion) self.menuItemsStackView.addArrangedSubview(sideMenuVersionView) sideMenuVersionView.widthAnchor.constraint(equalTo: menuItemsStackView.widthAnchor).isActive = true self.sideMenuVersionView = sideMenuVersionView } } private func render(error: Error) { self.activityPresenter.removeCurrentActivityIndicator(animated: true) self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil) } // MARK: - Actions } // MARK: - SideMenuViewModelViewDelegate extension SideMenuViewController: SideMenuViewModelViewDelegate { func sideMenuViewModel(_ viewModel: SideMenuViewModelType, didUpdateViewState viewSate: SideMenuViewState) { self.render(viewState: viewSate) } } // MARK: - SideMenuActionViewDelegate extension SideMenuViewController: SideMenuActionViewDelegate { func sideMenuActionView(_ actionView: SideMenuActionView, didTapMenuItem sideMenuItem: SideMenuItem?) { guard let sideMenuItem = sideMenuItem else { return } self.viewModel.process(viewAction: .tap(menuItem: sideMenuItem, sourceView: actionView)) } }
35.116592
137
0.690206
649152cd2405ddc0c230edb4cbec28ac19941a82
1,273
// // PassCodeLSwiftDemoUITests.swift // PassCodeLSwiftDemoUITests // // Created by s-sakurai on 2017/04/07. // Copyright © 2017年 s-sakurai. All rights reserved. // import XCTest class PassCodeLSwiftDemoUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } 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() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.405405
182
0.670856
fe3508483cb27e31b78704b0058a276e8201575b
818
// // PTViewController.swift // SharePromote // // Created by Bavaria on 2018/5/2. // import UIKit class PTShareNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.view.transform = CGAffineTransform(translationX: 0, y: self.view.frame.size.height) UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions(rawValue: 7 << 16 | UIViewAnimationOptions.allowAnimatedContent.rawValue), animations: { self.view.transform = .identity }, completion: nil) } }
23.371429
172
0.650367
62f6d075c37a21494bdf4597bbc42fb57532c366
6,577
import XCTest @testable import RaytracerChallenge /// Feature: Tuples, Vectors, and Points class TestTuples: XCTestCase { /// A tuple with w=1.0 is a point func testPoint() { let a = Tuple(x: 4.3, y: -4.2, z: 3.1, w: 1) XCTAssertEqual(a.x, 4.3, accuracy: .epsilon) XCTAssertEqual(a.y, -4.2, accuracy: .epsilon) XCTAssertEqual(a.z, 3.1, accuracy: .epsilon) XCTAssertEqual(a.w, 1, accuracy: .epsilon) XCTAssertTrue(a.isPoint) XCTAssertFalse(a.isVector) } /// A tuple with w=0 is a vector func testVector() { let a = Tuple(x: 4.3, y: -4.2, z: 3.1, w: 0) XCTAssertEqual(a.x, 4.3, accuracy: .epsilon) XCTAssertEqual(a.y, -4.2, accuracy: .epsilon) XCTAssertEqual(a.z, 3.1, accuracy: .epsilon) XCTAssertEqual(a.w, 0, accuracy: .epsilon) XCTAssertFalse(a.isPoint) XCTAssertTrue(a.isVector) } /// Tuple.point() creates tuples with w=1 func testPointConstructor() { let p: Tuple = .point(x: 4, y: -4, z: 3) XCTAssertEqual(p, Tuple(x: 4, y: -4, z: 3, w: 1)) XCTAssertTrue(p.isPoint) XCTAssertFalse(p.isVector) } /// Tuple.vector() creates tuples with w=0 func testVectorConstructor() { let v: Tuple = .vector(x: 4, y: -4, z: 3) XCTAssertEqual(v, Tuple(x: 4, y: -4, z: 3, w: 0)) XCTAssertFalse(v.isPoint) XCTAssertTrue(v.isVector) } /// Adding two tuples func testAddingTuples() { let a1 = Tuple(x: 3, y: -2, z: 5, w: 1) let a2 = Tuple(x: -2, y: 3, z: 1, w: 0) XCTAssertEqual(a1 + a2, Tuple(x: 1, y: 1, z: 6, w: 1)) } /// Subtracting two points func testSubtractingPoints() { let p1 = Tuple.point(x: 3, y: 2, z: 1) let p2 = Tuple.point(x: 5, y: 6, z: 7) XCTAssertEqual(p1 - p2, .vector(x: -2, y: -4, z: -6)) } /// Subtracting a vector from a point func testSubtractingVectorFromPoint() { let p = Tuple.point(x: 3, y: 2, z: 1) let v = Tuple.vector(x: 5, y: 6, z: 7) XCTAssertEqual(p - v, .point(x: -2, y: -4, z: -6)) } /// Subtracting two vectors func testSubtractingVectors() { let v1 = Tuple.vector(x: 3, y: 2, z: 1) let v2 = Tuple.vector(x: 5, y: 6, z: 7) XCTAssertEqual(v1 - v2, .vector(x: -2, y: -4, z: -6)) } /// Subtracting a vector from the zero vector func testSubtractingFromZeroVector() { let v = Tuple.vector(x: 1, y: -2, z: 3) XCTAssertEqual(.zeroVector - v, .vector(x: -1, y: 2, z: -3)) } /// Negating a tuple func testNegatingTuple() { let a = Tuple(x: 1, y: -2, z: 3, w: -4) XCTAssertEqual(-a, Tuple(x: -1, y: 2, z: -3, w: 4)) XCTAssertEqual(-a, .zeroVector - a) } /// Multiplying a tuple by a scalar func testMultiplingTupleByScalar() { let a = Tuple(x: 1, y: -2, z: 3, w: -4) XCTAssertEqual(a * 3.5, Tuple(x: 3.5, y: -7, z: 10.5, w: -14)) } /// Multiplying a tuple by a fraction func testMultiplingTupleByFraction() { let a = Tuple(x: 1, y: -2, z: 3, w: -4) XCTAssertEqual(a * 0.5, Tuple(x: 0.5, y: -1, z: 1.5, w: -2)) } /// Dividing a tuple by a scalar func testDividingTupleByScalar() { let a = Tuple(x: 1, y: -2, z: 3, w: -4) XCTAssertEqual(a / 2, Tuple(x: 0.5, y: -1, z: 1.5, w: -2)) XCTAssertEqual(a / 2, a * 0.5) } /// Testing magnitude func testMagnitude() { XCTAssertEqual(Tuple.vector(x: 1, y: 0, z: 0).magnitude, 1) XCTAssertEqual(Tuple.vector(x: 0, y: 1, z: 0).magnitude, 1) XCTAssertEqual(Tuple.vector(x: 0, y: 1, z: 0).magnitude, 1) XCTAssertEqual(Tuple.vector(x: 1, y: 2, z: 3).magnitude, sqrt(14)) XCTAssertEqual(Tuple.vector(x: -1, y: -2, z: -3).magnitude, sqrt(14)) } /// Testing normalize func testNormalize() { XCTAssertEqual(Tuple.vector(x: 4, y: 0, z: 0).normalized, .vector(x: 1, y: 0, z: 0)) XCTAssertEqual(Tuple.vector(x: 4, y: 0, z: 0).normalized.magnitude, 1, accuracy: .epsilon) XCTAssertEqual(Tuple.vector(x: 1, y: 2, z: 3).normalized, .vector(x: 0.26726, y: 0.53452, z: 0.80178)) XCTAssertEqual(Tuple.vector(x: 1, y: 2, z: 3).normalized.magnitude, 1, accuracy: .epsilon) } /// The dot product of two tuples func testDot() { let a = Tuple.vector(x: 1, y: 2, z: 3) let b = Tuple.vector(x: 2, y: 3, z: 4) XCTAssertEqual(a.dot(b), 20) } /// The cross product of two vectors func testCross() { let a = Tuple.vector(x: 1, y: 2, z: 3) let b = Tuple.vector(x: 2, y: 3, z: 4) XCTAssertEqual(a.cross(b), .vector(x: -1, y: 2, z: -1)) XCTAssertEqual(b.cross(a), .vector(x: 1, y: -2, z: 1)) } /// Colors are (red, green, blue) tuples func testColor() { let c = Color(red: -0.5, green: 0.4, blue: 1.7) XCTAssertEqual(c.red, -0.5) XCTAssertEqual(c.green, 0.4) XCTAssertEqual(c.blue, 1.7) } /// Adding colors func testAddingColors() { let c1 = Color(red: 0.9, green: 0.6, blue: 0.75) let c2 = Color(red: 0.7, green: 0.1, blue: 0.25) XCTAssertEqual(c1 + c2, Color(red: 1.6, green: 0.7, blue: 1)) } /// Subtracting colors func testSubtractingColors() { let c1 = Color(red: 0.9, green: 0.6, blue: 0.75) let c2 = Color(red: 0.7, green: 0.1, blue: 0.25) XCTAssertEqual(c1 - c2, Color(red: 0.2, green: 0.5, blue: 0.5)) } /// Multiplying a color by a scalar func testMultiplyingColorByScalar() { let c = Color(red: 0.2, green: 0.3, blue: 0.4) XCTAssertEqual(c * 2, Color(red: 0.4, green: 0.6, blue: 0.8)) } /// Multiplying a color by a color func testMultiplyingColorByColor() { let c1 = Color(red: 1, green: 0.2, blue: 0.4) let c2 = Color(red: 0.9, green: 1, blue: 0.1) XCTAssertEqual(c1 * c2, Color(red: 0.9, green: 0.2, blue: 0.04)) } /// Reflecting a vector approaching at 45° func testReflectingVectorAt45() { let v = Tuple.vector(x: 1, y: -1, z: 0) let n = Tuple.vector(x: 0, y: 1, z: 0) XCTAssertEqual(v.reflect(n), .vector(x: 1, y: 1, z: 0)) } /// Reflecting a vector off a slanted surface func testReflectingVectorAtSlant() { let v = Tuple.vector(x: 0, y: -1, z: 0) let n = Tuple.vector(x: sqrt(2)/2, y: sqrt(2)/2, z: 0) XCTAssertEqual(v.reflect(n), .vector(x: 1, y: 0, z: 0)) } }
35.551351
110
0.552836
ddce92c337b475e081c33692ed4089718dceb958
616
// // CitiyCDEK.swift // PickpointDemo // // Created by Irina Romas on 27.04.2020. // Copyright © 2020 Irina Romas. All rights reserved. // import Foundation struct CityCDEK: Codable { let cityName: String let cityCode: String let cityUuid: String let country: String let countryCode: String let region: String let regionCode: String? let subRegion: String? let paymentLimit: Double let regionCodeExt: String? let latitude: Float? let longitude: Float? let kladr: String? let fiasGuid: String? let regionFiasGuid: String? let timezone: String? }
21.241379
54
0.680195
902706cfdc67200c37317d974673cd50576bb77c
16,634
// PagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit // MARK: Protocols public protocol IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo } public protocol PagerTabStripDelegate: class { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) } public protocol PagerTabStripIsProgressiveDelegate: PagerTabStripDelegate { func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) } public protocol PagerTabStripDataSource: class { func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] } // MARK: PagerTabStripViewController open class PagerTabStripViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak public var containerView: UIScrollView! open weak var delegate: PagerTabStripDelegate? open weak var datasource: PagerTabStripDataSource? open var pagerBehaviour = PagerTabStripBehaviour.progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) open private(set) var viewControllers = [UIViewController]() open private(set) var currentIndex = 0 open private(set) var preCurrentIndex = 0 // used *only* to store the index to which move when the pager becomes visible open var pageWidth: CGFloat { return containerView.bounds.width } open var scrollPercentage: CGFloat { if swipeDirection != .right { let module = fmod(containerView.contentOffset.x, pageWidth) return module == 0.0 ? 1.0 : module / pageWidth } return 1 - fmod(containerView.contentOffset.x >= 0 ? containerView.contentOffset.x : pageWidth + containerView.contentOffset.x, pageWidth) / pageWidth } open var swipeDirection: SwipeDirection { if containerView.contentOffset.x > lastContentOffset { return .left } else if containerView.contentOffset.x < lastContentOffset { return .right } return .none } override open func viewDidLoad() { super.viewDidLoad() let conteinerViewAux = containerView ?? { let containerView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height)) containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return containerView }() containerView = conteinerViewAux if containerView.superview == nil { view.addSubview(containerView) } containerView.bounces = true containerView.alwaysBounceHorizontal = true containerView.alwaysBounceVertical = false containerView.scrollsToTop = false containerView.delegate = self containerView.showsVerticalScrollIndicator = false containerView.showsHorizontalScrollIndicator = false containerView.isPagingEnabled = true reloadViewControllers() let childController = viewControllers[currentIndex] addChild(childController) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isViewAppearing = true children.forEach { $0.beginAppearanceTransition(true, animated: animated) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) lastSize = containerView.bounds.size updateIfNeeded() let needToUpdateCurrentChild = preCurrentIndex != currentIndex if needToUpdateCurrentChild { moveToViewController(at: preCurrentIndex) } isViewAppearing = false children.forEach { $0.endAppearanceTransition() } } open override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) children.forEach { $0.beginAppearanceTransition(false, animated: animated) } } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) children.forEach { $0.endAppearanceTransition() } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() updateIfNeeded() } open override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false } open func moveToViewController(at index: Int, animated: Bool = true) { guard isViewLoaded && view.window != nil && currentIndex != index else { preCurrentIndex = index return } if animated && pagerBehaviour.skipIntermediateViewControllers && abs(currentIndex - index) > 1 { var tmpViewControllers = viewControllers let currentChildVC = viewControllers[currentIndex] let fromIndex = currentIndex < index ? index - 1 : index + 1 let fromChildVC = viewControllers[fromIndex] tmpViewControllers[currentIndex] = fromChildVC tmpViewControllers[fromIndex] = currentChildVC pagerTabStripChildViewControllersForScrolling = tmpViewControllers containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: fromIndex), y: 0), animated: false) (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: true) } else { (navigationController?.view ?? view).isUserInteractionEnabled = !animated containerView.setContentOffset(CGPoint(x: pageOffsetForChild(at: index), y: 0), animated: animated) } } open func moveTo(viewController: UIViewController, animated: Bool = true) { moveToViewController(at: viewControllers.firstIndex(of: viewController)!, animated: animated) } // MARK: - PagerTabStripDataSource open func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { assertionFailure("Sub-class must implement the PagerTabStripDataSource viewControllers(for:) method") return [] } // MARK: - Helpers open func updateIfNeeded() { if isViewLoaded && !lastSize.equalTo(containerView.bounds.size) { updateContent() } } open func canMoveTo(index: Int) -> Bool { return currentIndex != index && viewControllers.count > index } open func pageOffsetForChild(at index: Int) -> CGFloat { return CGFloat(index) * containerView.bounds.width } open func offsetForChild(at index: Int) -> CGFloat { return (CGFloat(index) * containerView.bounds.width) + ((containerView.bounds.width - view.bounds.width) * 0.5) } open func offsetForChild(viewController: UIViewController) throws -> CGFloat { guard let index = viewControllers.firstIndex(of: viewController) else { throw PagerTabStripError.viewControllerOutOfBounds } return offsetForChild(at: index) } open func pageFor(contentOffset: CGFloat) -> Int { let result = virtualPageFor(contentOffset: contentOffset) return pageFor(virtualPage: result) } open func virtualPageFor(contentOffset: CGFloat) -> Int { return Int((contentOffset + 1.5 * pageWidth) / pageWidth) - 1 } open func pageFor(virtualPage: Int) -> Int { if virtualPage < 0 { return 0 } if virtualPage > viewControllers.count - 1 { return viewControllers.count - 1 } return virtualPage } open func updateContent() { if lastSize.width != containerView.bounds.size.width { lastSize = containerView.bounds.size containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) } lastSize = containerView.bounds.size let pagerViewControllers = pagerTabStripChildViewControllersForScrolling ?? viewControllers containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(pagerViewControllers.count), height: containerView.contentSize.height) for (index, childController) in pagerViewControllers.enumerated() { let pageOffsetForChild = self.pageOffsetForChild(at: index) if abs(containerView.contentOffset.x - pageOffsetForChild) < containerView.bounds.width { if childController.parent != nil { childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] } else { childController.beginAppearanceTransition(true, animated: false) addChild(childController) childController.view.frame = CGRect(x: offsetForChild(at: index), y: 0, width: view.bounds.width, height: containerView.bounds.height) childController.view.autoresizingMask = [.flexibleHeight, .flexibleWidth] containerView.addSubview(childController.view) childController.didMove(toParent: self) childController.endAppearanceTransition() } } else { if childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } } } let oldCurrentIndex = currentIndex let virtualPage = virtualPageFor(contentOffset: containerView.contentOffset.x) let newCurrentIndex = pageFor(virtualPage: virtualPage) currentIndex = newCurrentIndex preCurrentIndex = currentIndex let changeCurrentIndex = newCurrentIndex != oldCurrentIndex if let progressiveDelegate = self as? PagerTabStripIsProgressiveDelegate, pagerBehaviour.isProgressiveIndicator { let (fromIndex, toIndex, scrollPercentage) = progressiveIndicatorData(virtualPage) progressiveDelegate.updateIndicator(for: self, fromIndex: fromIndex, toIndex: toIndex, withProgressPercentage: scrollPercentage, indexWasChanged: changeCurrentIndex) } else { delegate?.updateIndicator(for: self, fromIndex: min(oldCurrentIndex, pagerViewControllers.count - 1), toIndex: newCurrentIndex) } } open func reloadPagerTabStripView() { guard isViewLoaded else { return } for childController in viewControllers where childController.parent != nil { childController.beginAppearanceTransition(false, animated: false) childController.willMove(toParent: nil) childController.view.removeFromSuperview() childController.removeFromParent() childController.endAppearanceTransition() } reloadViewControllers() containerView.contentSize = CGSize(width: containerView.bounds.width * CGFloat(viewControllers.count), height: containerView.contentSize.height) if currentIndex >= viewControllers.count { currentIndex = viewControllers.count - 1 } preCurrentIndex = currentIndex containerView.contentOffset = CGPoint(x: pageOffsetForChild(at: currentIndex), y: 0) updateContent() } // MARK: - UIScrollViewDelegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { if containerView == scrollView { updateContent() lastContentOffset = scrollView.contentOffset.x } } open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if containerView == scrollView { lastPageNumber = pageFor(contentOffset: scrollView.contentOffset.x) } } open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if containerView == scrollView { pagerTabStripChildViewControllersForScrolling = nil (navigationController?.view ?? view).isUserInteractionEnabled = true updateContent() } } // MARK: - Orientation open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) isViewRotating = true pageBeforeRotate = currentIndex coordinator.animate(alongsideTransition: nil) { [weak self] _ in guard let me = self else { return } me.isViewRotating = false me.currentIndex = me.pageBeforeRotate me.preCurrentIndex = me.currentIndex me.updateIfNeeded() } } // MARK: Private private func progressiveIndicatorData(_ virtualPage: Int) -> (Int, Int, CGFloat) { let count = viewControllers.count var fromIndex = currentIndex var toIndex = currentIndex let direction = swipeDirection if direction == .left { if virtualPage > count - 1 { fromIndex = count - 1 toIndex = count } else { if self.scrollPercentage >= 0.5 { fromIndex = max(toIndex - 1, 0) } else { toIndex = fromIndex + 1 } } } else if direction == .right { if virtualPage < 0 { fromIndex = 0 toIndex = -1 } else { if self.scrollPercentage > 0.5 { fromIndex = min(toIndex + 1, count - 1) } else { toIndex = fromIndex - 1 } } } let scrollPercentage = pagerBehaviour.isElasticIndicatorLimit ? self.scrollPercentage : ((toIndex < 0 || toIndex >= count) ? 0.0 : self.scrollPercentage) return (fromIndex, toIndex, scrollPercentage) } private func reloadViewControllers() { guard let dataSource = datasource else { fatalError("dataSource must not be nil") } viewControllers = dataSource.viewControllers(for: self) // viewControllers guard !viewControllers.isEmpty else { fatalError("viewControllers(for:) should provide at least one child view controller") } viewControllers.forEach { if !($0 is IndicatorInfoProvider) { fatalError("Every view controller provided by PagerTabStripDataSource's viewControllers(for:) method must conform to IndicatorInfoProvider") }} } private var pagerTabStripChildViewControllersForScrolling: [UIViewController]? private var lastPageNumber = 0 private var lastContentOffset: CGFloat = 0.0 private var pageBeforeRotate = 0 private var lastSize = CGSize(width: 0, height: 0) internal var isViewRotating = false internal var isViewAppearing = false }
41.79397
213
0.673741
e5508cad98443d027e9b6e120e19e87bcd4a5cac
761
import UIKit import XCTest import NetworkBase 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.366667
111
0.605782
ac9224b4a64daca84133a1d4f6c93e3f0c6aca18
618
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "Guard-iOS-WeCom", defaultLocalization: "en", platforms: [ .macOS(.v10_14), .iOS(.v10), .tvOS(.v13) ], products: [ .library( name: "WeCom", targets: ["WeCom"]) ], dependencies: [ ], targets: [ .binaryTarget( name: "WeCom", url: "https://github.com/Authing/guard-ios-wecom/releases/download/1.0.0/WeCom.xcframework.zip", checksum: "a73c2d0ac24529c5e1e894644c49ec62f47b3e45459088a35244643e6122ca9a" ) ] )
24.72
108
0.572816
f41dc665b7a57a1740383910351c4119138f82a2
6,429
// // ProfileViewController.swift // twitter // // Created by Gerardo Parra on 7/3/17. // Copyright © 2017 Charles Hieger. All rights reserved. // import UIKit class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var coverImage: UIImageView! @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var iconBorder: UIView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var followingCount: UILabel! @IBOutlet weak var followerCount: UILabel! @IBOutlet weak var verifiedImage: UIImageView! @IBOutlet weak var followersLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var logOutButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var followingButton: UIButton! var tweets: [Tweet] = [] var user: User? = nil var fromTimeline: Bool = false override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 130 // Toggle views based on user if !fromTimeline { user = User.current } logOutButton.isHidden = fromTimeline followingButton.isHidden = !fromTimeline // Format log out, following buttons logOutButton.layer.borderWidth = 1 logOutButton.layer.borderColor = logOutButton.currentTitleColor.cgColor logOutButton.layer.cornerRadius = logOutButton.frame.height / 2 if (user?.isFollowing)! { followingButton.backgroundColor = logOutButton.currentTitleColor followingButton.setTitleColor(UIColor.white, for: .normal) } else if user?.screenName == User.current?.screenName { followingButton.isHidden = true } else { followingButton.layer.borderWidth = 1 followingButton.layer.borderColor = logOutButton.currentTitleColor.cgColor followingButton.setTitle("Follow", for: .normal) } followingButton.layer.cornerRadius = followingButton.frame.height / 2 // Format images iconBorder.layer.cornerRadius = iconBorder.frame.width / 2 iconImage.layer.cornerRadius = iconImage.frame.width / 2 // Change close button tint let origImage = UIImage(named: "close-icon") let tintedImage = origImage?.withRenderingMode(.alwaysTemplate) closeButton.setImage(tintedImage, for: .normal) closeButton.tintColor = UIColor.white closeButton.isHidden = !logOutButton.isHidden // Set profile data iconImage.af_setImage(withURL: (user?.iconURL)!) coverImage.af_setImage(withURL: (user?.coverURL)!) nameLabel.text = user?.name let username = user?.screenName! screenNameLabel.text = "@\(username!)" locationLabel.text = user?.location // Add commas to large follower numbers let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal let formattedFollowers = numberFormatter.string(from: NSNumber(value: (user?.followers)!))! let formattedFollowing = numberFormatter.string(from: NSNumber(value: (user?.following)!))! followingCount.text = String(formattedFollowing) followerCount.text = String(formattedFollowers) // Proper number grammar if user?.followers! == 1 { followersLabel.text = "Follower" } // Verified icon if (user?.verified)! { verifiedImage.isHidden = false } // Fetch tweets APIManager.shared.getUserTimeLine(with: (user?.screenName)!) { (tweets, error) in if let tweets = tweets { self.tweets = tweets self.tableView.reloadData() } else if let error = error { print("Error getting home timeline: " + error.localizedDescription) } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tweets.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileCell", for: indexPath) as! TweetCell cell.tweet = tweets[indexPath.row] cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsets.zero cell.layoutMargins = UIEdgeInsets.zero return cell } @IBAction func didTapFollowing(_ sender: Any) { if followingButton.currentTitle == "Follow" { followingButton.backgroundColor = logOutButton.currentTitleColor followingButton.setTitleColor(UIColor.white, for: .normal) followingButton.setTitle("Following", for: .normal) } else { followingButton.layer.borderWidth = 1 followingButton.layer.borderColor = logOutButton.currentTitleColor.cgColor let titleColor = followingButton.layer.borderColor followingButton.setTitleColor(UIColor(cgColor: titleColor!), for: .normal) followingButton.layer.backgroundColor = UIColor.clear.cgColor followingButton.setTitle("Follow", for: .normal) } } @IBAction func didTapLogout(_ sender: Any) { APIManager.shared.logout() } @IBAction func didTapClose(_ sender: Any) { dismiss(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.817647
109
0.653912
f7ca847cdc5026a81fec7f18f3f8899ace041b90
635
// // TestView.swift // UITests // // Created by Ramon Haro Marques // import UIKit @testable import UI class TestView: UIView { //MARK: - Properties private (set) lazy var loadingIndicator: UIActivityIndicatorView = { return UIActivityIndicatorView() }() //MARK: - Constructor init() { super.init(frame: .zero) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - ReusableView implementation extension TestView: ReusableView {} //MARK: - LoaderDisplayable implementation extension TestView: LoaderDisplayable {}
18.676471
72
0.659843
33564cf6305629ad69eb8eaae7b0ee5195868b29
603
// // KeyComboTests.swift // HotKeyTests // // Created by Sam Soffes on 7/21/17. // Copyright © 2017 Sam Soffes. All rights reserved. // import XCTest import HotKey final class KeyComboTests: XCTestCase { func testSerialization() { let keyCombo = KeyCombo(key: .c, modifiers: .command) let dictionary = keyCombo.dictionary XCTAssertEqual(8, dictionary["keyCode"] as! Int) XCTAssertEqual(256, dictionary["modifiers"] as! Int) let keyCombo2 = KeyCombo(dictionary: dictionary)! XCTAssertEqual(keyCombo.key, keyCombo2.key) XCTAssertEqual(keyCombo.modifiers, keyCombo2.modifiers) } }
24.12
57
0.737977
11ecfcd24c7850c3cdfa3d4c84349c98d53e70d0
552
// // ImportedPlaylist.swift // Aural // // Copyright © 2021 Kartik Venugopal. All rights reserved. // // This software is licensed under the MIT software license. // See the file "LICENSE" in the project root directory for license terms. // import Foundation /// /// A temporary container for a playlist constructed from an imported playlist file. /// struct ImportedPlaylist { // The filesystem location of the playlist file referenced by this object let file: URL // URLs of tracks in this playlist let tracks: [URL] }
24
84
0.706522
08642b7018e1481f711ecc6c0cbb325904371d83
46,230
// // Record.swift // kintone-ios-sdkTests // // Created by t000572 on 2018/10/01. // Copyright © 2018年 Cybozu. All rights reserved. // import XCTest @testable import kintone_ios_sdk @testable import Promises class RecordTest: XCTestCase { private let testUser1 = Member("user1", "user1") private let testUser2 = Member("user2", "user2") private let testOrg1 = Member("test", "テスト組織") private let testOrg2 = Member("検証組織", "検証組織") private let testGroup1 = Member("TeamA", "チームA") private let testGroup2 = Member("TeamB", "チームB") private let testAdmin = Member("cybozu", "cybozu") private var recordManagement: Record? override func setUp() { super.setUp() // set auth var auth = Auth() auth = auth.setPasswordAuth(TestsConstants.ADMIN_USERNAME, TestsConstants.ADMIN_PASSWORD) let certPassword = TestsConstants.CERT_PASSWORD let testBundle = Bundle(for: type(of: self)) let pathURLString = testBundle.url(forResource: TestsConstants.CERT_NAME, withExtension: TestsConstants.CERT_EXTENSION) auth.setClientCertByPath(pathURLString!.absoluteString, certPassword) let conn = Connection(TestsConstants.DOMAIN, auth, -1) // instance of Record class self.recordManagement = Record(conn) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func getErrorMessage(_ error: Any) -> String { if error is KintoneAPIException { return (error as! KintoneAPIException).toString()! } else { return (error as! Error).localizedDescription } } func testGetRecord() throws { // create test data for get record var testData: Dictionary<String, FieldValue> = createAddData() testData = addData(testData, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordSuccess") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, testData).then{addResponse -> Promise<GetRecordResponse> in let recNum = addResponse.getId() return (self.recordManagement?.getRecord(RecordTestConstants.APP_ID, recNum!))! }.then{ getResponse in let resultData: Dictionary<String, FieldValue> = getResponse.getRecord()! // check result for (code, value) in resultData { let resultFieldType = value.getType() let resultFieldValue = value.getValue() let testDataValue = testData[code]?.getValue() ?? "" // check exec result self.checkResult(resultFieldType!, resultFieldValue as Any, testDataValue as Any) } }.catch{ error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testGetRecords() throws { // create test data for get record var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() var testData3: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecords1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecords2") testData3 = addData(testData3, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecords3") var testDatas = [testData1, testData2, testData3] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDatas).then{addResponse -> Promise<GetRecordsResponse> in let recIds = addResponse.getIDs() var idsString = "(" for id in recIds! { if idsString == "(" { idsString += String(id) } else { idsString += "," + String(id) } } let query = "$id in " + idsString + ")" + " order by $id asc" print(query) return (self.recordManagement?.getRecords(RecordTestConstants.APP_ID, query, nil, true))! }.then{ getResponse in let resultData = getResponse.getRecords()! // check result for (i, dval) in (resultData.enumerated()) { for (code, value) in dval { let resultFieldType = value.getType() let resultFieldValue = value.getValue() let testDataValue = testDatas[i][code]?.getValue() ?? "" self.checkResult(resultFieldType!, resultFieldValue as Any, testDataValue as Any) } } }.catch{ error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testGetRecordsWithoutApp() throws { // exec get record test self.recordManagement?.getRecords(99999999, nil, nil, true).then{_ in XCTFail(self.getErrorMessage("CAN GET UNEXIST APP")) }.catch{ error in XCTAssertTrue(true) } XCTAssert(waitForPromises(timeout: 10)) } func testGetRecordsWithQuery() throws { // create test data for get record var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() var testData3: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithQuery1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithQuery2") testData3 = addData(testData3, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithQuery3") var testDatas = [testData1, testData2, testData3] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDatas).then{ addResponse -> Promise<GetRecordsResponse> in let recIds = addResponse.getIDs() let query = "$id >= " + recIds![0].description + " order by $id asc" return (self.recordManagement?.getRecords(RecordTestConstants.APP_ID, query, nil, true))! }.then{response in let resultData = response.getRecords() // check result for (i, dval) in (resultData!.enumerated()) { for (code, value) in dval { let resultFieldType = value.getType() let resultFieldValue = value.getValue() let testDataValue = testDatas[i][code]?.getValue() ?? "" self.checkResult(resultFieldType!, resultFieldValue as Any, testDataValue as Any) } } }.catch{ error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 10)) } func testGetAllRecordsByCursorSuccess() { let fields = ["SINGLE_LINE_TEXT", "DROP_DOWN"] // create test data for get record var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() var testData3: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields2") testData3 = addData(testData3, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields3") let testDatas = [testData1, testData2, testData3] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDatas).then{addResponse -> Promise<GetRecordsResponse> in let query = " order by Record_number asc" return (self.recordManagement?.getAllRecordsByCursor(RecordTestConstants.APP_ID, query, fields))! }.then{response in let resultData = response.getRecords() // check result XCTAssert((resultData?.count)! >= 3) }.catch{ error in print(self.getErrorMessage(error)) XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 50)) } func testGetRecordsWithFields() throws { let fields = ["SINGLE_LINE_TEXT", "DROP_DOWN"] // create test data for get record var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() var testData3: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields2") testData3 = addData(testData3, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithFields3") var testDatas = [testData1, testData2, testData3] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDatas).then{addResponse -> Promise<GetRecordsResponse> in let recIds = addResponse.getIDs() let query = "NUMBER >= 5 and Record_number >= " + recIds![0].description + " order by Record_number asc" return (self.recordManagement?.getRecords(RecordTestConstants.APP_ID, query, fields, true))! }.then{response in let resultData = response.getRecords() // check result for (i, dval) in (resultData?.enumerated())! { XCTAssertEqual(2, dval.count) for (code, value) in dval { let resultFieldType = value.getType() let resultFieldValue = value.getValue() let testDataValue = testDatas[i][code]?.getValue() self.checkResult(resultFieldType!, resultFieldValue as Any, testDataValue as Any) } } }.catch{ error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 50)) } func testGetRecordsWithoutTotal() throws { // create test data for get record var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() var testData3: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithoutTotal1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithoutTotal2") testData3 = addData(testData3, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testGetRecordsWithoutTotal3") var testDatas = [testData1, testData2, testData3] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDatas) .then{addResponse -> Promise<GetRecordsResponse> in let recIds = addResponse.getIDs() let query = "Record_number >= " + recIds![0].description + " order by Record_number asc" return (self.recordManagement?.getRecords(RecordTestConstants.APP_ID, query, nil, nil))! }.then{response in let resultData = response.getRecords() // check result XCTAssertNil(response.getTotalCount()) for (i, dval) in (resultData?.enumerated())! { for (code, value) in dval { let resultFieldType = value.getType() let resultFieldValue = value.getValue() let testDataValue = testDatas[i][code]?.getValue() self.checkResult(resultFieldType!, resultFieldValue as Any, testDataValue as Any) } } }.catch{ error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 20)) } func testAddRecord() throws { // create test data for add var testData: Dictionary<String, FieldValue> = createAddData() testData = addData(testData, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testAddRecord") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, testData).then{response in XCTAssertNotNil(response.getId()) XCTAssertNotNil(response.getRevision()) }.catch {error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 10)) } func testAddRecordWithoutRecord() throws { self.recordManagement?.addRecord(RecordTestConstants.APP_ID, nil).then{response in XCTAssertNotNil(response.getId()) XCTAssertNotNil(response.getRevision()) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testAddRecords() throws { // create test data for addRecords var testData1: Dictionary<String, FieldValue> = createAddData() var testData2: Dictionary<String, FieldValue> = createAddData() testData1 = addData(testData1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testAddRecordsS1") testData2 = addData(testData2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testAddRecords2") let testDataList = [testData1, testData2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, testDataList).then{response in XCTAssertEqual(2, response.getIDs()?.count) XCTAssertEqual(2, response.getRevisions()?.count) XCTAssertNotNil(response.getIDs()![0]) XCTAssertNotNil(response.getIDs()![1]) XCTAssertNotNil(response.getRevisions()![0]) XCTAssertNotNil(response.getRevisions()![1]) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordById() throws { // create test data for update var updRecord = createAddData() self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updRecord).then{addResponse in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() updRecord = self.addData(updRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testUpdateRecordById") self.recordManagement?.updateRecordByID(RecordTestConstants.APP_ID, updRecNum!, updRecord, updRevision).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordByIdWithoutRevision() throws { // create test data for update var updRecord = createAddData() self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updRecord).then{addResponse in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() updRecord = self.addData(updRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordByIdWithoutRevision") self.recordManagement?.updateRecordByID(RecordTestConstants.APP_ID, updRecNum!, updRecord, nil).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordByIdWithoutRecord() throws { // create test data for update var updRecord = createAddData() self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updRecord).then{addResponse in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() updRecord = self.addData(updRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordByIdWithoutRecord") self.recordManagement?.updateRecordByID(RecordTestConstants.APP_ID, updRecNum!, nil, nil).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordByUpdateKey() throws { // create unique key let now = NSDate() let formatter = DateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let uniquekey = formatter.string(from: now as Date) + (Int(arc4random_uniform(1000000) + 1)).description // create test data for update var addRecord = createAddData() addRecord = addData(addRecord, "UPDATE_KEY", FieldType.SINGLE_LINE_TEXT, uniquekey) self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addRecord).then{addResponse in let updRevision = addResponse.getRevision() let updKey: RecordUpdateKey = RecordUpdateKey("UPDATE_KEY", uniquekey) var updRecord: Dictionary<String, FieldValue> = [:] updRecord = self.addData(updRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordByUpdateKey") self.recordManagement?.updateRecordByUpdateKey(RecordTestConstants.APP_ID, updKey, updRecord, nil).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordByUpdateKeyWithoutRecord() throws { // create unique key let now = NSDate() let formatter = DateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let uniquekey = formatter.string(from: now as Date) + (Int(arc4random_uniform(1000000) + 1)).description // create test data for update var addRecord = createAddData() addRecord = addData(addRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordByUpdateKeyWithoutRecord") addRecord = addData(addRecord, "UPDATE_KEY", FieldType.SINGLE_LINE_TEXT, uniquekey) self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addRecord).then{addResponse in let updRevision = addResponse.getRevision() let updKey: RecordUpdateKey = RecordUpdateKey("UPDATE_KEY", uniquekey) self.recordManagement?.updateRecordByUpdateKey(RecordTestConstants.APP_ID, updKey, nil, nil).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecords() throws { // create test data for update var addRecord1 = createAddData() var addRecord2 = createAddData() let addRecordList = [addRecord1, addRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, addRecordList).then{addResponse in // update data addRecord1 = self.addData(addRecord1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testUpdateRecords1") addRecord2 = self.addData(addRecord2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "testUpdateRecords2") let updItem1: RecordUpdateItem = RecordUpdateItem(addResponse.getIDs()?[0], nil, nil, addRecord1) let updItem2: RecordUpdateItem = RecordUpdateItem(addResponse.getIDs()?[1], nil, nil, addRecord2) let updItemList = [updItem1, updItem2] self.recordManagement?.updateRecords(RecordTestConstants.APP_ID, updItemList).then{response in XCTAssertEqual(2, response.getRecords()?.count) XCTAssertEqual((response.getRecords()![0]).getID(), addResponse.getIDs()![0]) XCTAssertEqual((response.getRecords()![1]).getID(), addResponse.getIDs()![1]) XCTAssertEqual((response.getRecords()![0]).getRevision(), addResponse.getRevisions()![0]+1) XCTAssertEqual((response.getRecords()![1]).getRevision(), addResponse.getRevisions()![1]+1) } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testDeleteRecords() throws { // create test data for delete let delRecord1 = createAddData() let delRecord2 = createAddData() let delRecordList = [delRecord1, delRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, delRecordList).then{addResponse -> Promise<Void> in let delId = [addResponse.getIDs()![0], addResponse.getIDs()![1]] return (self.recordManagement?.deleteRecords(RecordTestConstants.APP_ID, delId))! }.then{ XCTAssertTrue(true) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 50)) } func testDeleteRecordsWithRevision() throws { // create test data for delete let delRecord1 = createAddData() let delRecord2 = createAddData() let delRecordList = [delRecord1, delRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, delRecordList).then{addResponse in var delIdAndRevision: Dictionary<Int, Int> = [:] delIdAndRevision[addResponse.getIDs()![0]] = addResponse.getRevisions()![0] delIdAndRevision[addResponse.getIDs()![1]] = addResponse.getRevisions()![1] return (self.recordManagement?.deleteRecordsWithRevision(RecordTestConstants.APP_ID, delIdAndRevision))! }.then{ XCTAssertTrue(true) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testDeleteRecordsWithRevisionWithoutRevision() throws { // create test data for delete var delRecord1 = createAddData() var delRecord2 = createAddData() delRecord1 = addData(delRecord1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testDeleteRecordsWithRevisionWithoutRevision1") delRecord2 = addData(delRecord2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testDeleteRecordsWithRevisionWithoutRevision2") let delRecordList = [delRecord1, delRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, delRecordList).then{addResponse -> Promise<Void> in var delIdAndRevision: Dictionary<Int, Int> = [:] delIdAndRevision[(addResponse.getIDs()![0])] = -1 delIdAndRevision[addResponse.getIDs()![1]] = -1 return (self.recordManagement?.deleteRecordsWithRevision(RecordTestConstants.APP_ID, delIdAndRevision))! }.then { XCTAssertTrue(true) }.catch{error in XCTFail() } XCTAssert(waitForPromises(timeout: 50)) } func testUpdateRecordAssignees() throws { // create test data for update assignees var updAssigneesRecord = createAddData() updAssigneesRecord = addData(updAssigneesRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordAssignees") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updAssigneesRecord).then{addResponse -> Promise<UpdateRecordResponse> in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() let assignees: Array<String> = [self.testUser1.code!] return (self.recordManagement?.updateRecordAssignees(RecordTestConstants.APP_ID, updRecNum!, assignees, updRevision).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordAssigneesWithoutRevision() throws { // create test data for update assignee var updAssigneesRecord = createAddData() updAssigneesRecord = addData(updAssigneesRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordAssigneesWithoutRevision") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updAssigneesRecord).then{addResponse -> Promise<UpdateRecordResponse> in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() let assignees: Array<String> = [self.testUser1.code!] return (self.recordManagement?.updateRecordAssignees(RecordTestConstants.APP_ID, updRecNum!, assignees, nil).then{response in XCTAssertEqual(updRevision!+1, response.getRevision()) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordStatus() throws { // create test data for update status var updStatusRecord = createAddData() updStatusRecord = addData(updStatusRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordStatus") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updStatusRecord).then{addResponse -> Promise<UpdateRecordResponse> in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() let assignee = self.testUser1.code let status = "処理開始" return (self.recordManagement?.updateRecordStatus(RecordTestConstants.APP_ID, updRecNum!, status, assignee, updRevision).then{response in XCTAssertEqual(updRevision!+2, response.getRevision()) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordStatusWithoutRevision() throws { // create test data for update status var updStatusRecord = createAddData() updStatusRecord = addData(updStatusRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordStatusWithoutRevision") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updStatusRecord).then{addResponse -> Promise<UpdateRecordResponse> in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() let assignee = self.testUser2.code let status = "処理開始" return (self.recordManagement?.updateRecordStatus(RecordTestConstants.APP_ID, updRecNum!, status, assignee, nil).then{response in XCTAssertEqual(updRevision!+2, response.getRevision()) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordStatusWithoutAssignee() throws { // create test data for update status var updStatusRecord = createAddData() updStatusRecord = addData(updStatusRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordStatusWithoutAssignee") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, updStatusRecord).then{addResponse -> Promise<UpdateRecordResponse> in let updRecNum = addResponse.getId() let updRevision = addResponse.getRevision() let status = "処理開始" return (self.recordManagement?.updateRecordStatus(RecordTestConstants.APP_ID, updRecNum!, status, nil, updRevision))! }.then{_ in XCTFail(self.getErrorMessage("Can Add Record Without Assignee")) }.catch{error in XCTAssertTrue(true) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordsStatus() throws { // create test data for update status var updStatusRecord1 = createAddData() var updStatusRecord2 = createAddData() updStatusRecord1 = addData(updStatusRecord1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordsStatus1") updStatusRecord2 = addData(updStatusRecord2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordsStatus2") let updsStatus = [updStatusRecord1, updStatusRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, updsStatus).then{addResponse -> Promise<UpdateRecordsResponse> in let id1 = addResponse.getIDs()![0] let id2 = addResponse.getIDs()![1] let revision1 = addResponse.getRevisions()![0] let revision2 = addResponse.getRevisions()![1] let item1: RecordUpdateStatusItem = RecordUpdateStatusItem("処理開始", self.testUser1.code, id1, revision1) let item2: RecordUpdateStatusItem = RecordUpdateStatusItem("処理開始", self.testUser2.code, id2, revision2) let itemList = [item1, item2] return (self.recordManagement?.updateRecordsStatus(RecordTestConstants.APP_ID, itemList).then{response in XCTAssertEqual(2, response.getRecords()?.count) XCTAssertEqual((response.getRecords()![0]).getID(), addResponse.getIDs()![0]) XCTAssertEqual((response.getRecords()![1]).getID(), addResponse.getIDs()![1]) XCTAssertEqual((response.getRecords()![0]).getRevision(), addResponse.getRevisions()![0]+2) XCTAssertEqual((response.getRecords()![1]).getRevision(), addResponse.getRevisions()![1]+2) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testUpdateRecordsStatusWithoutReivision() throws { // create test data for update status var updStatusRecord1 = createAddData() var updStatusRecord2 = createAddData() updStatusRecord1 = addData(updStatusRecord1, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordsStatusWithoutReivision1") updStatusRecord2 = addData(updStatusRecord2, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testUpdateRecordsStatusWithoutReivision2") let updsStatus = [updStatusRecord1, updStatusRecord2] self.recordManagement?.addRecords(RecordTestConstants.APP_ID, updsStatus).then{addResponse -> Promise<UpdateRecordsResponse> in let id1 = addResponse.getIDs()![0] let id2 = addResponse.getIDs()![1] let item1: RecordUpdateStatusItem = RecordUpdateStatusItem("処理開始", self.testUser1.code, id1, nil) let item2: RecordUpdateStatusItem = RecordUpdateStatusItem("処理開始", self.testUser2.code, id2, nil) let itemList = [item1, item2] return (self.recordManagement?.updateRecordsStatus(RecordTestConstants.APP_ID, itemList).then{response in XCTAssertEqual(2, response.getRecords()?.count) XCTAssertEqual((response.getRecords()![0]).getID(), addResponse.getIDs()![0]) XCTAssertEqual((response.getRecords()![1]).getID(), addResponse.getIDs()![1]) XCTAssertEqual((response.getRecords()![0]).getRevision(), addResponse.getRevisions()![0]+2) XCTAssertEqual((response.getRecords()![1]).getRevision(), addResponse.getRevisions()![1]+2) })! }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testAddComment() throws { // create test data for add comment var addCommentRecord = createAddData() addCommentRecord = addData(addCommentRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testAddComment") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addCommentRecord).then{addResponse -> Promise<AddCommentResponse> in let updRecNum = addResponse.getId() let mention = CommentMention() let comment = CommentContent() mention.setCode(self.testUser1.code!) mention.setType("USER") let mentionList = [mention] comment.setText("add comment test") comment.setMentions(mentionList) return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{response in XCTAssertNotNil(response.getId()) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testAddCommentWithoutMention() throws { // create test data for add comment var addCommentRecord = createAddData() addCommentRecord = addData(addCommentRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testAddCommentWithoutMention") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addCommentRecord).then{addResponse -> Promise<AddCommentResponse> in let updRecNum = addResponse.getId() let comment = CommentContent() comment.setText("add comment without mention test") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{response in XCTAssertNotNil(response.getId()) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testGetComments() throws { // create test data for get comments var addCommentRecord = createAddData() addCommentRecord = addData(addCommentRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testGetComments") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addCommentRecord).then{addResponse in let updRecNum = addResponse.getId() let mention = CommentMention() let comment = CommentContent() mention.setCode(self.testUser1.code!) mention.setType("USER") let mentionList = [mention] comment.setText("add comment test1") comment.setMentions(mentionList) self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment).then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test2") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test3") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test4") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then { _ in return self.recordManagement?.getComments(RecordTestConstants.APP_ID, updRecNum!, "asc", 1, 2).then{response in XCTAssertEqual(2, response.getComments()?.count) XCTAssertNotNil(response.getComments()![0].getId()) XCTAssertNotNil(response.getComments()![1].getId()) XCTAssertNotNil(response.getComments()![0].getCreatedAt()) XCTAssertNotNil(response.getComments()![1].getCreatedAt()) XCTAssertEqual(self.testUser1.name! + " \nadd comment test2 ", response.getComments()![0].getText()) XCTAssertEqual(self.testUser1.name! + " \nadd comment test3 ", response.getComments()![1].getText()) XCTAssertEqual(self.testAdmin.code, response.getComments()![0].getCreator()?.code) XCTAssertEqual(self.testAdmin.code, response.getComments()![1].getCreator()?.code) XCTAssertEqual(mention.getCode(), response.getComments()![0].getMentions()![0].getCode()) XCTAssertEqual(mention.getCode(), response.getComments()![1].getMentions()![0].getCode()) }.catch{error in XCTFail(self.getErrorMessage(error)) } } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testGetCommentsWithoutOption() throws { // create test data for get comments var addCommentRecord = createAddData() addCommentRecord = addData(addCommentRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testGetCommentsWithoutOption") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, addCommentRecord).then{addResponse in let updRecNum = addResponse.getId() let mention = CommentMention() let comment = CommentContent() mention.setCode(self.testUser1.code!) mention.setType("USER") let mentionList = [mention] comment.setText("add comment test1") comment.setMentions(mentionList) self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment).then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test2") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test3") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then{_ -> Promise<AddCommentResponse> in comment.setText("add comment test4") return (self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment))! }.then { _ in return self.recordManagement?.getComments(RecordTestConstants.APP_ID, updRecNum!, nil, nil, nil).then{response in XCTAssertEqual(4, response.getComments()?.count) XCTAssertNotNil(response.getComments()![0].getId()) XCTAssertNotNil(response.getComments()![0].getCreatedAt()) XCTAssertEqual(self.testUser1.name! + " \nadd comment test4 ", response.getComments()![0].getText()) XCTAssertEqual(self.testAdmin.code, response.getComments()![0].getCreator()?.code) XCTAssertEqual(mention.getCode(), response.getComments()![0].getMentions()![0].getCode()) } } }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testDeleteComment() throws { // create test data for delete comment var delCommentRecord = createAddData() delCommentRecord = addData(delCommentRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, " testDeleteComment") self.recordManagement?.addRecord(RecordTestConstants.APP_ID, delCommentRecord).then{addResponse in let updRecNum = addResponse.getId() let mention = CommentMention() let comment = CommentContent() mention.setCode(self.testUser1.code!) mention.setType("USER") let mentionList = [mention] comment.setText("delete comment test") comment.setMentions(mentionList) return ((self.recordManagement?.addComment(RecordTestConstants.APP_ID, updRecNum!, comment) .then{addComResponse -> Promise<Void> in return (self.recordManagement?.deleteComment(RecordTestConstants.APP_ID, updRecNum!, addComResponse.getId()!))! })!) }.then{ XCTAssertTrue(true) }.catch{error in XCTFail(self.getErrorMessage(error)) } XCTAssert(waitForPromises(timeout: 5)) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } private func createAddData() -> Dictionary<String, FieldValue> { var testRecord: Dictionary<String, FieldValue> = [:] // text type testRecord = addData(testRecord, "SINGLE_LINE_TEXT", FieldType.SINGLE_LINE_TEXT, "single line text add data") testRecord = addData(testRecord, "UPDATE_KEY", FieldType.SINGLE_LINE_TEXT, "") testRecord = addData(testRecord, "MULTI_LINE_TEXT", FieldType.MULTI_LINE_TEXT, "multi line text add data1\nmulti line text add data2") testRecord = addData(testRecord, "RICH_TEXT", FieldType.RICH_TEXT, "<div><strong>rich text test add</strong></div>") let uniqunum = arc4random() % 10 testRecord = addData(testRecord, "NUMBER", FieldType.NUMBER, uniqunum.description) // select type let selectMultiData = ["sample1", "sample2"] testRecord = addData(testRecord, "RADIO_BUTTON", FieldType.RADIO_BUTTON, "sample1") testRecord = addData(testRecord, "CHECK_BOX", FieldType.CHECK_BOX, selectMultiData) testRecord = addData(testRecord, "MULTI_SELECT", FieldType.MULTI_SELECT, selectMultiData) testRecord = addData(testRecord, "DROP_DOWN", FieldType.DROP_DOWN, "sample2") testRecord = addData(testRecord, "DATE", FieldType.DATE, "2019-01-01") testRecord = addData(testRecord, "TIME", FieldType.TIME, "08:14") testRecord = addData(testRecord, "DATETIME", FieldType.DATETIME, "2019-01-01T02:30:00Z") // user select type let selectUserData: [Member] = [self.testUser1, self.testUser2] let selectOrgData: [Member] = [self.testOrg1, self.testOrg2] let selectGroupData: [Member] = [self.testGroup1, self.testGroup2] testRecord = addData(testRecord, "USER_SELECT", FieldType.USER_SELECT, selectUserData) testRecord = addData(testRecord, "ORGANIZATION_SELECT", FieldType.ORGANIZATION_SELECT, selectOrgData) testRecord = addData(testRecord, "GROUP_SELECT", FieldType.GROUP_SELECT, selectGroupData) // subTable let subtableValue = SubTableValueItem() let selectUserDataForSub: [Member] = [self.testUser1, self.testUser2] var subtableItem: Dictionary<String, FieldValue> = [:] subtableItem = addData(subtableItem, "SINGLE_LINE_TEXT_TABLE", FieldType.SINGLE_LINE_TEXT, "single line text subtable test data") subtableItem = addData(subtableItem, "DROP_DOWN_TABLE", FieldType.DROP_DOWN, "sample1") subtableItem = addData(subtableItem, "USER_SELECT_TABLE", FieldType.USER_SELECT, selectUserDataForSub) subtableValue.setValue(subtableItem) let subtableData: [SubTableValueItem] = [subtableValue] testRecord = addData(testRecord, "Table", FieldType.SUBTABLE, subtableData) return testRecord } private func addData(_ recordData: Dictionary<String, FieldValue>, _ code: String, _ type: FieldType, _ value: Any) -> Dictionary<String, FieldValue> { var recData = recordData let field = FieldValue() field.setType(type) field.setValue(value) recData[code] = field return recData } func checkResult(_ fieldType: FieldType, _ fieldValue: Any, _ comarisonValue: Any) { switch fieldType { case .SINGLE_LINE_TEXT: fallthrough case .MULTI_LINE_TEXT: fallthrough case .RICH_TEXT: fallthrough case .DATE: fallthrough case .TIME: fallthrough case .DATETIME: fallthrough case .NUMBER: let resultVal = fieldValue as! String let expectedVal = comarisonValue as! String XCTAssertEqual(resultVal, expectedVal) break case .SUBTABLE: let resultVal = fieldValue as! Array<SubTableValueItem> for (_, subVal) in resultVal.enumerated() { for (_, val) in (subVal.getValue()?.enumerated())! { XCTAssertNotNil(val.value.getValue()) } } break case .MULTI_SELECT: let resultVal = fieldValue as! Array<String> let expectedVal = comarisonValue as! Array<String> XCTAssertEqual(resultVal, expectedVal) break case .USER_SELECT: fallthrough case .ORGANIZATION_SELECT: fallthrough case .GROUP_SELECT: let resultVal = fieldValue as! Array<Member> let expectedVal = comarisonValue as! Array<Member> for (i, val) in resultVal.enumerated() { XCTAssertTrue(val==expectedVal[i]) } break case .FILE: let resultVal = fieldValue as! Array<FileModel> let expectedVal = comarisonValue as! Array<FileModel> for (i, val) in resultVal.enumerated() { XCTAssertTrue(val==expectedVal[i]) } break default: break } } } extension Member: Equatable { static func ==(lhs: Member, rhs: Member) -> Bool { return lhs.code == rhs.code && lhs.name == rhs.name } } extension SubTableValueItem: Equatable { static func ==(lhs: SubTableValueItem, rhs: SubTableValueItem) -> Bool { return lhs.getID() == rhs.getID() && lhs.getValue() == rhs.getValue() } }
51.423804
155
0.646463
2f6ac7e2f32b9802692b47b890b7a0a26d8a6bf5
4,991
// // SLGenericsNineView // SLGenericsNineView // // Created by 一声雷 on 2017/8/28. // Copyright © 2017年 che300. All rights reserved. // import UIKit public class SLGenericsNineView<ItemView:UIView, ItemModel>: UIView { /// cell是否从xib中加载的 public var isCellLoadFromXib = false /// 数据源 public var dataArr:[ItemModel]?{ didSet{ self.reloadData() } } /// 刷新列表数据 public func reloadData(){ if dataArr?.count == self.subviews.count{ // 1.只是进行子控件的数据更新 for (i , subView) in self.subviews.enumerated(){ if let view = subView as? ItemView, let model = dataArr?[i]{ self.map(view, model) } } }else{ // 2.删除原先的子控件,进行重新布局 creatAllItems() } } /// 重新布局 public func reLayoutSubViews(){ creatAllItems() } /// 每个cell点击以后的回调闭包 public var itemClicked:((_ itemView:ItemView, _ model:ItemModel, _ index:Int)->Void)? /* 1:若使用frame布局,只需确定位置即可,尺寸自动计算. 2:若使用autolayout布局:只需确定位置即可,尺寸自动计算. */ /// - Parameters: /// - totalWidth: 控件的width /// - map:映射函数,控件和模型直接的数据赋值关系 public init(totalWidth: CGFloat, map:@escaping (_ cell:ItemView, _ itemModel:ItemModel)->Void) { self.totalWidth = totalWidth self.map = map super.init(frame: CGRect(x: 0, y: 0, width: totalWidth, height: 0)) self.backgroundColor = UIColor.gray } /// 上边距 public var topMargin:CGFloat = 0 /// 左边距 public var leftMargin:CGFloat = 0 /// 右边距 public var rightMargin:CGFloat = 0 /// 下边距 public var bottomMargin:CGFloat = 0 /// 设置边距 public func set(edges:CGFloat){ self.topMargin = edges self.bottomMargin = edges self.leftMargin = edges self.rightMargin = edges } /// 水平间距 public var horizontalSpace:CGFloat = 1 /// 垂直间距 public var verticalSpace:CGFloat = 1 /// 每行展示的个数 public var everyRowCount:Int = 3 /// cell高度 public var itemHeight:CGFloat = 80 /// cell宽度 public var itemWidth:CGFloat{ get{ let everyRowBtnsWidth = totalWidth - CGFloat(everyRowCount-1)*horizontalSpace - leftMargin - rightMargin return everyRowBtnsWidth/CGFloat(everyRowCount) } } /// 整体宽度 public var totalWidth:CGFloat /// 整体高度 public var totalHeight:CGFloat{ guard let count = dataArr?.count else{ return self.frame.height } var rowCount = 0 if count % everyRowCount == 0{ rowCount = count / everyRowCount }else{ rowCount = count / everyRowCount + 1 } let height = itemHeight*CGFloat(rowCount) + verticalSpace*CGFloat(rowCount-1) + topMargin + bottomMargin return height } private var map:((_ cell:ItemView, _ itemModel:ItemModel)->Void) private func initCell() -> ItemView{ if isCellLoadFromXib{ let view = Bundle.main.loadNibNamed(ItemView.nameOfClass, owner: nil, options: nil)?.last as! ItemView view.autoresizingMask = [.flexibleBottomMargin,.flexibleRightMargin] return view }else{ return ItemView.init() } } private func creatAllItems(){ guard let data = self.dataArr else{ self.removeAllSubviews() return } self.removeAllSubviews() for ( i, data ) in data.enumerated(){ let itemX = i % everyRowCount // 处于第几列 let itemY = i / everyRowCount // 处于第几行 let btn = self.initCell() btn.tag = i let x = CGFloat(itemX)*horizontalSpace + CGFloat(itemX)*itemWidth + leftMargin let y = CGFloat(itemY)*verticalSpace + CGFloat(itemY)*itemHeight + topMargin btn.frame = CGRect(x: x, y: y, width: self.itemWidth, height: self.itemHeight) self.addSubview(btn) self.map(btn, data) // 添加点击手势 let tap = UITapGestureRecognizer(target: self, action:#selector(self.didClicked(_:))) tap.numberOfTouchesRequired = 1 tap.numberOfTapsRequired = 1 btn.addGestureRecognizer(tap) } // 更新自身高度 let size = CGSize(width: self.totalWidth, height: self.totalHeight) self.frame.size = size // 通知控件固有尺寸变化 self.invalidateIntrinsicContentSize() } // 手势的点击事件 @objc func didClicked(_ tap:UITapGestureRecognizer){ if let cell = tap.view as? ItemView, let data = self.dataArr?[cell.tag]{ self.itemClicked?(cell, data, cell.tag) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 控件固有尺寸 public override var intrinsicContentSize: CGSize{ return CGSize(width: totalWidth, height: totalHeight) } }
31
116
0.58886
9b9843f8385647aab7126c7ea6eaf4c0c6321d22
3,203
// // NSViewControllerExtensions.swift // Simple Login // // Created by Thanh-Nhon Nguyen on 06/01/2020. // Copyright © 2020 SimpleLogin. All rights reserved. // import Cocoa extension NSViewController { func showHUD(attributedMessageString: NSAttributedString) { let storyboardName = NSStoryboard.Name(stringLiteral: "HUD") let storyboard = NSStoryboard(name: storyboardName, bundle: nil) let storyboardID = NSStoryboard.SceneIdentifier(stringLiteral: "HUDWindowControllerID") if let hudWindowController = storyboard.instantiateController(withIdentifier: storyboardID) as? NSWindowController { if let hudViewController = hudWindowController.contentViewController as? HUDViewController { hudViewController.attributedMessageString = attributedMessageString } hudWindowController.window?.isOpaque = false hudWindowController.showWindow(self) NSAnimationContext.runAnimationGroup({ (context) in context.duration = 1.35 hudWindowController.window?.animator().alphaValue = 1.0 }) { hudWindowController.window?.animator().alphaValue = 0.0 hudWindowController.close() } } } func showEnterApiKeyWindowController() { let storyboardName = NSStoryboard.Name(stringLiteral: "EnterApiKey") let storyboard = NSStoryboard(name: storyboardName, bundle: nil) let storyboardID = NSStoryboard.SceneIdentifier(stringLiteral: "EnterApiKeyWindowControllerID") if let enterApiKeyWindowController = storyboard.instantiateController(withIdentifier: storyboardID) as? NSWindowController { enterApiKeyWindowController.showWindow(nil) } } func showHomeWindowController(with userInfo: UserInfo) { let storyboard = NSStoryboard(name: NSStoryboard.Name(stringLiteral: "Home"), bundle: nil) let storyboardID = NSStoryboard.SceneIdentifier(stringLiteral: "HomeWindowController") let homeWindowController = storyboard.instantiateController(withIdentifier: storyboardID) as? HomeWindowController homeWindowController?.userInfo = userInfo homeWindowController?.showWindow(nil) } func showErrorAlert(_ error: SLError) { let alert = NSAlert() alert.icon = NSImage(named: NSImage.Name(stringLiteral: "SimpleLogin")) alert.messageText = "Error occured" alert.informativeText = error.description alert.addButton(withTitle: "Close") alert.alertStyle = .warning alert.runModal() } } final class HUDViewController: NSViewController { @IBOutlet private weak var messageLabel: NSTextField! var attributedMessageString: NSAttributedString? override func viewWillAppear() { super.viewWillAppear() messageLabel.attributedStringValue = attributedMessageString ?? NSAttributedString(string: "") view.window?.setContentSize(NSSize(width: messageLabel.intrinsicContentSize.width + 8*2, height: messageLabel.intrinsicContentSize.height + 8*2)) } }
42.144737
153
0.693725
1470a6b07f1b2382b318ab93f815a5f49badab2b
172
//: Playground - noun: a place where people can play import UIKit var str = "Hello, \"playground\"" str.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
19.111111
67
0.77907
3378df0c4d51a87f3339fb66c97a87b97d25dc74
7,519
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen #if os(OSX) import AppKit.NSFont internal typealias Font = NSFont #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit.UIFont internal typealias Font = UIFont #endif // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length // MARK: - Fonts // swiftlint:disable identifier_name line_length type_body_length internal enum FontFamily { internal enum SFProDisplay { internal static let black = FontConvertible(name: "SFProDisplay-Black", family: "SF Pro Display", path: "SF-Pro-Display-Black.otf") internal static let blackItalic = FontConvertible(name: "SFProDisplay-BlackItalic", family: "SF Pro Display", path: "SF-Pro-Display-BlackItalic.otf") internal static let bold = FontConvertible(name: "SFProDisplay-Bold", family: "SF Pro Display", path: "SF-Pro-Display-Bold.otf") internal static let boldItalic = FontConvertible(name: "SFProDisplay-BoldItalic", family: "SF Pro Display", path: "SF-Pro-Display-BoldItalic.otf") internal static let heavy = FontConvertible(name: "SFProDisplay-Heavy", family: "SF Pro Display", path: "SF-Pro-Display-Heavy.otf") internal static let heavyItalic = FontConvertible(name: "SFProDisplay-HeavyItalic", family: "SF Pro Display", path: "SF-Pro-Display-HeavyItalic.otf") internal static let light = FontConvertible(name: "SFProDisplay-Light", family: "SF Pro Display", path: "SF-Pro-Display-Light.otf") internal static let lightItalic = FontConvertible(name: "SFProDisplay-LightItalic", family: "SF Pro Display", path: "SF-Pro-Display-LightItalic.otf") internal static let medium = FontConvertible(name: "SFProDisplay-Medium", family: "SF Pro Display", path: "SF-Pro-Display-Medium.otf") internal static let mediumItalic = FontConvertible(name: "SFProDisplay-MediumItalic", family: "SF Pro Display", path: "SF-Pro-Display-MediumItalic.otf") internal static let regular = FontConvertible(name: "SFProDisplay-Regular", family: "SF Pro Display", path: "SF-Pro-Display-Regular.otf") internal static let regularItalic = FontConvertible(name: "SFProDisplay-RegularItalic", family: "SF Pro Display", path: "SF-Pro-Display-RegularItalic.otf") internal static let semibold = FontConvertible(name: "SFProDisplay-Semibold", family: "SF Pro Display", path: "SF-Pro-Display-Semibold.otf") internal static let semiboldItalic = FontConvertible(name: "SFProDisplay-SemiboldItalic", family: "SF Pro Display", path: "SF-Pro-Display-SemiboldItalic.otf") internal static let thin = FontConvertible(name: "SFProDisplay-Thin", family: "SF Pro Display", path: "SF-Pro-Display-Thin.otf") internal static let thinItalic = FontConvertible(name: "SFProDisplay-ThinItalic", family: "SF Pro Display", path: "SF-Pro-Display-ThinItalic.otf") internal static let ultralight = FontConvertible(name: "SFProDisplay-Ultralight", family: "SF Pro Display", path: "SF-Pro-Display-Ultralight.otf") internal static let ultralightItalic = FontConvertible(name: "SFProDisplay-UltralightItalic", family: "SF Pro Display", path: "SF-Pro-Display-UltralightItalic.otf") internal static let all: [FontConvertible] = [black, blackItalic, bold, boldItalic, heavy, heavyItalic, light, lightItalic, medium, mediumItalic, regular, regularItalic, semibold, semiboldItalic, thin, thinItalic, ultralight, ultralightItalic] } internal enum SFProText { internal static let black = FontConvertible(name: "SFProText-Black", family: "SF Pro Text", path: "SF-Pro-Text-Black.otf") internal static let blackItalic = FontConvertible(name: "SFProText-BlackItalic", family: "SF Pro Text", path: "SF-Pro-Text-BlackItalic.otf") internal static let bold = FontConvertible(name: "SFProText-Bold", family: "SF Pro Text", path: "SF-Pro-Text-Bold.otf") internal static let boldItalic = FontConvertible(name: "SFProText-BoldItalic", family: "SF Pro Text", path: "SF-Pro-Text-BoldItalic.otf") internal static let heavy = FontConvertible(name: "SFProText-Heavy", family: "SF Pro Text", path: "SF-Pro-Text-Heavy.otf") internal static let heavyItalic = FontConvertible(name: "SFProText-HeavyItalic", family: "SF Pro Text", path: "SF-Pro-Text-HeavyItalic.otf") internal static let light = FontConvertible(name: "SFProText-Light", family: "SF Pro Text", path: "SF-Pro-Text-Light.otf") internal static let lightItalic = FontConvertible(name: "SFProText-LightItalic", family: "SF Pro Text", path: "SF-Pro-Text-LightItalic.otf") internal static let medium = FontConvertible(name: "SFProText-Medium", family: "SF Pro Text", path: "SF-Pro-Text-Medium.otf") internal static let mediumItalic = FontConvertible(name: "SFProText-MediumItalic", family: "SF Pro Text", path: "SF-Pro-Text-MediumItalic.otf") internal static let regular = FontConvertible(name: "SFProText-Regular", family: "SF Pro Text", path: "SF-Pro-Text-Regular.otf") internal static let regularItalic = FontConvertible(name: "SFProText-RegularItalic", family: "SF Pro Text", path: "SF-Pro-Text-RegularItalic.otf") internal static let semibold = FontConvertible(name: "SFProText-Semibold", family: "SF Pro Text", path: "SF-Pro-Text-Semibold.otf") internal static let semiboldItalic = FontConvertible(name: "SFProText-SemiboldItalic", family: "SF Pro Text", path: "SF-Pro-Text-SemiboldItalic.otf") internal static let thin = FontConvertible(name: "SFProText-Thin", family: "SF Pro Text", path: "SF-Pro-Text-Thin.otf") internal static let thinItalic = FontConvertible(name: "SFProText-ThinItalic", family: "SF Pro Text", path: "SF-Pro-Text-ThinItalic.otf") internal static let ultralight = FontConvertible(name: "SFProText-Ultralight", family: "SF Pro Text", path: "SF-Pro-Text-Ultralight.otf") internal static let ultralightItalic = FontConvertible(name: "SFProText-UltralightItalic", family: "SF Pro Text", path: "SF-Pro-Text-UltralightItalic.otf") internal static let all: [FontConvertible] = [black, blackItalic, bold, boldItalic, heavy, heavyItalic, light, lightItalic, medium, mediumItalic, regular, regularItalic, semibold, semiboldItalic, thin, thinItalic, ultralight, ultralightItalic] } internal static let allCustomFonts: [FontConvertible] = [SFProDisplay.all, SFProText.all].flatMap { $0 } internal static func registerAllCustomFonts() { allCustomFonts.forEach { $0.register() } } } // swiftlint:enable identifier_name line_length type_body_length // MARK: - Implementation Details internal struct FontConvertible { internal let name: String internal let family: String internal let path: String internal func font(size: CGFloat) -> Font! { return Font(font: self, size: size) } internal func register() { // swiftlint:disable:next conditional_returns_on_newline guard let url = url else { return } CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil) } fileprivate var url: URL? { let bundle = Bundle(for: BundleToken.self) return bundle.url(forResource: path, withExtension: nil) } } internal extension Font { convenience init!(font: FontConvertible, size: CGFloat) { #if os(iOS) || os(tvOS) || os(watchOS) if !UIFont.fontNames(forFamilyName: font.family).contains(font.name) { font.register() } #elseif os(OSX) if let url = font.url, CTFontManagerGetScopeForURL(url as CFURL) == .none { font.register() } #endif self.init(name: font.name, size: size) } } private final class BundleToken {}
69.62037
247
0.743583
69a497c37834d151ca315234292165e9de924ecf
9,583
// // ViewController.swift // DropDown // // Created by Kevin Hirsch on 28/07/15. // Copyright (c) 2015 Kevin Hirsch. All rights reserved. // import UIKit import DropDown class ViewController: UIViewController { //MARK: - Properties @IBOutlet weak var chooseArticleButton: UIButton! @IBOutlet weak var amountButton: UIButton! @IBOutlet weak var chooseButton: UIButton! @IBOutlet weak var centeredDropDownButton: UIButton! @IBOutlet weak var rightBarButton: UIBarButtonItem! let textField = UITextField() //MARK: - DropDown's let chooseArticleDropDown = DropDown() let amountDropDown = DropDown() let chooseDropDown = DropDown() let centeredDropDown = DropDown() let rightBarDropDown = DropDown() lazy var dropDowns: [DropDown] = { return [ self.chooseArticleDropDown, self.amountDropDown, self.chooseDropDown, self.centeredDropDown, self.rightBarDropDown ] }() //MARK: - Actions @IBAction func chooseArticle(_ sender: AnyObject) { chooseArticleDropDown.show() } @IBAction func changeAmount(_ sender: AnyObject) { amountDropDown.show() } @IBAction func choose(_ sender: AnyObject) { chooseDropDown.show() } @IBAction func showCenteredDropDown(_ sender: AnyObject) { centeredDropDown.show() } @IBAction func showBarButtonDropDown(_ sender: AnyObject) { rightBarDropDown.show() } @IBAction func changeDIsmissMode(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: dropDowns.forEach { $0.dismissMode = .automatic } case 1: dropDowns.forEach { $0.dismissMode = .onTap } default: break; } } @IBAction func changeDirection(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: dropDowns.forEach { $0.direction = .any } case 1: dropDowns.forEach { $0.direction = .bottom } case 2: dropDowns.forEach { $0.direction = .top } default: break; } } @IBAction func changeUI(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: setupDefaultDropDown() case 1: customizeDropDown(self) default: break; } } @IBAction func showKeyboard(_ sender: AnyObject) { textField.becomeFirstResponder() } @IBAction func hideKeyboard(_ sender: AnyObject) { view.endEditing(false) } func setupDefaultDropDown() { DropDown.setupDefaultAppearance() dropDowns.forEach { $0.cellNib = UINib(nibName: "DropDownCell", bundle: Bundle(for: DropDownCell.self)) $0.customCellConfiguration = nil } } func customizeDropDown(_ sender: AnyObject) { let appearance = DropDown.appearance() appearance.cellHeight = 60 appearance.backgroundColor = UIColor(white: 1, alpha: 1) appearance.selectionBackgroundColor = UIColor(red: 0.6494, green: 0.8155, blue: 1.0, alpha: 0.2) // appearance.separatorColor = UIColor(white: 0.7, alpha: 0.8) appearance.cornerRadius = 10 appearance.shadowColor = UIColor(white: 0.6, alpha: 1) appearance.shadowOpacity = 0.9 appearance.shadowRadius = 25 appearance.animationduration = 0.25 appearance.textColor = .darkGray // appearance.textFont = UIFont(name: "Georgia", size: 14) dropDowns.forEach { /*** FOR CUSTOM CELLS ***/ $0.cellNib = UINib(nibName: "MyCell", bundle: nil) $0.customCellConfiguration = { (index: Index, item: String, cell: DropDownCell) -> Void in guard let cell = cell as? MyCell else { return } // Setup your custom UI components cell.suffixLabel.text = "Suffix \(index)" } /*** ---------------- ***/ } } //MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() setupDropDowns() dropDowns.forEach { $0.dismissMode = .onTap } dropDowns.forEach { $0.direction = .any } view.addSubview(textField) } //MARK: - Setup func setupDropDowns() { setupChooseArticleDropDown() setupAmountDropDown() setupChooseDropDown() setupCenteredDropDown() setupRightBarDropDown() } func setupChooseArticleDropDown() { chooseArticleDropDown.anchorView = chooseArticleButton // Will set a custom with instead of anchor view width // dropDown.width = 100 // By default, the dropdown will have its origin on the top left corner of its anchor view // So it will come over the anchor view and hide it completely // If you want to have the dropdown underneath your anchor view, you can do this: chooseArticleDropDown.bottomOffset = CGPoint(x: 0, y: chooseArticleButton.bounds.height) // You can also use localizationKeysDataSource instead. Check the docs. chooseArticleDropDown.dataSource = [ "iPhone SE | Black | 64G", "Samsung S7", "Huawei P8 Lite Smartphone 4G", "Asus Zenfone Max 4G", "Apple Watwh | Sport Edition" ] // Action triggered on selection chooseArticleDropDown.selectionAction = { [weak self] (index, item) in self?.chooseArticleButton.setTitle(item, for: .normal) } chooseArticleDropDown.multiSelectionAction = { [weak self] (indices, items) in print("Muti selection action called with: \(items)") if items.isEmpty { self?.chooseArticleButton.setTitle("", for: .normal) } } // Action triggered on dropdown cancelation (hide) // dropDown.cancelAction = { [unowned self] in // // You could for example deselect the selected item // self.dropDown.deselectRowAtIndexPath(self.dropDown.indexForSelectedRow) // self.actionButton.setTitle("Canceled", forState: .Normal) // } // You can manually select a row if needed // dropDown.selectRowAtIndex(3) } func setupAmountDropDown() { amountDropDown.anchorView = amountButton // By default, the dropdown will have its origin on the top left corner of its anchor view // So it will come over the anchor view and hide it completely // If you want to have the dropdown underneath your anchor view, you can do this: amountDropDown.bottomOffset = CGPoint(x: 0, y: amountButton.bounds.height) // You can also use localizationKeysDataSource instead. Check the docs. amountDropDown.dataSource = [ "10 €", "20 €", "30 €", "40 €", "50 €", "60 €", "70 €", "80 €", "90 €", "100 €", "110 €", "120 €" ] // Action triggered on selection amountDropDown.selectionAction = { [weak self] (index, item) in self?.amountButton.setTitle(item, for: .normal) } } func setupChooseDropDown() { chooseDropDown.anchorView = chooseButton // By default, the dropdown will have its origin on the top left corner of its anchor view // So it will come over the anchor view and hide it completely // If you want to have the dropdown underneath your anchor view, you can do this: chooseDropDown.bottomOffset = CGPoint(x: 0, y: chooseButton.bounds.height) // You can also use localizationKeysDataSource instead. Check the docs. chooseDropDown.dataSource = [ "Lorem ipsum dolor", "sit amet consectetur sit amet consectetur sit amet consectetur sit amet consectetur sit amet consectetur", // long string for testing multi-line support in tableview cell. "cadipisci en..." ] // Action triggered on selection chooseDropDown.selectionAction = { [weak self] (index, item) in self?.chooseButton.setTitle(item, for: .normal) } } func setupCenteredDropDown() { // Not setting the anchor view makes the drop down centered on screen // centeredDropDown.anchorView = centeredDropDownButton // You can also use localizationKeysDataSource instead. Check the docs. centeredDropDown.dataSource = [ "The drop down", "Is centered on", "the view because", "it has no anchor view defined.", "Click anywhere to dismiss." ] centeredDropDown.selectionAction = { [weak self] (index, item) in self?.centeredDropDownButton.setTitle(item, for: .normal) } } func setupRightBarDropDown() { rightBarDropDown.anchorView = rightBarButton // You can also use localizationKeysDataSource instead. Check the docs. rightBarDropDown.dataSource = [ "Menu 1", "Menu 2", "Menu 3", "Menu 4" ] } }
34.225
119
0.589794
c15ca1ac85327692d0d344e8ac608f1cdd21e119
515
//: [Previous](@previous) import Foundation // .map usage let formatter = NumberFormatter() formatter.numberStyle = .spellOut // Ex where we define String specific as return value for map [123, 68, 98].publisher.map { value -> String in formatter.string(from: NSNumber(integerLiteral: value)) ?? "" }.sink { print($0) } // Ex where it infers string from the result [123, 68, 98].publisher.map { formatter.string(from: NSNumber(integerLiteral: $0)) ?? "" }.sink { print($0) } //: [Next](@next)
20.6
65
0.667961
568263b3bf49f7edc89232d1444c64708d18d27f
59,035
//#if RENDER_MOD_STYLESHEET // // Expression.swift // Expression // // Version 0.11.1 // // Created by Nick Lockwood on 15/09/2016. // Copyright © 2016 Nick Lockwood. All rights reserved. // // Distributed under the permissive MIT license // Get the latest version from here: // // https://github.com/nicklockwood/Expression // // 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 /// Immutable wrapper for a parsed expression /// Reusing the same Expression instance for multiple evaluations is more efficient /// than creating a new one each time you wish to evaluate an expression string. public final class Expression: CustomStringConvertible { private var root: Subexpression /// Function prototype for evaluating an expression /// Return nil for an unrecognized symbol, or throw an error if the symbol is recognized /// but there is some other problem (e.g. wrong number of arguments for a function) public typealias Evaluator = (_ symbol: Symbol, _ args: [Double]) throws -> Double? /// Evaluator for individual symbols public typealias SymbolEvaluator = (_ args: [Double]) throws -> Double /// Type representing the arity (number of arguments) accepted by a function public enum Arity: ExpressibleByIntegerLiteral, CustomStringConvertible, Equatable { public typealias IntegerLiteralType = Int /// An exact number of arguments case exactly(Int) /// A minimum number of arguments case atLeast(Int) /// ExpressibleByIntegerLiteral constructor public init(integerLiteral value: Int) { self = .exactly(value) } /// The human-readable description of the arity public var description: String { switch self { case let .exactly(value): return "\(value) argument\(value == 1 ? "" : "s")" case let .atLeast(value): return "at least \(value) argument\(value == 1 ? "" : "s")" } } /// Equatable implementation /// Note: this works more like a contains() function if the /// lhs is a range and the rhs is an exact value. This allows /// foo(x) to match foo(...) in a symbols dictionary public static func == (lhs: Arity, rhs: Arity) -> Bool { switch (lhs, rhs) { case let (.exactly(lhs), .exactly(rhs)), let (.atLeast(lhs), .atLeast(rhs)): return lhs == rhs case let (.atLeast(min), .exactly(rhs)): return rhs >= min case (.exactly, _), (.atLeast, _): return false } } } /// Symbols that make up an expression public enum Symbol: CustomStringConvertible, Hashable { /// A named variable case variable(String) /// An infix operator case infix(String) /// A prefix operator case prefix(String) /// A postfix operator case postfix(String) /// A function accepting a number of arguments specified by `arity` case function(String, arity: Arity) /// A array of values accessed by index case array(String) /// Evaluator for individual symbols @available(*, deprecated, message: "Use SymbolEvaluator instead") public typealias Evaluator = SymbolEvaluator /// The human-readable name of the symbol public var name: String { switch self { case let .variable(name), let .infix(name), let .prefix(name), let .postfix(name), let .function(name, _), let .array(name): return name } } /// The human-readable description of the symbol public var description: String { switch self { case let .variable(name): return "variable \(demangle(name))" case let .infix(name): return "infix operator \(demangle(name))" case let .prefix(name): return "prefix operator \(demangle(name))" case let .postfix(name): return "postfix operator \(demangle(name))" case let .function(name, _): return "function \(demangle(name))()" case let .array(name): return "array \(demangle(name))[]" } } /// Required by the Hashable protocol public var hashValue: Int { return name.hashValue } /// Equatable implementation public static func == (lhs: Symbol, rhs: Symbol) -> Bool { if case let .function(_, lhsarity) = lhs, case let .function(_, rhsarity) = rhs, lhsarity != rhsarity { return false } return lhs.description == rhs.description } } /// Runtime error when parsing or evaluating an expression public enum Error: Swift.Error, CustomStringConvertible, Equatable { /// An application-specific error case message(String) /// The parser encountered a sequence of characters it didn't recognize case unexpectedToken(String) /// The parser expected to find a delimiter (e.g. closing paren) but didn't case missingDelimiter(String) /// The specified constant, operator or function was not recognized case undefinedSymbol(Symbol) /// A function was called with the wrong number of arguments (arity) case arityMismatch(Symbol) /// An array was accessed with an index outside the valid range case arrayBounds(Symbol, Double) /// The human-readable description of the error public var description: String { switch self { case let .message(message): return message case .unexpectedToken(""): return "Empty expression" case let .unexpectedToken(string): return "Unexpected token `\(string)`" case let .missingDelimiter(string): return "Missing `\(string)`" case let .undefinedSymbol(symbol): return "Undefined \(symbol)" case let .arityMismatch(symbol): let arity: Arity switch symbol { case .variable: arity = 0 case .infix("?:"): arity = 3 case .infix: arity = 2 case .postfix, .prefix: arity = 1 case let .function(_, requiredArity): arity = requiredArity case .array: arity = 1 } let description = symbol.description return String(description.first!).uppercased() + "\(description.dropFirst()) expects \(arity)" case let .arrayBounds(symbol, index): return "Index \(stringify(index)) out of bounds for \(symbol)" } } /// Equatable implementation public static func == (lhs: Error, rhs: Error) -> Bool { switch (lhs, rhs) { case let (.message(lhs), .message(rhs)), let (.unexpectedToken(lhs), .unexpectedToken(rhs)), let (.missingDelimiter(lhs), .missingDelimiter(rhs)): return lhs == rhs case let (.undefinedSymbol(lhs), .undefinedSymbol(rhs)), let (.arityMismatch(lhs), .arityMismatch(rhs)): return lhs == rhs case let (.arrayBounds(lsymbol, lindex), .arrayBounds(rsymbol, rindex)): return lsymbol == rsymbol && lindex == rindex case (.message, _), (.unexpectedToken, _), (.missingDelimiter, _), (.undefinedSymbol, _), (.arityMismatch, _), (.arrayBounds, _): return false } } } /// Options for configuring an expression public struct Options: OptionSet { /// Disable optimizations such as constant substitution public static let noOptimize = Options(rawValue: 1 << 1) /// Enable standard boolean operators and constants public static let boolSymbols = Options(rawValue: 1 << 2) /// Assume all functions and operators in `symbols` are "pure", i.e. /// they have no side effects, and always produce the same output /// for a given set of arguments public static let pureSymbols = Options(rawValue: 1 << 3) /// Packed bitfield of options public let rawValue: Int /// Designated initializer public init(rawValue: Int) { self.rawValue = rawValue } } /// Creates an Expression object from a string /// Optionally accepts some or all of: /// - A set of options for configuring expression behavior /// - A dictionary of constants for simple static values /// - A dictionary of arrays for static collections of related values /// - A dictionary of symbols, for implementing custom functions and operators /// - A custom evaluator function for more complex symbol processing public convenience init( _ expression: String, options: Options = [], constants: [String: Double] = [:], arrays: [String: [Double]] = [:], symbols: [Symbol: SymbolEvaluator] = [:], evaluator: Evaluator? = nil ) { self.init( Expression.parse(expression), options: options, constants: constants, arrays: arrays, symbols: symbols, evaluator: evaluator ) } /// Alternative constructor that accepts a pre-parsed expression public init( _ expression: ParsedExpression, options: Options = [], constants: [String: Double] = [:], arrays: [String: [Double]] = [:], symbols: [Symbol: SymbolEvaluator] = [:], evaluator: Evaluator? = nil ) { root = expression.root let boolSymbols = options.contains(.boolSymbols) ? Expression.boolSymbols : [:] var impureSymbols = Dictionary<Symbol, SymbolEvaluator>() var pureSymbols = Dictionary<Symbol, SymbolEvaluator>() // Evaluators func symbolEvaluator(for symbol: Symbol) -> SymbolEvaluator? { if let fn = symbols[symbol] { return fn } else if boolSymbols.isEmpty, case .infix("?:") = symbol, let lhs = symbols[.infix("?")], let rhs = symbols[.infix(":")] { return { args in try rhs([lhs([args[0], args[1]]), args[2]]) } } return nil } func customEvaluator(for symbol: Symbol, optimizing: Bool) -> SymbolEvaluator? { guard let evaluator = evaluator else { return nil } let fallback: SymbolEvaluator = { guard let fn = defaultEvaluator(for: symbol) else { return errorHandler(for: symbol) } return optimizing ? { [unowned self] args in // Rewrite expression to skip custom evaluator pureSymbols[symbol] = customEvaluator(for: symbol, optimizing: false) impureSymbols.removeValue(forKey: symbol) self.root = self.root.optimized(withSymbols: impureSymbols, pureSymbols: pureSymbols) return try fn(args) } : fn }() return { args in // Try custom evaluator if let value = try evaluator(symbol, args) { return value } // Special case for ternary if args.count == 3, boolSymbols.isEmpty, case .infix("?:") = symbol, let lhs = try evaluator(.infix("?"), [args[0], args[1]]), let value = try evaluator(.infix(":"), [lhs, args[2]]) { return value } // Try default evaluator return try fallback(args) } } func defaultEvaluator(for symbol: Symbol) -> SymbolEvaluator? { // Check default symbols return Expression.mathSymbols[symbol] ?? boolSymbols[symbol] } func errorHandler(for symbol: Symbol) -> SymbolEvaluator { // Check for arity mismatch if case let .function(called, arity) = symbol { let keys = Set(Expression.mathSymbols.keys).union(boolSymbols.keys).union(symbols.keys) for case let .function(name, requiredArity) in keys where name == called && arity != requiredArity { return { _ in throw Error.arityMismatch(.function(called, arity: requiredArity)) } } } // Not found return { _ in throw Error.undefinedSymbol(symbol) } } // Resolve symbols and optimize expression let optimize = !options.contains(.noOptimize) for symbol in root.symbols { if case let .variable(name) = symbol, let value = constants[name] { pureSymbols[symbol] = { _ in value } } else if case let .array(name) = symbol, let array = arrays[name] { pureSymbols[symbol] = { args in guard let index = Int(exactly: floor(args[0])), array.indices.contains(index) else { throw Error.arrayBounds(symbol, args[0]) } return array[index] } } else if let fn = symbolEvaluator(for: symbol) { if case .variable = symbol { impureSymbols[symbol] = fn } else if options.contains(.pureSymbols) { pureSymbols[symbol] = fn } else { impureSymbols[symbol] = fn } } else if let fn = customEvaluator(for: symbol, optimizing: optimize) { impureSymbols[symbol] = fn } else { pureSymbols[symbol] = defaultEvaluator(for: symbol) ?? errorHandler(for: symbol) } } if !optimize { for (symbol, evaluator) in pureSymbols { impureSymbols[symbol] = evaluator } pureSymbols.removeAll() } root = root.optimized(withSymbols: impureSymbols, pureSymbols: pureSymbols) } /// Verify that the string is a valid identifier public static func isValidIdentifier(_ string: String) -> Bool { var characters = UnicodeScalarView(string) switch characters.parseIdentifier() ?? characters.parseEscapedIdentifier() { case .symbol(.variable, _, _)?: return characters.isEmpty default: return false } } /// Verify that the string is a valid operator public static func isValidOperator(_ string: String) -> Bool { var characters = UnicodeScalarView(string) guard case let .symbol(symbol, _, _)? = characters.parseOperator(), case let .infix(name) = symbol, name != "(", name != "[" else { return false } return characters.isEmpty } private static var cache = [String: Subexpression]() private static let queue = DispatchQueue(label: "com.Expression") // For testing static func isCached(_ expression: String) -> Bool { return queue.sync { cache[expression] != nil } } /// Parse an expression and optionally cache it for future use. /// Returns an opaque struct that cannot be evaluated but can be queried /// for symbols or used to construct an executable Expression instance public static func parse(_ expression: String, usingCache: Bool = true) -> ParsedExpression { // Check cache if usingCache { var cachedExpression: Subexpression? queue.sync { cachedExpression = cache[expression] } if let subexpression = cachedExpression { return ParsedExpression(root: subexpression) } } // Parse var characters = Substring.UnicodeScalarView(expression.unicodeScalars) let parsedExpression = parse(&characters) // Store if usingCache { queue.sync { cache[expression] = parsedExpression.root } } return parsedExpression } /// Parse an expression directly from the provided UnicodeScalarView, /// stopping when it reaches a token matching the `delimiter` string. /// This is convenient if you wish to parse expressions that are nested /// inside another string, e.g. for implementing string interpolation. /// If no delimiter string is specified, the method will throw an error /// if it encounters an unexpected token, but won't consume it public static func parse( _ input: inout Substring.UnicodeScalarView, upTo delimiters: String... ) -> ParsedExpression { var unicodeScalarView = UnicodeScalarView(input) let start = unicodeScalarView var subexpression: Subexpression do { subexpression = try unicodeScalarView.parseSubexpression(upTo: delimiters) } catch { let expression = String(start.prefix(upTo: unicodeScalarView.startIndex)) subexpression = .error(error as! Error, expression) } input = Substring.UnicodeScalarView(unicodeScalarView) return ParsedExpression(root: subexpression) } /// Clear the expression cache (useful for testing, or in low memory situations) public static func clearCache(for expression: String? = nil) { queue.sync { if let expression = expression { cache.removeValue(forKey: expression) } else { cache.removeAll() } } } /// Returns the optmized, pretty-printed expression if it was valid /// Otherwise, returns the original (invalid) expression string public var description: String { return root.description } /// All symbols used in the expression public var symbols: Set<Symbol> { return root.symbols } /// Evaluate the expression public func evaluate() throws -> Double { return try root.evaluate() } /// Standard math symbols public static let mathSymbols: [Symbol: SymbolEvaluator] = { var symbols: [Symbol: ([Double]) -> Double] = [:] // constants symbols[.variable("pi")] = { _ in .pi } // infix operators symbols[.infix("+")] = { $0[0] + $0[1] } symbols[.infix("-")] = { $0[0] - $0[1] } symbols[.infix("*")] = { $0[0] * $0[1] } symbols[.infix("/")] = { $0[0] / $0[1] } symbols[.infix("%")] = { fmod($0[0], $0[1]) } // prefix operators symbols[.prefix("-")] = { -$0[0] } // functions - arity 1 symbols[.function("sqrt", arity: 1)] = { sqrt($0[0]) } symbols[.function("floor", arity: 1)] = { floor($0[0]) } symbols[.function("ceil", arity: 1)] = { ceil($0[0]) } symbols[.function("round", arity: 1)] = { round($0[0]) } symbols[.function("cos", arity: 1)] = { cos($0[0]) } symbols[.function("acos", arity: 1)] = { acos($0[0]) } symbols[.function("sin", arity: 1)] = { sin($0[0]) } symbols[.function("asin", arity: 1)] = { asin($0[0]) } symbols[.function("tan", arity: 1)] = { tan($0[0]) } symbols[.function("atan", arity: 1)] = { atan($0[0]) } symbols[.function("abs", arity: 1)] = { abs($0[0]) } // functions - arity 2 symbols[.function("pow", arity: 2)] = { pow($0[0], $0[1]) } symbols[.function("atan2", arity: 2)] = { atan2($0[0], $0[1]) } symbols[.function("mod", arity: 2)] = { fmod($0[0], $0[1]) } // functions - variadic symbols[.function("max", arity: .atLeast(2))] = { $0.reduce($0[0]) { max($0, $1) } } symbols[.function("min", arity: .atLeast(2))] = { $0.reduce($0[0]) { min($0, $1) } } return symbols }() /// Standard boolean symbols public static let boolSymbols: [Symbol: SymbolEvaluator] = { var symbols: [Symbol: ([Double]) -> Double] = [:] // boolean constants symbols[.variable("true")] = { _ in 1 } symbols[.variable("default")] = { _ in 1 } symbols[.variable("false")] = { _ in 0 } // boolean infix operators symbols[.infix("==")] = { (args: [Double]) -> Double in args[0] == args[1] ? 1 : 0 } symbols[.infix("!=")] = { (args: [Double]) -> Double in args[0] != args[1] ? 1 : 0 } symbols[.infix(">")] = { (args: [Double]) -> Double in args[0] > args[1] ? 1 : 0 } symbols[.infix(">=")] = { (args: [Double]) -> Double in args[0] >= args[1] ? 1 : 0 } symbols[.infix("<")] = { (args: [Double]) -> Double in args[0] < args[1] ? 1 : 0 } symbols[.infix("<=")] = { (args: [Double]) -> Double in args[0] <= args[1] ? 1 : 0 } symbols[.infix("&&")] = { (args: [Double]) -> Double in args[0] != 0 && args[1] != 0 ? 1 : 0 } symbols[.infix("||")] = { (args: [Double]) -> Double in args[0] != 0 || args[1] != 0 ? 1 : 0 } // boolean prefix operators symbols[.prefix("!")] = { (args: [Double]) -> Double in args[0] == 0 ? 1 : 0 } // ternary operator symbols[.infix("?:")] = { (args: [Double]) -> Double in if args.count == 3 { return args[0] != 0 ? args[1] : args[2] } return args[0] != 0 ? args[0] : args[1] } return symbols }() } /// An opaque wrapper for a parsed expression public struct ParsedExpression: CustomStringConvertible { fileprivate let root: Subexpression /// Returns the pretty-printed expression if it was valid /// Otherwise, returns the original (invalid) expression string public var description: String { return root.description } /// All symbols used in the expression public var symbols: Set<Expression.Symbol> { return root.symbols } /// Any error detected during parsing public var error: Expression.Error? { if case let .error(error, _) = root { return error } return nil } } // The internal expression implementation private enum Subexpression: CustomStringConvertible { case literal(Double) case symbol(Expression.Symbol, [Subexpression], Expression.SymbolEvaluator) case error(Expression.Error, String) var isOperand: Bool { switch self { case let .symbol(symbol, args, _) where args.isEmpty: switch symbol { case .infix, .prefix, .postfix: return false default: return true } case .symbol, .literal: return true case .error: return false } } func evaluate() throws -> Double { switch self { case let .literal(value): return value case let .symbol(_, args, fn): let argValues = try args.map { try $0.evaluate() } return try fn(argValues) case let .error(error, _): throw error } } var description: String { func arguments(_ args: [Subexpression]) -> String { return args.map { if case .symbol(.infix(","), _, _) = $0 { return "(\($0))" } return $0.description }.joined(separator: ", ") } switch self { case let .literal(value): return stringify(value) case let .symbol(symbol, args, _): guard isOperand else { return demangle(symbol.name) } func needsSeparation(_ lhs: String, _ rhs: String) -> Bool { let lhs = lhs.unicodeScalars.last!, rhs = rhs.unicodeScalars.first! return lhs == "." || (isOperator(lhs) || lhs == "-") == (isOperator(rhs) || rhs == "-") } switch symbol { case let .prefix(name): let arg = args[0] let description = "\(arg)" switch arg { case .symbol(.infix, _, _), .symbol(.postfix, _, _), .error, .symbol where needsSeparation(name, description): return "\(demangle(name))(\(description))" // Parens required case .symbol, .literal: return "\(demangle(name))\(description)" // No parens needed } case let .postfix(name): let arg = args[0] let description = "\(arg)" switch arg { case .symbol(.infix, _, _), .symbol(.postfix, _, _), .error, .symbol where needsSeparation(description, name): return "(\(description))\(demangle(name))" // Parens required case .symbol, .literal: return "\(description)\(demangle(name))" // No parens needed } case .infix(","): return "\(args[0]), \(args[1])" case .infix("?:") where args.count == 3: return "\(args[0]) ? \(args[1]) : \(args[2])" case let .infix(name): let lhs = args[0] let lhsDescription: String switch lhs { case let .symbol(.infix(opName), _, _) where !op(opName, takesPrecedenceOver: name): lhsDescription = "(\(lhs))" default: lhsDescription = "\(lhs)" } let rhs = args[1] let rhsDescription: String switch rhs { case let .symbol(.infix(opName), _, _) where op(name, takesPrecedenceOver: opName): rhsDescription = "(\(rhs))" default: rhsDescription = "\(rhs)" } return "\(lhsDescription) \(demangle(name)) \(rhsDescription)" case let .variable(name): return demangle(name) case let .function(name, _): return "\(demangle(name))(\(arguments(args)))" case let .array(name): return "\(demangle(name))[\(arguments(args))]" } case let .error(_, expression): return expression } } var symbols: Set<Expression.Symbol> { switch self { case .literal, .error: return [] case let .symbol(symbol, subexpressions, _): var symbols = Set([symbol]) for subexpression in subexpressions { symbols.formUnion(subexpression.symbols) } return symbols } } func optimized(withSymbols impureSymbols: [Expression.Symbol: Expression.SymbolEvaluator], pureSymbols: [Expression.Symbol: Expression.SymbolEvaluator]) -> Subexpression { guard case .symbol(let symbol, var args, _) = self else { return self } args = args.map { $0.optimized(withSymbols: impureSymbols, pureSymbols: pureSymbols) } guard let fn = pureSymbols[symbol] else { return .symbol(symbol, args, impureSymbols[symbol]!) } var argValues = [Double]() for arg in args { guard case let .literal(value) = arg else { return .symbol(symbol, args, fn) } argValues.append(value) } guard let result = try? fn(argValues) else { return .symbol(symbol, args, fn) } return .literal(result) } } // Produce a printable number, without redundant decimal places private func stringify(_ number: Double) -> String { if let int = Int64(exactly: number) { return "\(int)" } return "\(number)" } // Escape unprintable characters in a parsed symbol name private func demangle(_ symbolName: String) -> String { guard let delimiter = symbolName.first, "`'\"".contains(delimiter), symbolName.count > 1, symbolName.last == delimiter else { return symbolName } var result = "\(delimiter)" for char in symbolName.unicodeScalars.dropFirst().dropLast() { switch char.value { case 0: result += "\\0" case 9: result += "\\t" case 10: result += "\\n" case 13: result += "\\r" case 0x20 ..< 0x7F, _ where isOperator(char) || isIdentifier(char): result.append(Character(char)) default: result += "\\u{\(String(format: "%X", char.value))}" } } result.append(delimiter) return result } private let placeholder: Expression.SymbolEvaluator = { _ in preconditionFailure() } private let assignmentOperators = Set([ "=", "*=", "/=", "%=", "+=", "-=", "<<=", ">>=", "&=", "^=", "|=", ":=", ]) private let comparisonOperators = Set([ "<", "<=", ">=", ">", "==", "!=", "<>", "===", "!==", "lt", "le", "lte", "gt", "ge", "gte", "eq", "ne", ]) private func op(_ lhs: String, takesPrecedenceOver rhs: String) -> Bool { // https://github.com/apple/swift-evolution/blob/master/proposals/0077-operator-precedence.md func precedence(of op: String) -> Int { switch op { case "<<", ">>", ">>>": // bitshift return 2 case "*", "/", "%", "&": // multiplication return 1 case "..", "...", "..<": // range formation return -1 case "is", "as", "isa": // casting return -2 case "??", "?:": // null-coalescing return -3 case _ where comparisonOperators.contains(op): // comparison return -4 case "&&", "and": // and return -5 case "||", "or": // or return -6 case "?", ":": // ternary return -7 case _ where assignmentOperators.contains(op): // assignment return -8 case ",": return -100 default: // +, -, |, ^, etc return 0 } } func isRightAssociative(_ op: String) -> Bool { return comparisonOperators.contains(op) || assignmentOperators.contains(op) } let p1 = precedence(of: lhs) let p2 = precedence(of: rhs) if p1 == p2 { return !isRightAssociative(lhs) } return p1 > p2 } private func isOperator(_ char: UnicodeScalar) -> Bool { // Strangely, this is faster than switching on value if "/=­+!*%<>&|^~?:".unicodeScalars.contains(char) { return true } switch char.value { case 0x00A1 ... 0x00A7, 0x00A9, 0x00AB, 0x00AC, 0x00AE, 0x00B0 ... 0x00B1, 0x00B6, 0x00BB, 0x00BF, 0x00D7, 0x00F7, 0x2016 ... 0x2017, 0x2020 ... 0x2027, 0x2030 ... 0x203E, 0x2041 ... 0x2053, 0x2055 ... 0x205E, 0x2190 ... 0x23FF, 0x2500 ... 0x2775, 0x2794 ... 0x2BFF, 0x2E00 ... 0x2E7F, 0x3001 ... 0x3003, 0x3008 ... 0x3030: return true default: return false } } private func isIdentifierHead(_ c: UnicodeScalar) -> Bool { switch c.value { case 0x5F, 0x23, 0x24, 0x40, // _ # $ @ 0x41 ... 0x5A, // A-Z 0x61 ... 0x7A, // a-z 0x00A8, 0x00AA, 0x00AD, 0x00AF, 0x00B2 ... 0x00B5, 0x00B7 ... 0x00BA, 0x00BC ... 0x00BE, 0x00C0 ... 0x00D6, 0x00D8 ... 0x00F6, 0x00F8 ... 0x00FF, 0x0100 ... 0x02FF, 0x0370 ... 0x167F, 0x1681 ... 0x180D, 0x180F ... 0x1DBF, 0x1E00 ... 0x1FFF, 0x200B ... 0x200D, 0x202A ... 0x202E, 0x203F ... 0x2040, 0x2054, 0x2060 ... 0x206F, 0x2070 ... 0x20CF, 0x2100 ... 0x218F, 0x2460 ... 0x24FF, 0x2776 ... 0x2793, 0x2C00 ... 0x2DFF, 0x2E80 ... 0x2FFF, 0x3004 ... 0x3007, 0x3021 ... 0x302F, 0x3031 ... 0x303F, 0x3040 ... 0xD7FF, 0xF900 ... 0xFD3D, 0xFD40 ... 0xFDCF, 0xFDF0 ... 0xFE1F, 0xFE30 ... 0xFE44, 0xFE47 ... 0xFFFD, 0x10000 ... 0x1FFFD, 0x20000 ... 0x2FFFD, 0x30000 ... 0x3FFFD, 0x40000 ... 0x4FFFD, 0x50000 ... 0x5FFFD, 0x60000 ... 0x6FFFD, 0x70000 ... 0x7FFFD, 0x80000 ... 0x8FFFD, 0x90000 ... 0x9FFFD, 0xA0000 ... 0xAFFFD, 0xB0000 ... 0xBFFFD, 0xC0000 ... 0xCFFFD, 0xD0000 ... 0xDFFFD, 0xE0000 ... 0xEFFFD: return true default: return false } } private func isIdentifier(_ c: UnicodeScalar) -> Bool { switch c.value { case 0x30 ... 0x39, // 0-9 0x0300 ... 0x036F, 0x1DC0 ... 0x1DFF, 0x20D0 ... 0x20FF, 0xFE20 ... 0xFE2F: return true default: return isIdentifierHead(c) } } // Workaround for horribly slow Substring.UnicodeScalarView perf private struct UnicodeScalarView { public typealias Index = String.UnicodeScalarView.Index private let characters: String.UnicodeScalarView public private(set) var startIndex: Index public private(set) var endIndex: Index public init(_ unicodeScalars: String.UnicodeScalarView) { characters = unicodeScalars startIndex = characters.startIndex endIndex = characters.endIndex } public init(_ unicodeScalars: Substring.UnicodeScalarView) { self.init(String.UnicodeScalarView(unicodeScalars)) } public init(_ string: String) { self.init(string.unicodeScalars) } public var first: UnicodeScalar? { return isEmpty ? nil : characters[startIndex] } public var isEmpty: Bool { return startIndex >= endIndex } public subscript(_ index: Index) -> UnicodeScalar { return characters[index] } public func index(after index: Index) -> Index { return characters.index(after: index) } public func prefix(upTo index: Index) -> UnicodeScalarView { var view = UnicodeScalarView(characters) view.startIndex = startIndex view.endIndex = index return view } public func suffix(from index: Index) -> UnicodeScalarView { var view = UnicodeScalarView(characters) view.startIndex = index view.endIndex = endIndex return view } public mutating func popFirst() -> UnicodeScalar? { if isEmpty { return nil } let char = characters[startIndex] startIndex = characters.index(after: startIndex) return char } /// Returns the remaining characters fileprivate var unicodeScalars: Substring.UnicodeScalarView { return characters[startIndex ..< endIndex] } } private typealias _UnicodeScalarView = UnicodeScalarView private extension String { init(_ unicodeScalarView: _UnicodeScalarView) { self.init(unicodeScalarView.unicodeScalars) } } private extension Substring.UnicodeScalarView { init(_ unicodeScalarView: _UnicodeScalarView) { self.init(unicodeScalarView.unicodeScalars) } } // Expression parsing logic private extension UnicodeScalarView { mutating func scanCharacters(_ matching: (UnicodeScalar) -> Bool) -> String? { var index = startIndex while index < endIndex { if !matching(self[index]) { break } index = self.index(after: index) } if index > startIndex { let string = String(prefix(upTo: index)) self = suffix(from: index) return string } return nil } mutating func scanCharacter(_ matching: (UnicodeScalar) -> Bool = { _ in true }) -> String? { if let c = first, matching(c) { self = suffix(from: index(after: startIndex)) return String(c) } return nil } mutating func scanCharacter(_ character: UnicodeScalar) -> Bool { return scanCharacter({ $0 == character }) != nil } mutating func scanToEndOfToken() -> String? { return scanCharacters({ switch $0 { case " ", "\t", "\n", "\r": return false default: return true } }) } mutating func skipWhitespace() -> Bool { if let _ = scanCharacters({ switch $0 { case " ", "\t", "\n", "\r": return true default: return false } }) { return true } return false } mutating func parseDelimiter(_ delimiters: [String]) -> Bool { outer: for delimiter in delimiters { let start = self for char in delimiter.unicodeScalars { guard scanCharacter(char) else { self = start continue outer } } self = start return true } return false } mutating func parseNumericLiteral() -> Subexpression? { func scanInteger() -> String? { return scanCharacters { if case "0" ... "9" = $0 { return true } return false } } func scanHex() -> String? { return scanCharacters { switch $0 { case "0" ... "9", "A" ... "F", "a" ... "f": return true default: return false } } } func scanExponent() -> String? { let start = self if let e = scanCharacter({ $0 == "e" || $0 == "E" }) { let sign = scanCharacter({ $0 == "-" || $0 == "+" }) ?? "" if let exponent = scanInteger() { return e + sign + exponent } } self = start return nil } func scanNumber() -> String? { var number: String var endOfInt = self if let integer = scanInteger() { if integer == "0", scanCharacter("x") { return "0x\(scanHex() ?? "")" } endOfInt = self if scanCharacter(".") { guard let fraction = scanInteger() else { self = endOfInt return integer } number = "\(integer).\(fraction)" } else { number = integer } } else if scanCharacter(".") { guard let fraction = scanInteger() else { self = endOfInt return nil } number = ".\(fraction)" } else { return nil } if let exponent = scanExponent() { number += exponent } return number } guard let number = scanNumber() else { return nil } guard let value = Double(number) else { return .error(.unexpectedToken(number), number) } return .literal(value) } mutating func parseOperator() -> Subexpression? { if var op = scanCharacters({ $0 == "." }) ?? scanCharacters({ $0 == "-" }) { if let tail = scanCharacters(isOperator) { op += tail } return .symbol(.infix(op), [], placeholder) } if let op = scanCharacters(isOperator) ?? scanCharacter({ "([,".unicodeScalars.contains($0) }) { return .symbol(.infix(op), [], placeholder) } return nil } mutating func parseIdentifier() -> Subexpression? { func scanIdentifier() -> String? { var start = self var identifier = "" if scanCharacter(".") { identifier = "." } else if let head = scanCharacter(isIdentifierHead) { identifier = head start = self if scanCharacter(".") { identifier.append(".") } } else { return nil } while let tail = scanCharacters(isIdentifier) { identifier += tail start = self if scanCharacter(".") { identifier.append(".") } } if identifier.hasSuffix(".") { self = start if identifier == "." { return nil } identifier = String(identifier.unicodeScalars.dropLast()) } else if scanCharacter("'") { identifier.append("'") } return identifier } guard let identifier = scanIdentifier() else { return nil } return .symbol(.variable(identifier), [], placeholder) } mutating func parseEscapedIdentifier() -> Subexpression? { guard let delimiter = first, var string = scanCharacter({ "`'\"".unicodeScalars.contains($0) }) else { return nil } while let part = scanCharacters({ $0 != delimiter && $0 != "\\" }) { string += part if scanCharacter("\\"), let c = popFirst() { switch c { case "0": string += "\0" case "t": string += "\t" case "n": string += "\n" case "r": string += "\r" case "u" where scanCharacter("{"): let hex = scanCharacters({ switch $0 { case "0" ... "9", "A" ... "F", "a" ... "f": return true default: return false } }) ?? "" guard scanCharacter("}") else { guard let junk = scanToEndOfToken() else { return .error(.missingDelimiter("}"), string) } return .error(.unexpectedToken(junk), string) } guard !hex.isEmpty else { return .error(.unexpectedToken("}"), string) } guard let codepoint = Int(hex, radix: 16), let c = UnicodeScalar(codepoint) else { // TODO: better error for invalid codepoint? return .error(.unexpectedToken(hex), string) } string.append(Character(c)) default: string.append(Character(c)) } } } guard scanCharacter(delimiter) else { return .error(string == String(delimiter) ? .unexpectedToken(string) : .missingDelimiter(String(delimiter)), string) } string.append(Character(delimiter)) return .symbol(.variable(string), [], placeholder) } mutating func parseSubexpression(upTo delimiters: [String]) throws -> Subexpression { var stack: [Subexpression] = [] func collapseStack(from i: Int) throws { guard stack.count > i + 1 else { return } let lhs = stack[i] let rhs = stack[i + 1] if lhs.isOperand { if rhs.isOperand { guard case let .symbol(.postfix(op), args, _) = lhs else { // Cannot follow an operand throw Expression.Error.unexpectedToken("\(rhs)") } // Assume postfix operator was actually an infix operator stack[i] = args[0] stack.insert(.symbol(.infix(op), [], placeholder), at: i + 1) try collapseStack(from: i) } else if case let .symbol(symbol, _, _) = rhs { switch symbol { case _ where stack.count <= i + 2, .postfix: stack[i ... i + 1] = [.symbol(.postfix(symbol.name), [lhs], placeholder)] try collapseStack(from: 0) default: let rhs = stack[i + 2] if rhs.isOperand { if stack.count > i + 3 { let rhs = stack[i + 3] guard !rhs.isOperand, case let .symbol(.infix(op2), _, _) = rhs, op(symbol.name, takesPrecedenceOver: op2) else { try collapseStack(from: i + 2) return } } if symbol.name == ":", case let .symbol(.infix("?"), args, _) = lhs { // ternary stack[i ... i + 2] = [.symbol(.infix("?:"), [args[0], args[1], rhs], placeholder)] } else { stack[i ... i + 2] = [.symbol(.infix(symbol.name), [lhs, rhs], placeholder)] } try collapseStack(from: 0) } else if case let .symbol(symbol2, _, _) = rhs { if case .prefix = symbol2 { try collapseStack(from: i + 2) } else if ["+", "/", "*"].contains(symbol.name) { // Assume infix stack[i + 2] = .symbol(.prefix(symbol2.name), [], placeholder) try collapseStack(from: i + 2) } else { // Assume postfix stack[i + 1] = .symbol(.postfix(symbol.name), [], placeholder) try collapseStack(from: i) } } else if case let .error(error, _) = rhs { throw error } } } else if case let .error(error, _) = rhs { throw error } } else if case let .symbol(symbol, _, _) = lhs { // Treat as prefix operator if rhs.isOperand { stack[i ... i + 1] = [.symbol(.prefix(symbol.name), [rhs], placeholder)] try collapseStack(from: 0) } else if case .symbol = rhs { // Nested prefix operator? try collapseStack(from: i + 1) } else if case let .error(error, _) = rhs { throw error } } else if case let .error(error, _) = lhs { throw error } } _ = skipWhitespace() var operandPosition = true var precededByWhitespace = true while !parseDelimiter(delimiters), let expression = parseNumericLiteral() ?? parseIdentifier() ?? parseOperator() ?? parseEscapedIdentifier() { // Prepare for next iteration var followedByWhitespace = skipWhitespace() || isEmpty switch expression { case let .symbol(.infix(name), _, _): switch name { case "(": switch stack.last { case let .symbol(.variable(name), _, _)?: var args = [Subexpression]() if first != ")" { repeat { do { try args.append(parseSubexpression(upTo: [",", ")"])) } catch Expression.Error.unexpectedToken("") { throw Expression.Error.unexpectedToken(scanCharacter() ?? "") } } while scanCharacter(",") } stack[stack.count - 1] = .symbol( .function(name, arity: .exactly(args.count)), args, placeholder ) case let last? where last.isOperand: throw Expression.Error.unexpectedToken("(") default: try stack.append(parseSubexpression(upTo: [")"])) } guard scanCharacter(")") else { throw Expression.Error.missingDelimiter(")") } operandPosition = false followedByWhitespace = skipWhitespace() case ",": operandPosition = true if let last = stack.last, !last.isOperand, case let .symbol(.infix(op), _, _) = last { // If previous token was an infix operator, convert it to postfix stack[stack.count - 1] = .symbol(.postfix(op), [], placeholder) } stack.append(expression) case "[": guard case let .symbol(.variable(name), _, _)? = stack.last else { throw Expression.Error.unexpectedToken("[") } operandPosition = true do { let index = try parseSubexpression(upTo: [",", "]"]) guard scanCharacter("]") else { if scanCharacter(",") { throw Expression.Error.arityMismatch(.array(name)) } throw Expression.Error.missingDelimiter("]") } stack[stack.count - 1] = .symbol(.array(name), [index], placeholder) } catch Expression.Error.unexpectedToken("") { guard scanCharacter("]") else { throw Expression.Error.missingDelimiter("]") } throw Expression.Error.unexpectedToken("]") } default: operandPosition = true switch (precededByWhitespace, followedByWhitespace) { case (true, true), (false, false): stack.append(expression) case (true, false): stack.append(.symbol(.prefix(name), [], placeholder)) case (false, true): stack.append(.symbol(.postfix(name), [], placeholder)) } } case let .symbol(.variable(name), _, _) where !operandPosition: operandPosition = true stack.append(.symbol(.infix(name), [], placeholder)) default: operandPosition = false stack.append(expression) } // Next iteration precededByWhitespace = followedByWhitespace } // Check for trailing junk let start = self if !parseDelimiter(delimiters), let junk = scanToEndOfToken() { self = start throw Expression.Error.unexpectedToken(junk) } try collapseStack(from: 0) switch stack.first { case let .error(error, _)?: throw error case let result?: if result.isOperand { return result } throw Expression.Error.unexpectedToken(result.description) case nil: // Empty expression throw Expression.Error.unexpectedToken("") } } } /// Wrapper for Expression that works with any type of value public struct AnyExpression: CustomStringConvertible { private let expression: Expression private let evaluator: () throws -> Any /// Function prototype for evaluating an expression /// Return nil for an unrecognized symbol, or throw an error if the symbol is recognized /// but there is some other problem (e.g. wrong number or type of arguments) public typealias Evaluator = (_ symbol: Symbol, _ args: [Any]) throws -> Any? /// Evaluator for individual symbols public typealias SymbolEvaluator = (_ args: [Any]) throws -> Any /// Symbols that make up an expression public typealias Symbol = Expression.Symbol /// Runtime error when parsing or evaluating an expression public typealias Error = Expression.Error /// Options for configuring an expression public typealias Options = Expression.Options /// Creates an Expression object from a string /// Optionally accepts some or all of: /// - A set of options for configuring expression behavior /// - A dictionary of constants for simple static values (including arrays) /// - A dictionary of symbols, for implementing custom functions and operators /// - A custom evaluator function for more complex symbol processing public init( _ expression: String, options: Options = .boolSymbols, constants: [String: Any] = [:], symbols: [Symbol: SymbolEvaluator] = [:], evaluator: Evaluator? = nil ) { self.init( Expression.parse(expression), options: options, constants: constants, symbols: symbols, evaluator: evaluator ) } /// Alternative constructor that accepts a pre-parsed expression public init( _ expression: ParsedExpression, options: Options = .boolSymbols, constants: [String: Any] = [:], symbols: [Symbol: SymbolEvaluator] = [:], evaluator: Evaluator? = nil ) { let mask = (-Double.nan).bitPattern var values = [Any]() func store(_ value: Any) -> Double { switch value { case is Bool: break case let doubleValue as Double: return doubleValue case let floatValue as Float: return Double(floatValue) case is Int, is UInt, is Int32, is UInt32: return Double(truncating: value as! NSNumber) case let uintValue as UInt64: if uintValue <= 9007199254740992 as UInt64 { return Double(uintValue) } case let intValue as Int64: if intValue <= 9007199254740992 as Int64, intValue >= -9223372036854775808 as Int64 { return Double(intValue) } case let numberValue as NSNumber: // Hack to avoid losing type info for UIFont.Weight, etc if "\(value)".contains("rawValue") { break } return Double(truncating: numberValue) default: break } var index: Int? if AnyExpression.isNil(value) { index = values.index(where: { AnyExpression.isNil($0) }) } else if let lhs = value as? AnyHashable { index = values.index(where: { $0 as? AnyHashable == lhs }) } else if let lhs = value as? [AnyHashable] { index = values.index(where: { ($0 as? [AnyHashable]).map { $0 == lhs } ?? false }) } if index == nil { values.append(value) index = values.count - 1 } return Double(bitPattern: UInt64(index! + 1) | mask) } func load(_ arg: Double) -> Any? { let bits = arg.bitPattern if bits & mask == mask { let index = Int(bits ^ mask) - 1 if index >= 0, index < values.count { return values[index] } } return nil } // Handle string literals and constants var numericConstants = [String: Double]() var arrayConstants = [String: [Double]]() var pureSymbols = [Symbol: ([Double]) throws -> Double]() var impureSymbols = [Symbol: ([Any]) throws -> Any]() for symbol in expression.symbols { switch symbol { case let .variable(name): if let value = constants[name] { numericConstants[name] = store(value) } else if let fn = symbols[symbol] { impureSymbols[symbol] = fn } else if name == "nil" { numericConstants["nil"] = store(nil as Any? as Any) } else if name == "false" { numericConstants["false"] = store(false) } else if name == "true" { numericConstants["true"] = store(true) } else if name.count >= 2, "'\"".contains(name.first!), name.last == name.first { numericConstants[name] = store(String(name.dropFirst().dropLast())) } case let .array(name): if let array = constants[name] as? [Any] { arrayConstants[name] = array.map { store($0) } } else if let fn = symbols[symbol] { impureSymbols[symbol] = fn } case .infix("??"): // Not sure why anyone would override this, but the option is there if let fn = symbols[symbol] { impureSymbols[symbol] = fn break } // Note: the ?? operator should be safe to inline, as it doesn't store any // values, but symbols which store values cannot be safely inlined since they // are potentially side-effectful, which is why they are currently declared // in the evaluator function below instead of here pureSymbols[symbol] = { args in let lhs = args[0] return load(lhs).map { AnyExpression.isNil($0) ? args[1] : lhs } ?? lhs } // TODO: literal string as function (formatted string)? default: if let fn = symbols[symbol] { impureSymbols[symbol] = fn } } } // These are constant values that won't change between evaluations // and won't be re-stored, so must not be cleared let literals = values // Set description based on the parsed expression, prior to // peforming optimizations. This avoids issues with inlined // constants and string literals being converted to `nan` description = expression.description // Build Expression let expression = Expression( expression, options: options.subtracting(.boolSymbols).union(.pureSymbols), constants: numericConstants, arrays: arrayConstants, symbols: pureSymbols) { symbol, args in var stored = false let anyArgs: [Any] = args.map { if let value = load($0) { stored = true return value } return $0 } if let value = try impureSymbols[symbol]?(anyArgs) ?? evaluator?(symbol, anyArgs) { return store(value) } func doubleArgs() throws -> [Double]? { guard stored else { return args } var doubleArgs = [Double]() for arg in anyArgs { guard let doubleValue = arg as? Double ?? (arg as? NSNumber).map({ Double(truncating: $0) }) else { _ = try AnyExpression.unwrap(arg) return nil } doubleArgs.append(doubleValue) } return doubleArgs } if let fn = Expression.mathSymbols[symbol] { if let args = try doubleArgs() { // The arguments are all numbers, but we're going to // potentially lose precision by converting them to doubles // TODO: find alternative approach that doesn't lose precision return stored ? try fn(args) : nil } else if case .infix("+") = symbol { switch try (AnyExpression.unwrap(anyArgs[0]), AnyExpression.unwrap(anyArgs[1])) { case let (lhs as String, rhs): return try store("\(lhs)\(AnyExpression.stringify(rhs))") case let (lhs, rhs as String): return try store("\(AnyExpression.stringify(lhs))\(rhs)") default: break } } } else if options.contains(.boolSymbols), let fn = Expression.boolSymbols[symbol] { switch symbol { case .infix("==") where !(anyArgs[0] is Double) || !(anyArgs[1] is Double): return store(args[0].bitPattern == args[1].bitPattern) case .infix("!=") where !(anyArgs[0] is Double) || !(anyArgs[1] is Double): return store(args[0].bitPattern != args[1].bitPattern) case .infix("?:"): guard anyArgs.count == 3 else { return nil } if let number = anyArgs[0] as? NSNumber { return Double(truncating: number) != 0 ? args[1] : args[2] } default: if let args = try doubleArgs() { // Use Expression Bool functions, but convert results to actual Bools // See note above about precision return try store(fn(args) != 0) } } } else { // Fall back to Expression symbol handler return nil } throw Error.message("\(symbol) cannot be used with arguments of type" + "(\(anyArgs.map { "\(type(of: $0))" }.joined(separator: ", ")))") } self.evaluator = { defer { values = literals } let value = try expression.evaluate() return load(value) ?? value } self.expression = expression } /// Evaluate the expression public func evaluate<T>() throws -> T { guard let value: T = try AnyExpression.cast(evaluator()) else { throw Error.message("Unexpected nil return value") } return value } /// All symbols used in the expression public var symbols: Set<Symbol> { return expression.symbols } /// Returns the optmized, pretty-printed expression if it was valid /// Otherwise, returns the original (invalid) expression string public let description: String } // Private API private extension AnyExpression { // Convert any object to a string static func stringify(_ value: Any) throws -> String { switch try unwrap(value) { case let bool as Bool: return bool ? "true" : "false" case let number as NSNumber: if let int = Int64(exactly: number) { return "\(int)" } if let uint = UInt64(exactly: number) { return "\(uint)" } return "\(number)" case let value: return "\(value)" } } // Cast a value static func cast<T>(_ anyValue: Any) throws -> T? { if let value = anyValue as? T { return value } switch T.self { case let type as _Optional.Type where anyValue is NSNull: return type.nullValue as? T case is Double.Type, is Optional<Double>.Type: if let value = anyValue as? NSNumber { return Double(truncating: value) as? T } case is Int.Type, is Optional<Int>.Type: if let value = anyValue as? NSNumber { return Int(truncating: value) as? T } case is Bool.Type, is Optional<Bool>.Type: if let value = anyValue as? NSNumber { return (Double(truncating: value) != 0) as? T } case is String.Type: return try stringify(anyValue) as? T default: break } if isNil(anyValue) { return nil } throw AnyExpression.Error.message("mismatch: \(type(of: anyValue)) and not \(T.self)") } // Unwraps a potentially optional value or throws if nil static func unwrap(_ value: Any) throws -> Any { switch value { case let optional as _Optional: guard let value = optional.value else { fallthrough } return try unwrap(value) case is NSNull: throw AnyExpression.Error.message("Unexpected nil value") default: return value } } // Test if a value is nil static func isNil(_ value: Any) -> Bool { if let optional = value as? _Optional { guard let value = optional.value else { return true } return isNil(value) } return value is NSNull } } // Used to test if a value is Optional private protocol _Optional { var value: Any? { get } static var nullValue: Any { get } } extension Optional: _Optional { fileprivate var value: Any? { return self } static var nullValue: Any { return none as Any } } //#endif
32.50826
100
0.589311
eb7f943280218735272988d82c75c1928998429f
478
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Sundial", platforms: [ .iOS(.v9) ], products: [ .library(name: "Sundial", targets: ["Sundial"]) ], dependencies: [ .package(url: "https://github.com/netcosports/Astrolabe.git", .upToNextMajor(from: "5.1.0")) ], targets: [ .target(name: "Sundial", dependencies: ["Astrolabe"], path: "./Sources") ], swiftLanguageVersions: [.v5] )
22.761905
98
0.59205
7505904c88fed38a95e526fdca511cf3e3c23740
5,263
import ArgumentParser import Foundation import AdventKit class Cup: Equatable { static func == (lhs: Cup, rhs: Cup) -> Bool { lhs.label == rhs.label } init(label: Int) { self.label = label } var label: Int var next: Cup? var previous: Cup? } class Cups: CustomStringConvertible { var currentCup: Cup? var destination: Cup? var tail: Cup? var cupOne: Cup? var cupCount = 0 init(input: [Int]) { for i in 0..<input.count { self.append(value: input[i]) } for i in (input.count)...1_000 { self.append(value: i ) } } public func move() { } public func cupAt(index: Int) -> Cup? { // index has to be bigger than zero if index >= 0 { // I start with head, my current cup var cup = currentCup var i = index // decrementing of i steps until I get while cup != nil { if i == 0 { //print("return cup at \(index) ") return cup } i -= 1 cup = cup!.next } } // not found return nil } public func append(value: Int) { cupCount += 1 let newCup = Cup(label: value) if let lastCup = tail { newCup.previous = lastCup lastCup.next = newCup } else { currentCup = newCup } tail = newCup } public func contains(_ label: Int) -> Bool { var node = currentCup while node != nil { if node?.label == label { return true } node = node!.next } return false } public var description: String { var text = "" var node = currentCup for _ in 0..<cupCount { text += "\(node!.label)" node = node!.next } return text } } // Define our parser. struct Day23: ParsableCommand { //Declare optional argument. Drag the input file to terminal! @Option(name: [.short, .customLong("inputFile")], help: "Specify the path to the input file.") var inputFile : String = "" func run() throws { var input: String = "" if !inputFile.isEmpty { let url = URL(fileURLWithPath: inputFile) guard let inputFile = try? String(contentsOf: url) else {fatalError()} input = inputFile } else { print("Running Day23 Challenge with input from the website\n") let inputFile = "389125467" // example //guard let inputFile = "872495136" input = inputFile } print(input) //The crab is going to hide your stars - one each - under the two cups that will end up immediately clockwise of cup 1. You can have them if you predict what the labels on those cups will be when the crab is finished. //In the above example (389125467), this would be 934001 and then 159792; multiplying these together produces 149245887792. input = "389125467" // test! //input = "872495136" let inputLabels = Array(input.map {Int(String($0))!}) print(inputLabels) let game = Cups(input: inputLabels) game.tail?.next = game.currentCup game.currentCup?.previous = game.tail func move() { print("currentCup \(game.currentCup!.label)") // game.currentCup?.label // game.tail?.label // game.tail?.next?.label // game.cupAt(index: 0)!.label // currentcup // game.cupAt(index: 10)!.label // currentcup var pickedCupsArray: [Int] = [] for i in 1...3 { pickedCupsArray.append(game.cupAt(index: i)!.label) } // pickedCupsArray let threeCups = Cups(input: pickedCupsArray) var next = game.cupAt(index: 4)! // next.label // threeCups.description // threeCups.currentCup?.label //8 // threeCups.tail?.label //1 // make the cut - just taking away the three cups at this stage game.currentCup!.next = next // game.currentCup!.next?.label // 2 // look for destination cup - (currentLabel - 1) in cups var currentLabelMinusOne = game.currentCup!.label - 1 game.destination = nil // first I look in the cups I have from next to the current one while true { // check my destination is more than zero or I start wrapping the highest if currentLabelMinusOne == 0 { currentLabelMinusOne = 1_000 } print("looking for", currentLabelMinusOne, "and next is ", next.label) // check if currentLabelMinusOne is in picked up cups if so decrease if threeCups.cupAt(index: 0)?.label == currentLabelMinusOne || threeCups.cupAt(index: 1)?.label == currentLabelMinusOne || threeCups.cupAt(index: 2)?.label == currentLabelMinusOne { print("contained in picked cups!") // if found then I decrease currentLabelMinusOne -= 1; continue } // check for destination if currentLabelMinusOne == next.label { game.destination = next print("new destination \(next.label)") break } // here I did one round! if game.currentCup == next { print("I did one round!") // if not found then I decrease currentLabelMinusOne -= 1; } next = next.next! } // inserting my threeCups list let cut = game.destination!.next //print("inserting between \(game.destination!.label) and \(cut!.label)") game.destination?.next = threeCups.currentCup threeCups.tail?.next = cut // new currentcup is right on the next cup game.currentCup = game.currentCup?.next print("new current cup \(game.currentCup!.label)") // game.currentCup?.label } for i in 0..<10 { print("-- move \(i + 1) --") move() } //let one = game let solution = 0 print("solution ", solution) } } // Run the parser. Day23.main()
25.673171
219
0.65381
61a4becbcba4d307ac89511c25e979b0aa5f1716
187
// // Weather.swift // SwiftUIWeather // // Created by Abhiroop Patel on 01/10/20. // import Foundation struct Weather: Decodable { var temp: Double? var humidity: Double? }
13.357143
42
0.663102
6aa8299d5a70975ec2c9e8ac62919c5e0602dc91
674
// // Proxy.swift // Terra // // Created by DATree on 2019/12/26. // import Foundation public struct TerraWrapper<Base> { public let base: Base public init(_ base: Base) { self.base = base } } public protocol TerraCompatible { associatedtype Base static var terra: TerraWrapper<Base>.Type { get set } var terra: TerraWrapper<Base> { get set } } extension TerraCompatible { public static var terra: TerraWrapper<Self>.Type { get { return TerraWrapper<Self>.self } set { } } public var terra: TerraWrapper<Self> { get { return TerraWrapper(self) } set { } } } public struct Terra {}
18.722222
57
0.623145
f5a1ce49a65ccdc9aea5a28ca27803df777411c4
12,784
@testable import WMF import XCTest class NotificationServiceHelperTest: XCTestCase { private let testUsername1 = "Test Username" private let testUsername2 = "Test Username 2" var userOneTalkPageNotifications: [RemoteNotificationsAPIController.NotificationsResult.Notification] { let dateSevenMinutesAgo = Date(timeInterval: -TimeInterval.sevenMinutes, since: Date()) let dateEightMinutesAgo = Date(timeInterval: -TimeInterval.eightMinutes, since: Date()) guard let notification1 = standardUserTalkMessageNotification(date: dateEightMinutesAgo), let notification2 = standardUserTalkMessageNotification(date: dateSevenMinutesAgo) else { return [] } return [notification1, notification2] } var userTwoTalkPageNotifications: [RemoteNotificationsAPIController.NotificationsResult.Notification] { let dateSixMinutesAgo = Date(timeInterval: -TimeInterval.sixMinutes, since: Date()) guard let notification = RemoteNotificationsAPIController.NotificationsResult.Notification(project: .wikipedia("en", "English", nil), titleText: testUsername2, titleNamespace: .userTalk, remoteNotificationType: .userTalkPageMessage, date: dateSixMinutesAgo) else { return [] } return [notification] } 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 testAllNotificationsForSameTalkPage() throws { let dateFiveMinutesAgo = Date(timeInterval: -TimeInterval.fiveMinutes, since: Date()) guard let editRevertedNotification = RemoteNotificationsAPIController.NotificationsResult.Notification(project: .wikipedia("en", "English", nil), titleText: "Article", titleNamespace: .main, remoteNotificationType: .editReverted, date: dateFiveMinutesAgo) else { XCTFail("Failure setting up test notifications") return } let differentNotifications = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userOneTalkPageNotifications + [editRevertedNotification]) let talkPageNotificationsDifferentTitles = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userOneTalkPageNotifications + userTwoTalkPageNotifications) let talkPageNotificationsSameTitles = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userOneTalkPageNotifications) XCTAssertTrue(NotificationServiceHelper.allNotificationsAreForSameTalkPage(notifications: talkPageNotificationsSameTitles), "Notifications with a talk title namespace and the same title full text values should be seen as the same.") XCTAssertFalse(NotificationServiceHelper.allNotificationsAreForSameTalkPage(notifications: talkPageNotificationsDifferentTitles), "Notifications with a talk title namespace and different title full text values should not be seen as the same.") XCTAssertFalse(NotificationServiceHelper.allNotificationsAreForSameTalkPage(notifications: differentNotifications), "Notifications of different types should not be seen as the same.") } func testTalkPageContent() { let singleTalkPageNotification = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userTwoTalkPageNotifications) XCTAssertNotNil(NotificationServiceHelper.talkPageContent(for:singleTalkPageNotification), "Talk page content should be returned for a single talk notification.") let talkPageNotificationsDifferentTitles = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userOneTalkPageNotifications + userTwoTalkPageNotifications) XCTAssertNil(NotificationServiceHelper.talkPageContent(for:talkPageNotificationsDifferentTitles), "Bundled talk page content should not be returned for notifications that originated from different talk pages.") let talkPageNotificationsSameTitles = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>(userOneTalkPageNotifications) XCTAssertNotNil(NotificationServiceHelper.talkPageContent(for:talkPageNotificationsSameTitles), "Missing bundled talk page content for notifications that originated from the same talk page.") } func testDetermineNotificationsToDisplayAndCache() { //Business logic: //Sending in a set of cached notifications (some of which are quite old) along with a set of newly fetched notifications (some of which are also quite old) with some overlap amongst both sets should return only the fetched notifications within the last 10 minutes that are not already in the cached notifications set as notifications to display. The new set of cached notifications returned should be the calculated notifications to display, plus the old cached notifications that aren't older than 1 day let dateOneYearAgo = Date(timeInterval: -TimeInterval.oneYear, since: Date()) let dateThirtyDaysAgo = Date(timeInterval: -TimeInterval.thirtyDays, since: Date()) let dateTwelveHoursAgo = Date(timeInterval: -TimeInterval.twelveHours, since: Date()) let dateTwoHoursAgo = Date(timeInterval: -TimeInterval.twoHours, since: Date()) let dateNineMinutesAgo = Date(timeInterval: -TimeInterval.nineMinutes, since: Date()) let dateSevenMinutesAgo = Date(timeInterval: -TimeInterval.sevenMinutes, since: Date()) let dateFiveMinutesAgo = Date(timeInterval: -TimeInterval.fiveMinutes, since: Date()) let commonID2hours = "commonNotification2hours" let commonID9minutes = "commonNotification9minutes" //cached notifications has a two older than one day, two within the last day (one overlaps with fetched notifications), three within the last 10 minutes (one overlaps with fetched notifications) //fetched notifications has a one older than one day, two within the last day (one overlaps with cached notifications), three within the last 10 minutes (one overlaps with cached notifications) //setup cached notifications guard let cachedOneYearAgo = standardUserTalkMessageNotification(customID: "cachedNotification1year", date: dateOneYearAgo), let cachedThirtyDaysAgo = standardUserTalkMessageNotification(customID: "cachedNotification30days", date: dateThirtyDaysAgo), let cachedTwelveHoursAgo = standardUserTalkMessageNotification(customID: "cachedNotification12hours", date: dateTwelveHoursAgo), let cachedTwoHoursAgo = standardUserTalkMessageNotification(customID: commonID2hours, date: dateTwoHoursAgo), let cachedNineMinutesAgo = standardUserTalkMessageNotification(customID: commonID9minutes, date: dateNineMinutesAgo), let cachedSevenMinutesAgo = standardUserTalkMessageNotification(customID: "cachedNotification7minutes", date: dateSevenMinutesAgo), let cachedFiveMinutesAgo = standardUserTalkMessageNotification(customID: "cachedNotification5minutes", date: dateFiveMinutesAgo) else { return } let cachedNotifications = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>([cachedOneYearAgo, cachedThirtyDaysAgo, cachedTwelveHoursAgo, cachedTwoHoursAgo, cachedNineMinutesAgo, cachedSevenMinutesAgo, cachedFiveMinutesAgo]) //setup fetched notifications //purposefully not reusing cached notifications - we should test them as separate objects between cached and fetched so that their IDs are compared for identity guard let fetchedThirtyDaysAgo = standardUserTalkMessageNotification(customID: "fetchedNotification30days", date: dateThirtyDaysAgo), let fetchedTwelveHoursAgo = standardUserTalkMessageNotification(customID: "fetchedNotification12hours", date: dateTwelveHoursAgo), let fetchedTwoHoursAgo = standardUserTalkMessageNotification(customID: commonID2hours, date: dateTwoHoursAgo), let fetchedNineMinutesAgo = standardUserTalkMessageNotification(customID: commonID9minutes, date: dateNineMinutesAgo), let fetchedSevenMinutesAgo = standardUserTalkMessageNotification(customID: "fetchedNotification7minutes", date: dateSevenMinutesAgo), let fetchedFiveMinutesAgo = standardUserTalkMessageNotification(customID: "fetchedNotification5minutes", date: dateFiveMinutesAgo) else { return } let fetchedNotifications = Set<RemoteNotificationsAPIController.NotificationsResult.Notification>([fetchedThirtyDaysAgo, fetchedTwelveHoursAgo, fetchedTwoHoursAgo, fetchedNineMinutesAgo, fetchedSevenMinutesAgo, fetchedFiveMinutesAgo]) let result = NotificationServiceHelper.determineNotificationsToDisplayAndCache(fetchedNotifications: fetchedNotifications, cachedNotifications: cachedNotifications) let newNotificationsToDisplay = result.notificationsToDisplay let newNotificationsToCache = result.notificationsToCache XCTAssert(newNotificationsToDisplay.count == 2, "Unexpected count of new notifications to display. Should be those from the last 10 minutes that were not already in cachedNotifications input.") XCTAssert(newNotificationsToDisplay.contains(fetchedFiveMinutesAgo), "Unexpected items in new notifications to display.") XCTAssert(newNotificationsToDisplay.contains(fetchedSevenMinutesAgo), "Unexpected items in new notifications to display.") XCTAssert(newNotificationsToCache.count == 7, "Unexpected count of new notifications to cache. Should be those within the last 1 day from cached notifications input, plus those from the last 10 minutes from fetched notifications input.") XCTAssert(newNotificationsToCache.contains(cachedTwelveHoursAgo), "Unexpected items in new notifications to cache.") //Note these are seen as the same identity, because they were instantiated with the same customID. XCTAssert(newNotificationsToCache.contains(cachedTwoHoursAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(fetchedTwoHoursAgo), "Unexpected items in new notifications to cache.") //Note these are seen as the same identity, because they were instantiated with the same customID. XCTAssert(newNotificationsToCache.contains(cachedNineMinutesAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(fetchedNineMinutesAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(cachedSevenMinutesAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(fetchedSevenMinutesAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(cachedFiveMinutesAgo), "Unexpected items in new notifications to cache.") XCTAssert(newNotificationsToCache.contains(fetchedFiveMinutesAgo), "Unexpected items in new notifications to cache.") } func standardUserTalkMessageNotification(customID: String? = nil, date: Date) -> RemoteNotificationsAPIController.NotificationsResult.Notification? { return RemoteNotificationsAPIController.NotificationsResult.Notification(project: .wikipedia("en", "English", nil), titleText: testUsername1, titleNamespace: .userTalk, remoteNotificationType: .userTalkPageMessage, date: date, customID: customID) } } fileprivate extension TimeInterval { static var oneYear: TimeInterval { return TimeInterval(oneDay * 365) } static var fiveMinutes: TimeInterval { return TimeInterval(oneMinute * 5) } static var sixMinutes: TimeInterval { return TimeInterval(oneMinute * 6) } static var sevenMinutes: TimeInterval { return TimeInterval(oneMinute * 7) } static var eightMinutes: TimeInterval { return TimeInterval(oneMinute * 8) } static var nineMinutes: TimeInterval { return TimeInterval(oneMinute * 9) } static var twelveHours: TimeInterval { return TimeInterval(oneHour * 12) } static var twoHours: TimeInterval { return TimeInterval(oneHour * 2) } static var thirtyDays: TimeInterval { return TimeInterval(oneDay * 30) } }
69.478261
512
0.758605
3a61ffc82b5e601dbce9266c2e60d64b646bf0c0
937
// // SwiftyLibExamplesTests.swift // SwiftyLibExamplesTests // // Created by Woody Lee on 5/19/19. // Copyright © 2019 Woody Lee. All rights reserved. // import XCTest @testable import SwiftyLibExamples class SwiftyLibExamplesTests: 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. } } }
26.771429
111
0.665955
62867bf49dc8a190c09b8e252f4165a0f5d73ba1
1,960
// // LoggerTests.swift // MixpanelDemo // // Created by Sam Green on 7/8/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import XCTest @testable import Mixpanel class LoggerTests: XCTestCase { func testEnableDebug() { let counter = CounterLogging() Logger.addLogging(counter) Logger.enableLevel(.debug) Logger.debug(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableInfo() { let counter = CounterLogging() Logger.addLogging(counter) Logger.enableLevel(.info) Logger.info(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableWarning() { let counter = CounterLogging() Logger.addLogging(counter) Logger.enableLevel(.warning) Logger.warn(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableError() { let counter = CounterLogging() Logger.addLogging(counter) Logger.enableLevel(.error) Logger.error(message: "logged") XCTAssertEqual(1, counter.count) } func testDisabledLogging() { let counter = CounterLogging() Logger.addLogging(counter) Logger.disableLevel(.debug) Logger.debug(message: "not logged") XCTAssertEqual(0, counter.count) Logger.disableLevel(.error) Logger.error(message: "not logged") XCTAssertEqual(0, counter.count) Logger.disableLevel(.info) Logger.info(message: "not logged") XCTAssertEqual(0, counter.count) Logger.disableLevel(.warning) Logger.warn(message: "not logged") XCTAssertEqual(0, counter.count) } } /// This is a stub that implements `Logging` to be passed to our `Logger` instance for testing class CounterLogging: Logging { var count = 0 func addMessage(message: LogMessage) { count = count + 1 } }
25.128205
94
0.635714
0e4e2f67e6090a48a608f31bfb73b08392aa2917
635
// // System.swift // // // Created by Rostyslav Druzhchenko on 22.03.2021. // import Foundation public class System { public static let out: PrintStream = PrintStream(FileHandle.standardOutput) public static let err: PrintStream = PrintStream(FileHandle.standardError) } public class PrintStream { private let fileHandle: FileHandle init(_ fileHandle: FileHandle) { self.fileHandle = fileHandle } public func print(_ message: String) { fileHandle.write(message.data(using: .utf8)!) } public func println(_ message: String) { print(message) print("\n") } }
19.242424
79
0.667717
7266ad875f394cebcb0a8d68300209db75df6aaa
35,174
// // ReplicatorTest.swift // CouchbaseLite // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest import CouchbaseLiteSwift class ReplicatorTest: CBLTestCase { var oDB: Database! var repl: Replicator! var timeout: TimeInterval = 10 // At least 10 to cover single-shot replicator's retry logic override func setUp() { super.setUp() try! openOtherDB() oDB = otherDB! } override func tearDown() { try! oDB.close() oDB = nil repl = nil super.tearDown() } func config(target: Endpoint, type: ReplicatorType = .pushAndPull, continuous: Bool = false, auth: Authenticator? = nil, serverCert: SecCertificate? = nil) -> ReplicatorConfiguration { let config = ReplicatorConfiguration(database: self.db, target: target) config.replicatorType = type config.continuous = continuous config.authenticator = auth config.pinnedServerCertificate = serverCert return config } #if COUCHBASE_ENTERPRISE func config(target: Endpoint, type: ReplicatorType = .pushAndPull, continuous: Bool = false, auth: Authenticator? = nil, acceptSelfSignedOnly: Bool = false, serverCert: SecCertificate? = nil) -> ReplicatorConfiguration { let config = self.config(target: target, type: type, continuous: continuous, auth: auth, serverCert: serverCert) config.acceptOnlySelfSignedServerCertificate = acceptSelfSignedOnly return config } #endif func run(config: ReplicatorConfiguration, expectedError: Int?) { run(config: config, reset: false, expectedError: expectedError) } func run(config: ReplicatorConfiguration, reset: Bool, expectedError: Int?, onReplicatorReady: ((Replicator) -> Void)? = nil) { repl = Replicator(config: config) if let ready = onReplicatorReady { ready(repl) } run(replicator: repl, reset: reset, expectedError: expectedError) } func run(target: Endpoint, type: ReplicatorType = .pushAndPull, continuous: Bool = false, auth: Authenticator? = nil, serverCert: SecCertificate? = nil, expectedError: Int? = nil) { let config = self.config(target: target, type: type, continuous: continuous, auth: auth, serverCert: serverCert) run(config: config, reset: false, expectedError: expectedError) } #if COUCHBASE_ENTERPRISE func run(target: Endpoint, type: ReplicatorType = .pushAndPull, continuous: Bool = false, auth: Authenticator? = nil, acceptSelfSignedOnly: Bool = false, serverCert: SecCertificate? = nil, expectedError: Int? = nil) { let config = self.config(target: target, type: type, continuous: continuous, auth: auth, acceptSelfSignedOnly: acceptSelfSignedOnly, serverCert: serverCert) run(config: config, reset: false, expectedError: expectedError) } #endif func run(replicator: Replicator, expectedError: Int?) { run(replicator: replicator, reset: false, expectedError: expectedError); } func run(replicator: Replicator, reset: Bool, expectedError: Int?) { let x = self.expectation(description: "change") let token = replicator.addChangeListener { (change) in let status = change.status if replicator.config.continuous && status.activity == .idle && status.progress.completed == status.progress.total { replicator.stop() } if status.activity == .stopped { let error = status.error as NSError? if let err = expectedError { XCTAssertNotNil(error) if let e = error { XCTAssertEqual(e.code, err) } } else { XCTAssertNil(error) } x.fulfill() } } if (reset) { replicator.start(reset: reset) } else { replicator.start() } wait(for: [x], timeout: timeout) if replicator.status.activity != .stopped { replicator.stop() } replicator.removeChangeListener(withToken: token) } } class ReplicatorTest_Main: ReplicatorTest { #if COUCHBASE_ENTERPRISE func testEmptyPush() throws { let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: false) run(config: config, expectedError: nil) } func testResetCheckpoint() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("striped", forKey: "pattern") try db.saveDocument(doc2) // Push: let target = DatabaseEndpoint(database: oDB) var config = self.config(target: target, type: .push, continuous: false) run(config: config, expectedError: nil) // Pull: config = self.config(target: target, type: .pull, continuous: false) run(config: config, expectedError: nil) XCTAssertEqual(db.count, 2) var doc = db.document(withID: "doc1")! try db.purgeDocument(doc) doc = db.document(withID: "doc2")! try db.purgeDocument(doc) XCTAssertEqual(db.count, 0) // Pull again, shouldn't have any new changes: run(config: config, expectedError: nil) XCTAssertEqual(db.count, 0) // Reset and pull: let replicator = Replicator.init(config: config) replicator.resetCheckpoint() run(replicator: replicator, expectedError: nil) XCTAssertEqual(db.count, 2) } func testResetCheckpointContinuous() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("striped", forKey: "pattern") try db.saveDocument(doc2) // Push: let target = DatabaseEndpoint(database: oDB) var config = self.config(target: target, type: .push, continuous: true) run(config: config, expectedError: nil) // Pull: config = self.config(target: target, type: .pull, continuous: true) run(config: config, expectedError: nil) XCTAssertEqual(db.count, 2) var doc = db.document(withID: "doc1")! try db.purgeDocument(doc) doc = db.document(withID: "doc2")! try db.purgeDocument(doc) XCTAssertEqual(db.count, 0) // Pull again, shouldn't have any new changes: run(config: config, expectedError: nil) XCTAssertEqual(db.count, 0) // Reset and pull: let replicator = Replicator.init(config: config) replicator.resetCheckpoint() run(replicator: replicator, expectedError: nil) XCTAssertEqual(db.count, 2) } func testStartWithCheckpoint() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("striped", forKey: "pattern") try db.saveDocument(doc2) // Push: let target = DatabaseEndpoint(database: oDB) var config = self.config(target: target, type: .push, continuous: false) run(config: config, expectedError: nil) // Pull: config = self.config(target: target, type: .pull, continuous: false) run(config: config, expectedError: nil) XCTAssertEqual(db.count, 2) var doc = db.document(withID: "doc1")! try db.purgeDocument(doc) doc = db.document(withID: "doc2")! try db.purgeDocument(doc) XCTAssertEqual(db.count, 0) // Pull again, shouldn't have any new changes: run(config: config, expectedError: nil) XCTAssertEqual(db.count, 0) // Reset and pull: run(config: config, reset: true, expectedError: nil) XCTAssertEqual(db.count, 2) } func testStartWithResetCheckpointContinuous() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("striped", forKey: "pattern") try db.saveDocument(doc2) // Push: let target = DatabaseEndpoint(database: oDB) var config = self.config(target: target, type: .push, continuous: true) run(config: config, expectedError: nil) // Pull: config = self.config(target: target, type: .pull, continuous: true) run(config: config, expectedError: nil) XCTAssertEqual(db.count, 2) var doc = db.document(withID: "doc1")! try db.purgeDocument(doc) doc = db.document(withID: "doc2")! try db.purgeDocument(doc) XCTAssertEqual(db.count, 0) // Pull again, shouldn't have any new changes: run(config: config, expectedError: nil) XCTAssertEqual(db.count, 0) // Reset and pull: run(config: config, reset: true, expectedError: nil) XCTAssertEqual(db.count, 2) } func testDocumentReplicationEvent() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("Striped", forKey: "pattern") try db.saveDocument(doc2) // Push: let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: false) var replicator: Replicator! var token: ListenerToken! var docs: [ReplicatedDocument] = [] self.run(config: config, reset: false, expectedError: nil) { (r) in replicator = r token = r.addDocumentReplicationListener({ (replication) in XCTAssert(replication.isPush) for doc in replication.documents { docs.append(doc) } }) } // Check if getting two document replication events: XCTAssertEqual(docs.count, 2) XCTAssertEqual(docs[0].id, "doc1") XCTAssertNil(docs[0].error) XCTAssertFalse(docs[0].flags.contains(.deleted)) XCTAssertFalse(docs[0].flags.contains(.accessRemoved)) XCTAssertEqual(docs[1].id, "doc2") XCTAssertNil(docs[1].error) XCTAssertFalse(docs[1].flags.contains(.deleted)) XCTAssertFalse(docs[1].flags.contains(.accessRemoved)) // Add another doc: let doc3 = MutableDocument(id: "doc3") doc3.setString("Tiger", forKey: "species") doc3.setString("Star", forKey: "pattern") try db.saveDocument(doc3) // Run the replicator again: self.run(replicator: replicator, expectedError: nil) // Check if getting a new document replication event: XCTAssertEqual(docs.count, 3) XCTAssertEqual(docs[2].id, "doc3") XCTAssertNil(docs[2].error) XCTAssertFalse(docs[2].flags.contains(.deleted)) XCTAssertFalse(docs[2].flags.contains(.accessRemoved)) // Add another doc: let doc4 = MutableDocument(id: "doc4") doc4.setString("Tiger", forKey: "species") doc4.setString("WhiteStriped", forKey: "pattern") try db.saveDocument(doc4) // Remove document replication listener: replicator.removeChangeListener(withToken: token) // Run the replicator again: self.run(replicator: replicator, expectedError: nil) // Should not getting a new document replication event: XCTAssertEqual(docs.count, 3) } func testDocumentReplicationEventWithPushConflict() throws { let doc1a = MutableDocument(id: "doc1") doc1a.setString("Tiger", forKey: "species") doc1a.setString("Star", forKey: "pattern") try db.saveDocument(doc1a) let doc1b = MutableDocument(id: "doc1") doc1b.setString("Tiger", forKey: "species") doc1b.setString("Striped", forKey: "pattern") try oDB.saveDocument(doc1b) // Push: let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: false) var replicator: Replicator! var token: ListenerToken! var docs: [ReplicatedDocument] = [] self.run(config: config, reset: false, expectedError: nil) { (r) in replicator = r token = r.addDocumentReplicationListener({ (replication) in XCTAssert(replication.isPush) for doc in replication.documents { docs.append(doc) } }) } // Check: XCTAssertEqual(docs.count, 1) XCTAssertEqual(docs[0].id, "doc1") XCTAssertNotNil(docs[0].error) let err = docs[0].error! as NSError XCTAssertEqual(err.domain, CBLErrorDomain) XCTAssertEqual(err.code, CBLErrorHTTPConflict) XCTAssertFalse(docs[0].flags.contains(.deleted)) XCTAssertFalse(docs[0].flags.contains(.accessRemoved)) // Remove document replication listener: replicator.removeChangeListener(withToken: token) } func testDocumentReplicationEventWithPullConflict() throws { let doc1a = MutableDocument(id: "doc1") doc1a.setString("Tiger", forKey: "species") doc1a.setString("Star", forKey: "pattern") try db.saveDocument(doc1a) let doc1b = MutableDocument(id: "doc1") doc1b.setString("Tiger", forKey: "species") doc1b.setString("Striped", forKey: "pattern") try oDB.saveDocument(doc1b) // Pull: let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .pull, continuous: false) var replicator: Replicator! var token: ListenerToken! var docs: [ReplicatedDocument] = [] self.run(config: config, reset: false, expectedError: nil) { (r) in replicator = r token = r.addDocumentReplicationListener({ (replication) in XCTAssertFalse(replication.isPush) for doc in replication.documents { docs.append(doc) } }) } // Check: XCTAssertEqual(docs.count, 1) XCTAssertEqual(docs[0].id, "doc1") XCTAssertNil(docs[0].error) XCTAssertFalse(docs[0].flags.contains(.deleted)) XCTAssertFalse(docs[0].flags.contains(.accessRemoved)) // Remove document replication listener: replicator.removeChangeListener(withToken: token) } func testDocumentReplicationEventWithDeletion() throws { let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Star", forKey: "pattern") try db.saveDocument(doc1) // Delete: try db.deleteDocument(doc1) // Push: let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: false) var replicator: Replicator! var token: ListenerToken! var docs: [ReplicatedDocument] = [] self.run(config: config, reset: false, expectedError: nil) { (r) in replicator = r token = r.addDocumentReplicationListener({ (replication) in XCTAssert(replication.isPush) for doc in replication.documents { docs.append(doc) } }) } // Check: XCTAssertEqual(docs.count, 1) XCTAssertEqual(docs[0].id, "doc1") XCTAssertNil(docs[0].error) XCTAssertTrue(docs[0].flags.contains(.deleted)) XCTAssertFalse(docs[0].flags.contains(.accessRemoved)) // Remove document replication listener: replicator.removeChangeListener(withToken: token) } func testSingleShotPushFilter() throws { try testPushFilter(false) } func testContinuousPushFilter() throws { try testPushFilter(true) } func testPushFilter(_ isContinuous: Bool) throws { // Create documents: let content = "I'm a tiger.".data(using: .utf8)! let blob = Blob(contentType: "text/plain", data: content) let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") doc1.setBlob(blob, forKey: "photo") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("Striped", forKey: "pattern") doc2.setBlob(blob, forKey: "photo") try db.saveDocument(doc2) let doc3 = MutableDocument(id: "doc3") doc3.setString("Tiger", forKey: "species") doc3.setString("Star", forKey: "pattern") doc3.setBlob(blob, forKey: "photo") try db.saveDocument(doc3) try db.deleteDocument(doc3) // Create replicator with push filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: isContinuous) config.pushFilter = { (doc, flags) in XCTAssertNotNil(doc.id) let isDeleted = flags.contains(.deleted) XCTAssert(doc.id == "doc3" ? isDeleted : !isDeleted) if !isDeleted { // Check content: XCTAssertNotNil(doc.value(forKey: "pattern")) XCTAssertEqual(doc.string(forKey: "species")!, "Tiger") // Check blob: let photo = doc.blob(forKey: "photo") XCTAssertNotNil(photo) XCTAssertEqual(photo!.content, blob.content) } else { XCTAssert(doc.toDictionary() == [:]) } // Gather document ID: docIds.add(doc.id) // Reject doc2: return doc.id == "doc2" ? false : true } // Run the replicator: run(config: config, expectedError: nil) // Check documents passed to the filter: XCTAssertEqual(docIds.count, 3) XCTAssert(docIds.contains("doc1")) XCTAssert(docIds.contains("doc2")) XCTAssert(docIds.contains("doc3")) // Check replicated documents: XCTAssertNotNil(oDB.document(withID: "doc1")) XCTAssertNil(oDB.document(withID: "doc2")) XCTAssertNil(oDB.document(withID: "doc3")) } func testPullFilter() throws { // Add a document to db database so that it can pull the deleted docs from: let doc0 = MutableDocument(id: "doc0") doc0.setString("Cat", forKey: "species") try db.saveDocument(doc0) // Create documents: let content = "I'm a tiger.".data(using: .utf8)! let blob = Blob(contentType: "text/plain", data: content) let doc1 = MutableDocument(id: "doc1") doc1.setString("Tiger", forKey: "species") doc1.setString("Hobbes", forKey: "pattern") doc1.setBlob(blob, forKey: "photo") try self.oDB.saveDocument(doc1) let doc2 = MutableDocument(id: "doc2") doc2.setString("Tiger", forKey: "species") doc2.setString("Striped", forKey: "pattern") doc2.setBlob(blob, forKey: "photo") try self.oDB.saveDocument(doc2) let doc3 = MutableDocument(id: "doc3") doc3.setString("Tiger", forKey: "species") doc3.setString("Star", forKey: "pattern") doc3.setBlob(blob, forKey: "photo") try self.oDB.saveDocument(doc3) try self.oDB.deleteDocument(doc3) // Create replicator with pull filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .pull, continuous: false) config.pullFilter = { (doc, flags) in XCTAssertNotNil(doc.id) let isDeleted = flags.contains(.deleted) XCTAssert(doc.id == "doc3" ? isDeleted : !isDeleted) if !isDeleted { // Check content: XCTAssertNotNil(doc.value(forKey: "pattern")) XCTAssertEqual(doc.string(forKey: "species")!, "Tiger") // Check blob: let photo = doc.blob(forKey: "photo") XCTAssertNotNil(photo) // Note: Cannot access content because there is no actual blob file saved on disk. // XCTAssertEqual(photo!.content, blob.content) } else { XCTAssert(doc.toDictionary() == [:]) } // Gather document ID: docIds.add(doc.id) // Reject doc2: return doc.id == "doc2" ? false : true } // Run the replicator: run(config: config, expectedError: nil) // Check documents passed to the filter: XCTAssertEqual(docIds.count, 3) XCTAssert(docIds.contains("doc1")) XCTAssert(docIds.contains("doc2")) XCTAssert(docIds.contains("doc3")) // Check replicated documents: XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNil(db.document(withID: "doc2")) XCTAssertNil(db.document(withID: "doc3")) } func testPushAndForget() throws { let doc = MutableDocument(id: "doc1") doc.setString("Tiger", forKey: "species") doc.setString("Hobbes", forKey: "pattern") try db.saveDocument(doc) let promise = expectation(description: "document expiry expectation") let docChangeToken = db.addDocumentChangeListener(withID: doc.id) { [unowned self] (change) in XCTAssertEqual(doc.id, change.documentID) if self.db.document(withID: doc.id) == nil { promise.fulfill() } } XCTAssertEqual(self.db.count, 1) XCTAssertEqual(oDB.count, 0) // Push: let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: false) var replicator: Replicator! var docReplicationToken: ListenerToken! self.run(config: config, reset: false, expectedError: nil) { [unowned self] (r) in replicator = r docReplicationToken = r.addDocumentReplicationListener({ [unowned self] (replication) in try! self.db.setDocumentExpiration(withID: doc.id, expiration: Date()) }) } waitForExpectations(timeout: 5.0) replicator.removeChangeListener(withToken: docReplicationToken) db.removeChangeListener(withToken: docChangeToken); XCTAssertEqual(self.db.count, 0) XCTAssertEqual(oDB.count, 1) } // MARK: Removed Doc with Filter func testPullRemovedDocWithFilterSingleShot() throws { try testPullRemovedDocWithFilter(false) } func testPullRemovedDocWithFilterContinuous() throws { try testPullRemovedDocWithFilter(true) } func testPullRemovedDocWithFilter(_ isContinuous: Bool) throws { // Create documents: let doc1 = MutableDocument(id: "doc1") doc1.setString("pass", forKey: "name") try oDB.saveDocument(doc1) let doc2 = MutableDocument(id: "pass") doc2.setString("pass", forKey: "name") try oDB.saveDocument(doc2) // Create replicator with push filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .pull, continuous: isContinuous) config.pullFilter = { (doc, flags) in XCTAssertNotNil(doc.id) let isAccessRemoved = flags.contains(.accessRemoved) if isAccessRemoved { docIds.add(doc.id) return doc.id == "pass" } return doc.string(forKey: "name") == "pass" } // Run the replicator: run(config: config, expectedError: nil) XCTAssertEqual(docIds.count, 0) XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNotNil(db.document(withID: "pass")) guard let doc1Mutable = oDB.document(withID: "doc1")?.toMutable() else { fatalError("Docs must exists") } doc1Mutable.setData(["_removed": true]) try oDB.saveDocument(doc1Mutable) guard let doc2Mutable = oDB.document(withID: "pass")?.toMutable() else { fatalError("Docs must exists") } doc2Mutable.setData(["_removed": true]) try oDB.saveDocument(doc2Mutable) run(config: config, expectedError: nil) // Check documents passed to the filter: XCTAssertEqual(docIds.count, 2) XCTAssert(docIds.contains("doc1")) XCTAssert(docIds.contains("pass")) XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNil(db.document(withID: "pass")) } // MARK: Deleted Doc with Filter func testPushDeletedDocWithFilterSingleShot() throws { try testPushDeletedDocWithFilter(false) } func testPushDeletedDocWithFilterContinuous() throws { try testPushDeletedDocWithFilter(true) } func testPullDeletedDocWithFilterSingleShot() throws { try testPullDeletedDocWithFilter(false) } func testPullDeletedDocWithFilterContinuous() throws { try testPullDeletedDocWithFilter(true) } func testPushDeletedDocWithFilter(_ isContinuous: Bool) throws { // Create documents: let doc1 = MutableDocument(id: "doc1") doc1.setString("pass", forKey: "name") try db.saveDocument(doc1) let doc2 = MutableDocument(id: "pass") doc2.setString("pass", forKey: "name") try db.saveDocument(doc2) // Create replicator with push filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: isContinuous) config.pushFilter = { (doc, flags) in XCTAssertNotNil(doc.id) let isDeleted = flags.contains(.deleted) if isDeleted { docIds.add(doc.id) return doc.id == "pass" } return doc.string(forKey: "name") == "pass" } // Run the replicator: run(config: config, expectedError: nil) XCTAssertEqual(docIds.count, 0) XCTAssertNotNil(oDB.document(withID: "doc1")) XCTAssertNotNil(oDB.document(withID: "pass")) try db.deleteDocument(doc1) try db.deleteDocument(doc2) run(config: config, expectedError: nil) // Check documents passed to the filter: XCTAssertEqual(docIds.count, 2) XCTAssert(docIds.contains("doc1")) XCTAssert(docIds.contains("pass")) XCTAssertNotNil(oDB.document(withID: "doc1")) XCTAssertNil(oDB.document(withID: "pass")) } func testPullDeletedDocWithFilter(_ isContinuous: Bool) throws { // Create documents: let doc1 = MutableDocument(id: "doc1") doc1.setString("pass", forKey: "name") try oDB.saveDocument(doc1) let doc2 = MutableDocument(id: "pass") doc2.setString("pass", forKey: "name") try oDB.saveDocument(doc2) // Create replicator with push filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .pull, continuous: isContinuous) config.pullFilter = { (doc, flags) in XCTAssertNotNil(doc.id) let isDeleted = flags.contains(.deleted) if isDeleted { docIds.add(doc.id) return doc.id == "pass" } return doc.string(forKey: "name") == "pass" } // Run the replicator: run(config: config, expectedError: nil) XCTAssertEqual(docIds.count, 0) XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNotNil(db.document(withID: "pass")) try oDB.deleteDocument(doc1) try oDB.deleteDocument(doc2) run(config: config, expectedError: nil) // Check documents passed to the filter: XCTAssertEqual(docIds.count, 2) XCTAssert(docIds.contains("doc1")) XCTAssert(docIds.contains("pass")) XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNil(db.document(withID: "pass")) } // MARK: stop and restart replication with filter // https://issues.couchbase.com/browse/CBL-1061 func _testStopAndRestartPushReplicationWithFilter() throws { // Create documents: let doc1 = MutableDocument(id: "doc1") doc1.setString("pass", forKey: "name") try db.saveDocument(doc1) // Create replicator with pull filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .push, continuous: true) config.pushFilter = { (doc, flags) in XCTAssertNotNil(doc.id) docIds.add(doc.id) return doc.string(forKey: "name") == "pass" } // create a replicator repl = Replicator(config: config) run(replicator: repl, expectedError: nil) XCTAssertEqual(docIds.count, 1) XCTAssertEqual(oDB.count, 1) XCTAssertEqual(db.count, 1) // make some more changes let doc2 = MutableDocument(id: "doc2") doc2.setString("pass", forKey: "name") try db.saveDocument(doc2) let doc3 = MutableDocument(id: "doc3") doc3.setString("donotpass", forKey: "name") try db.saveDocument(doc3) // restart the same replicator docIds.removeAllObjects() run(replicator: repl, expectedError: nil) // should use the same replicator filter. XCTAssertEqual(docIds.count, 2) XCTAssert(docIds.contains("doc3")) XCTAssert(docIds.contains("doc2")) XCTAssertNotNil(oDB.document(withID: "doc1")) XCTAssertNotNil(oDB.document(withID: "doc2")) XCTAssertNil(oDB.document(withID: "doc3")) XCTAssertEqual(db.count, 3) XCTAssertEqual(oDB.count, 2) } func testStopAndRestartPullReplicationWithFilter() throws { // Create documents: let doc1 = MutableDocument(id: "doc1") doc1.setString("pass", forKey: "name") try oDB.saveDocument(doc1) // Create replicator with pull filter: let docIds = NSMutableSet() let target = DatabaseEndpoint(database: oDB) let config = self.config(target: target, type: .pull, continuous: true) config.pullFilter = { (doc, flags) in XCTAssertNotNil(doc.id) docIds.add(doc.id) return doc.string(forKey: "name") == "pass" } // create a replicator repl = Replicator(config: config) run(replicator: repl, expectedError: nil) XCTAssertEqual(docIds.count, 1) XCTAssertEqual(oDB.count, 1) XCTAssertEqual(db.count, 1) // make some more changes let doc2 = MutableDocument(id: "doc2") doc2.setString("pass", forKey: "name") try oDB.saveDocument(doc2) let doc3 = MutableDocument(id: "doc3") doc3.setString("donotpass", forKey: "name") try oDB.saveDocument(doc3) // restart the same replicator docIds.removeAllObjects() run(replicator: repl, expectedError: nil) // should use the same replicator filter. XCTAssertEqual(docIds.count, 2) XCTAssert(docIds.contains("doc3")) XCTAssert(docIds.contains("doc2")) XCTAssertNotNil(db.document(withID: "doc1")) XCTAssertNotNil(db.document(withID: "doc2")) XCTAssertNil(db.document(withID: "doc3")) XCTAssertEqual(oDB.count, 3) XCTAssertEqual(db.count, 2) } #endif }
36.261856
107
0.583016
5d6812f1db369ffbb0fab63e43291f4adba9909c
1,475
// // CloseButton.swift // WeScan // // Created by Boris Emorine on 2/27/18. // Copyright © 2018 WeTransfer. All rights reserved. // import UIKit /// A simple close button shaped like an "X". final class CloseButton: UIControl { let xLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(xLayer) backgroundColor = .clear isAccessibilityElement = true accessibilityTraits = UIAccessibilityTraits.button } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { self.clipsToBounds = false xLayer.frame = rect xLayer.lineWidth = 3.0 xLayer.path = pathForX(inRect: rect.insetBy(dx: xLayer.lineWidth / 2, dy: xLayer.lineWidth / 2)).cgPath xLayer.fillColor = UIColor.clear.cgColor xLayer.strokeColor = UIColor.black.cgColor xLayer.lineCap = CAShapeLayerLineCap.round } private func pathForX(inRect rect: CGRect) -> UIBezierPath { let path = UIBezierPath() path.move(to: rect.origin) path.addLine(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y + rect.height)) path.move(to: CGPoint(x: rect.origin.x + rect.width, y: rect.origin.y)) path.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.height)) return path } }
30.102041
111
0.63661
5d433ada64e581fd99323ccaf79a4124a4d86288
312
// // Answer.swift // refapa // // Created by Abraham Haros on 17/04/21. // import UIKit class Answer: NSObject, Codable { let isCorrect: Bool let answerText: String init(isCorrect: Bool, answerText: String) { self.isCorrect = isCorrect self.answerText = answerText } }
16.421053
47
0.63141
e4f32b0c0b9c33ffde40574d279a0881b3c63e0c
1,627
// // EasyRefresh.swift // Easy // // Created by OctMon on 2018/10/12. // import UIKit #if canImport(MJRefresh) import MJRefresh public extension Easy { typealias refresh = EasyRefresh } public class EasyRefresh: MJRefreshComponent { static func setHeader(_ header: MJRefreshGifHeader) { header.isAutomaticallyChangeAlpha = true header.setTitle(EasyGlobal.headerStateIdle, for: MJRefreshState.idle) header.setTitle(EasyGlobal.headerStatePulling, for: MJRefreshState.pulling) header.setTitle(EasyGlobal.headerStateRefreshing, for: MJRefreshState.refreshing) header.lastUpdatedTimeLabel?.isHidden = true } static func setFooter(_ footer: MJRefreshAutoNormalFooter) { footer.height = EasyGlobal.footerRefreshHeight footer.stateLabel?.textColor = EasyGlobal.footerStateLabelTextColor footer.stateLabel?.font = EasyGlobal.footerStateLabelFont footer.setTitle(EasyGlobal.footerStateNoMoreData, for: MJRefreshState.noMoreData) footer.isRefreshingTitleHidden = true footer.isHidden = true } } public extension EasyRefresh { static func headerWithHandler(_ handler: @escaping () -> Void) -> MJRefreshGifHeader { let header: MJRefreshGifHeader = MJRefreshGifHeader(refreshingBlock: handler) setHeader(header) return header } static func footerWithHandler(_ handler: @escaping () -> Void) -> MJRefreshAutoNormalFooter { let footer = MJRefreshAutoNormalFooter(refreshingBlock: handler) setFooter(footer) return footer } } #endif
30.12963
97
0.714813
76cdc1cd37339ffe6a6be0e9c0d896e3081434e4
501
// // ToppingItem.swift // smartPOS // // Created by I Am Focused on 14/04/2021. // Copyright © 2021 Clean Swift LLC. All rights reserved. // import Foundation typealias ToppingItems = [ToppingItem] struct ToppingItem: Decodable { var id: String var name: String var description: String var price: Double var maxQuantity: Int // var isActive: Bool? = true var state: ItemState? = .instock // var index: Float // var menuItemToppings: [MenuItemTopping] }
21.782609
58
0.668663
bf6f217df4c598b1793b66d43584900d56644e2a
8,382
// // KFImage.swift // Kingfisher // // Created by onevcat on 2019/06/26. // // Copyright (c) 2019 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import SwiftUI import Combine #if !KingfisherCocoaPods import Kingfisher #endif @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension Image { // Creates an SwiftUI.Image with either UIImage or NSImage. init(crossPlatformImage: KFCrossPlatformImage) { #if canImport(UIKit) self.init(uiImage: crossPlatformImage) #elseif canImport(AppKit) self.init(nsImage: crossPlatformImage) #endif } } /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public struct KFImage: View { /// An image binder that manages loading and cancelling image related task. @ObservedObject public private(set) var binder: ImageBinder // Acts as a placeholder when loading an image. var placeholder: AnyView? // Whether the download task should be cancelled when the view disappears. var cancelOnDisappear: Bool = false // Configurations should be performed on the image. var configurations: [(Image) -> Image] /// Creates a Kingfisher compatible image view to load image from the given `Source`. /// - Parameter source: The image `Source` defining where to load the target image. /// - Parameter options: The options should be applied when loading the image. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported. public init(source: Source?, options: KingfisherOptionsInfo? = nil) { binder = ImageBinder(source: source, options: options) configurations = [] binder.start() } /// Creates a Kingfisher compatible image view to load image from the given `Source`. /// - Parameter url: The image URL from where to load the target image. /// - Parameter options: The options should be applied when loading the image. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported. public init(_ url: URL?, options: KingfisherOptionsInfo? = nil) { let source = url.map { Source.network($0) } self.init(source: source, options: options) } /// Declares the content and behavior of this view. public var body: some View { Group { if binder.image != nil { configurations .reduce(Image(crossPlatformImage: binder.image!)) { current, config in config(current) } .animation(binder.fadeTransitionAnimation) } else { Group { if placeholder != nil { placeholder } else { Image(crossPlatformImage: .init()) } } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) .onDisappear { [unowned binder = self.binder] in if self.cancelOnDisappear { binder.cancel() } } } }.onAppear { [unowned binder] in if !binder.loadingOrSuccessed { binder.start() } } } } @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension KFImage { /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`. /// - Parameter block: The block applies to loaded image. /// - Returns: A `KFImage` view that configures internal `Image` with `block`. public func configure(_ block: @escaping (Image) -> Image) -> KFImage { var result = self result.configurations.append(block) return result } public func resizable( capInsets: EdgeInsets = EdgeInsets(), resizingMode: Image.ResizingMode = .stretch) -> KFImage { configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) } } public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage { configure { $0.renderingMode(renderingMode) } } public func interpolation(_ interpolation: Image.Interpolation) -> KFImage { configure { $0.interpolation(interpolation) } } public func antialiased(_ isAntialiased: Bool) -> KFImage { configure { $0.antialiased(isAntialiased) } } /// Sets a placeholder `View` which shows when loading the image. /// - Parameter content: A view that describes the placeholder. /// - Returns: A `KFImage` view that contains `content` as its placeholder. public func placeholder<Content: View>(@ViewBuilder _ content: () -> Content) -> KFImage { let v = content() var result = self result.placeholder = AnyView(v) return result } /// Sets cancelling the download task bound to `self` when the view disappearing. /// - Parameter flag: Whether cancel the task or not. /// - Returns: A `KFImage` view that cancels downloading task when disappears. public func cancelOnDisappear(_ flag: Bool) -> KFImage { var result = self result.cancelOnDisappear = flag return result } } @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension KFImage { /// Sets the action to perform when the image setting fails. /// - Parameter action: The action to perform. If `action` is `nil`, the /// call has no effect. /// - Returns: A `KFImage` view that triggers `action` when setting image fails. public func onFailure(perform action: ((KingfisherError) -> Void)?) -> KFImage { binder.setOnFailure(perform: action) return self } /// Sets the action to perform when the image setting successes. /// - Parameter action: The action to perform. If `action` is `nil`, the /// call has no effect. /// - Returns: A `KFImage` view that triggers `action` when setting image successes. public func onSuccess(perform action: ((RetrieveImageResult) -> Void)?) -> KFImage { binder.setOnSuccess(perform: action) return self } /// Sets the action to perform when the image downloading progress receiving new data. /// - Parameter action: The action to perform. If `action` is `nil`, the /// call has no effect. /// - Returns: A `KFImage` view that triggers `action` when new data arrives when downloading. public func onProgress(perform action: ((Int64, Int64) -> Void)?) -> KFImage { binder.setOnProgress(perform: action) return self } } #if DEBUG @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) struct KFImage_Previews : PreviewProvider { static var previews: some View { Group { KFImage(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!) .onSuccess { r in print(r) } .resizable() .aspectRatio(contentMode: .fit) .padding() } } } #endif
40.105263
115
0.641374
e52e6807f7ae30823ba8c6c49a742ec1aad2ecef
2,512
// // PermissionModel.swift // // // Created by Jevon Mao on 1/30/21. // import Foundation import SwiftUI import HealthKit /** The types of iOS system permission for show in the JMPermissions view Pass this as a parameter into JMPermissions View Modifier will display 3 UI elements–location, photo, and microphone. ``` [.location, photo, microphone] ``` */ public enum PermissionType { ///The `location` permission allows the device's positoin to be tracked case location ///The `locationAlways` permission provides location data even if app is in background case locationAlways ///Used to access the user's photo library case photo ///Permission allows developers to interact with the device microphone case microphone ///Permission that allows developers to interact with on-device camera case camera ///The `notification` permission allows the iOS system to receive notification from app case notification ///Permission that allows app to read & write to device calendar case calendar ///Permission that allows app to access device's bluetooth technologies case bluetooth ///A permission that allows developers to read & write to device contacts case contacts ///Permission that give app access to motion and fitness related sensor data case motion ///The `reminders` permission is needed to interact with device reminders case reminders /** Permission that allows app to access healthkit information - Note: Extensive Info.plist values and configurations are required for HealthKit authorization. Please see Apple Developer [website](https://developer.apple.com/documentation/healthkit/authorizing_access_to_health_data) for details. \n For example, passing in a `Set` of `HKSampleType`: ``` [.health(Set([HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .distanceCycling)!, HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!, HKObjectType.quantityType(forIdentifier: .heartRate)!]))] ``` */ case health(Set<HKSampleType>) ///Permission that allows app to use speech recognition case speech ///In order for app to track user's data across apps and websites, the tracking permission is needed @available(iOS 14.5, *) case tracking }
37.492537
242
0.708599
8925d3c1d83399edbbf6c86f284e3571724f8de7
3,491
// // DisplayPlayersViewModelTests.swift // KickStarterFrameworkTests // // Created by Abdullah Nana on 2021/11/25. // import XCTest @testable import KickStarterFramework class DisplayPlayersViewModelTests: XCTestCase { private var mockedPlayerRepository: MockPlayerRepository! private var viewModelUnderTest: DisplayPlayersViewModel! private var mockedDelegate: MockDelegate! override func setUp() { mockedPlayerRepository = MockPlayerRepository() mockedDelegate = MockDelegate() viewModelUnderTest = DisplayPlayersViewModel(repository: mockedPlayerRepository, delegate: mockedDelegate) } private var mockedPlayerData: PlayerResponseModel { let player = Player(id: 1, name: "Lionel Messi", age: 34, number: 10, position: "Forward", photo: "Messi Photo") let team = Teams(id: 1, name: "Manchester United", logo: "Man United Logo") let response = PlayerResponse(team: team, players: [player]) return PlayerResponseModel(get: "player", response: [response]) } func testFetchCoachDataSuccess() throws { mockedPlayerRepository.playerApiResponse = .success(mockedPlayerData) viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssert(!(viewModelUnderTest.playerResponse?.response.isEmpty ?? true)) XCTAssert(mockedDelegate.refreshCalled) } func testCoachDataFailure() { viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssert(viewModelUnderTest.playerResponse?.response.isEmpty ?? true) XCTAssert(mockedDelegate.showErrorCalled) } func testNumberOfPlayerDataResultsArrayReturnsCorrectValueAfterSuccess() { mockedPlayerRepository.playerApiResponse = .success(mockedPlayerData) viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssertEqual(1, viewModelUnderTest.numberOfPlayerResults) } func testNumberOfPlayerDataResultsArrayReturnsNilAfterFailure() { viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssertEqual(0, viewModelUnderTest.numberOfPlayerResults) } func testNumberOfPlayerDataResultsFunctionReturnsCorrectValueAfterSuccess() { mockedPlayerRepository.playerApiResponse = .success(mockedPlayerData) viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssertEqual(viewModelUnderTest.playerData(at: 0)?.name, "Lionel Messi") } func testNumberOfPlayerDataResultsFunctionReturnsNilAfterFailure() { viewModelUnderTest.fetchPlayerData(endpoint: viewModelUnderTest.endpoint(team: "33")) XCTAssertEqual(viewModelUnderTest.playerData(at: 0)?.name, nil) } final class MockDelegate: ViewModelDelegate { var refreshCalled = false var showErrorCalled = false func refreshViewContents() { refreshCalled = true } func showErrorMessage(error: Error) { showErrorCalled = true } } final class MockPlayerRepository: PlayerRepositable { func fetchPlayerData(method: HTTPMethod, endpoint: String, completionHandler: @escaping PlayerRepositoryResultBlock) { completionHandler(playerApiResponse) } var playerApiResponse: Result<PlayerResponseModel, Error> = .failure(URLError(.badServerResponse)) } }
45.934211
126
0.734174
6707eafe44302b0123e35845c7c2e0296c686e7d
6,146
// // AHDBColumnInfo.swift // Pods // // Created by Andy Tong on 9/21/17. // // import Foundation /// This struct describes a column's infomations when created public struct AHDBColumnInfo: Equatable { var name: String var type: AHDBDataType var isPrimaryKey = false var isForeignKey = false /// The key the foreign key is referring to var referenceKey: String = "" /// The foregin table's name var referenceTable: String = "" fileprivate(set) var constraints: [String] = [String]() /// This init method is used to add foregin key for this table /// /// - Parameters: /// - foreginKey: the foregin key's name in this table /// - type: the type should be the same as the one in the foreign table /// - referenceKey: the name that foreginKey is referring to in the foreign table /// - referenceTable: foreign table's name public init(foreginKey: String, type: AHDBDataType, referenceKey: String, referenceTable: String) { self.name = foreginKey self.referenceKey = referenceKey.lowercased() self.referenceTable = referenceTable.lowercased() self.isForeignKey = true self.type = type } public init(name: String, type: AHDBDataType, constraints: String... ) { self.name = name self.type = type for constraint in constraints { guard constraint.characters.count > 0 else { continue } let lowercased = constraint.lowercased() if lowercased.contains("primary key") { isPrimaryKey = true } self.constraints.append(lowercased) } } public init(name: String, type: AHDBDataType) { self.name = name self.type = type } public var bindingSql: String { if isForeignKey { let constraintString = constraints.joined(separator: " ") return "\(name) \(type.rawValue) \(constraintString) REFERENCES \(referenceTable)(\(referenceKey)) ON UPDATE CASCADE ON DELETE CASCADE" }else{ let constraintString = constraints.joined(separator: " ") return "\(name) \(type.rawValue) \(constraintString)" } } public static func ==(lhs: AHDBColumnInfo, rhs: AHDBColumnInfo) -> Bool { let b1 = lhs.name == rhs.name && lhs.type == rhs.type && lhs.isPrimaryKey == rhs.isPrimaryKey && lhs.referenceKey == rhs.referenceKey && lhs.referenceTable == rhs.referenceTable && lhs.constraints.count == rhs.constraints.count if b1 { for constraint in lhs.constraints { if rhs.constraints.contains(constraint) == false { return false } } for constraint in rhs.constraints { if lhs.constraints.contains(constraint) == false { return false } } return true } return false } } extension AHDBColumnInfo { internal class Coding: NSObject, NSCoding { let info: AHDBColumnInfo? init(info: AHDBColumnInfo) { self.info = info super.init() } // var name: String // var type: AHDBDataType // var isPrimaryKey = false // var isForeignKey = false // // var referenceKey: String = "" // var referenceTable: String = "" // // private(set) var constraints: [String] = [String]() required public init?(coder aDecoder: NSCoder) { let name: String = aDecoder.decodeObject(forKey: "name") as! String let typeStr = aDecoder.decodeObject(forKey: "type") as! String let type: AHDBDataType = AHDBDataType(rawValue: typeStr)! let isPrimaryKey = aDecoder.decodeBool(forKey: "isPrimaryKey") let isForeignKey = aDecoder.decodeBool(forKey: "isForeignKey") let referenceKey: String = aDecoder.decodeObject(forKey: "referenceKey") as! String let referenceTable: String = aDecoder.decodeObject(forKey: "referenceTable") as! String let constraints: [String] = aDecoder.decodeObject(forKey: "constraints") as! [String] var info = AHDBColumnInfo(name: name, type: type) info.isPrimaryKey = isPrimaryKey info.isForeignKey = isForeignKey info.referenceKey = referenceKey info.referenceTable = referenceTable info.constraints = constraints self.info = info super.init() } internal func encode(with aCoder: NSCoder) { guard let info = self.info else { return } aCoder.encode(info.name, forKey: "name") aCoder.encode(info.type.description, forKey: "type") aCoder.encode(info.isPrimaryKey, forKey: "isPrimaryKey") aCoder.encode(info.isForeignKey, forKey: "isForeignKey") aCoder.encode(info.referenceKey, forKey: "referenceKey") aCoder.encode(info.referenceTable, forKey: "referenceTable") aCoder.encode(info.constraints, forKey: "constraints") } } } internal protocol Encodable { var encoded: Decodable? { get } } internal protocol Decodable { var decoded: Encodable? { get } } extension AHDBColumnInfo: Encodable { var encoded: Decodable? { return AHDBColumnInfo.Coding(info: self) } } extension AHDBColumnInfo.Coding: Decodable { public var decoded: Encodable? { return self.info } } internal extension Sequence where Iterator.Element: Encodable { var encoded: [Decodable] { return self.filter({ $0.encoded != nil }).map({ $0.encoded! }) } } internal extension Sequence where Iterator.Element: Decodable { var decoded: [Encodable] { return self.filter({ $0.decoded != nil }).map({ $0.decoded! }) } }
32.17801
235
0.586886
d7738281d05ac76f24cb9704dc1f986933d8ef5a
969
// // BadgeKitTests.swift // BadgeKitTests // // Created by zhzh liu on 2018/1/16. // Copyright © 2018年 zhzh liu. All rights reserved. // import XCTest @testable import BadgeKit class BadgeKitTests: 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. // 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. } } }
26.189189
111
0.631579
ed7baa996fda65e81ee5e716fdcbdb4a88ebfbf5
2,977
// // PhotoViewModelTests.swift // CISampleTests // // Created by David on 2020/10/18. // Copyright © 2020 David. All rights reserved. // import XCTest import Moya @testable import CISample class PhotoViewModelTests: XCTestCase { var sut: PhotoViewModel! var mockManager: MockNetWorkManager! override func setUp() { super.setUp() mockManager = MockNetWorkManager() sut = PhotoViewModel(networkManager: mockManager) } override func tearDown() { mockManager = nil sut = nil super.tearDown() } func test_getPhoto() { // given mockManager.completePhotos = [Photo]() // when sut.initFetch() // then XCTAssert(mockManager.isGetPhotoCalled) } func test_create_cellViewModel() { // given let photos = StubGenerator().stubPhotos() mockManager.completePhotos = photos let expect = XCTestExpectation(description: "reload closure triggered") sut.reloadCollectionViewClosure = { expect.fulfill() } // when sut.initFetch() mockManager.fetchSuccess() wait(for: [expect], timeout: 1.0) XCTAssertEqual(sut.numberOfCells, photos.count) } func test_loading_whenFetching() { // given var loadingStatus = false let expect = XCTestExpectation(description: "Loading status updated") sut.updateLoadingStatus = { [weak sut] in loadingStatus = sut!.isLoading expect.fulfill() } // when sut.initFetch() // then wait(for: [expect], timeout: 1.0) mockManager.fetchSuccess() XCTAssertFalse(loadingStatus) } func test_getCellViewModel() { // given goToFetchPhotoFinished() let indexPath = IndexPath(row: 1, section: 0) let testPhoto = mockManager.completePhotos[indexPath.row] // when let vm = sut.getCellViewModel(at: indexPath) // then XCTAssertEqual(vm.title, testPhoto.title) } } extension PhotoViewModelTests { private func goToFetchPhotoFinished() { mockManager.completePhotos = StubGenerator().stubPhotos() sut.initFetch() mockManager.fetchSuccess() } } class MockNetWorkManager: APIServiceProtocol { var isGetPhotoCalled = false var completePhotos: [Photo] = [Photo]() var completeClosure: ((Result<[Photo], MoyaError>) -> ())! func getPhoto(completion: @escaping (Result<[Photo], MoyaError>) -> Void) { isGetPhotoCalled = true completeClosure = completion } func fetchSuccess() { completeClosure(.success(completePhotos)) } func fetchFail(error: MoyaError) { completeClosure(.failure(error)) } } class StubGenerator { func stubPhotos() -> [Photo] { let path = Bundle.main.path(forResource: "content", ofType: "json")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let photos = try! decoder.decode([Photo].self, from: data) return photos } }
23.440945
77
0.668794
f88a8e4be4192fdf0760888869cbb54ed80624f1
219
// // SetGameApp.swift // Set // // Created by Tiago Lopes on 23/09/21. // import SwiftUI @main struct SetGameApp: App { var body: some Scene { WindowGroup { SetGameView() } } }
12.166667
39
0.543379
266e9a74daa555380b92786a3f742b586e92a9a3
5,980
// Copyright 2019, Oath Inc. // Licensed under the terms of the MIT license. See LICENSE file in https://github.com/yahoo/Override for terms. import Foundation internal typealias FeatureOverrideHandler = (_ feature: AnyFeature, _ oldState: OverrideState) -> Void @objc public enum OverrideState: Int, CaseIterable { case featureDefault case disabled case enabled var description: String { switch self { case .featureDefault: return "Default" case .enabled: return "ON" case .disabled: return "OFF" } } static func fromString(_ str: String) -> OverrideState { switch str { case "ON": return .enabled case "OFF": return .disabled default: return .featureDefault } } } @objc public protocol AnyFeature: NSObjectProtocol { var key: String! { get } var requiresRestart: Bool { get } var defaultState: Bool { get } var enabled: Bool { get } var override: OverrideState { get set } } extension AnyFeature { public var hash: Int { return self.key.hashValue } } @objc public protocol ComputedDefaultState: NSObjectProtocol { var computedDefaultState: (_ feature: AnyFeature) -> Bool { get } } @objc open class BaseFeature: NSObject, AnyFeature { @objc public internal(set) var key: String! @objc public let requiresRestart: Bool @objc internal let underlyingDefaultState: Bool /// defaultState is a stored referencing a static variable to preserve the /// ability of subclass implementations to override with a computed value @objc public var defaultState: Bool { return self.underlyingDefaultState } @objc public var enabled: Bool { switch override { case .enabled: return true case .disabled: return false case .featureDefault: return defaultState } } @objc public dynamic var override: OverrideState = .featureDefault { didSet { self.overrideChangeHandler?(self) } } @objc internal var overrideChangeHandler: ((_ feature: BaseFeature) -> Void)? @objc init(key: String?, requiresRestart: Bool, defaultState: Bool) { self.key = key self.requiresRestart = requiresRestart self.underlyingDefaultState = defaultState } } @objc open class Feature: BaseFeature { @objc override open var description: String { let enabledString = enabled ? "ON" : "OFF" return "\(key ?? "UNKNOWN"):[\(enabledString)] - Override: \(override.description), Default: \(defaultState)" } @objc public convenience init(requiresRestart: Bool = false, defaultState: Bool = false) { self.init(key: nil, requiresRestart: requiresRestart, defaultState: defaultState) } @objc public override init(key: String?, requiresRestart: Bool = false, defaultState: Bool = false) { super.init(key: key, requiresRestart: requiresRestart, defaultState: defaultState) } } @objc open class DynamicFeature: BaseFeature, ComputedDefaultState { @objc public private(set) var computedDefaultState: (_ feature: AnyFeature) -> Bool @objc public override var defaultState: Bool { return computedDefaultState(self) } @objc public init(key: String? = nil, requiresRestart: Bool = false, computedDefault: @escaping (_ feature: AnyFeature) -> Bool) { self.computedDefaultState = computedDefault super.init(key: key, requiresRestart: requiresRestart, defaultState: false) } } // SWIFT-ONLY VERSION // // Below are version of Feature and DynamicFeature built entirely in Swift. This // Allow for a very elegant solution where the default implementations are provided // via Protocol extensions, and classes formed using Protocol composition. // ...however are not compatible with Objective-C due to use of protocol extensions. /* public protocol AnyFeature: class, CustomStringConvertible, CustomDebugStringConvertible { var key: String { get } var requiresRestart: Bool { get } var defaultState: Bool { get } var enabled: Bool { get } var override: OverrideState { get set } } public protocol ComputedDefaultState { var computedDefaultState: (_ feature: AnyFeature) -> Bool { get } } public extension AnyFeature { var enabled: Bool { switch override { case .on: return true case .off: return false case .featureDefault: return defaultState } } var description: String { return debugDescription } var debugDescription: String { let enabledString = enabled ? "ON" : "OFF" return "\(key):[\(enabledString)] - Override: \(override.description), Default: \(defaultState)" } } public extension AnyFeature where Self: ComputedDefaultState { var defaultState: Bool { return computedDefaultState(self) } } public class DynamicFeature: AnyFeature, ComputedDefaultState { public let computedDefaultState: (_ feature: AnyFeature) -> Bool public var override: OverrideState = .featureDefault public let key: String public let requiresRestart: Bool public init(key: String, requiresRestart: Bool = false, defaultState: @escaping (_ feature: AnyFeature) -> Bool) { self.key = key self.requiresRestart = requiresRestart self.computedDefaultState = defaultState } } public class Feature: AnyFeature { public let defaultState: Bool public var override: OverrideState = .featureDefault public let key: String public let requiresRestart: Bool public init(key: String, requiresRestart: Bool = false, defaultState: Bool = false) { self.key = key self.requiresRestart = requiresRestart self.defaultState = defaultState } } */
28.75
118
0.663211
e50e1b220510749ec7c38fc0f9fd75862339ec61
2,357
// // MapViewController.swift // PIDRunner // // Created by Dawid Cieslak on 22/04/2018. // Copyright © 2018 Dawid Cieslak. All rights reserved. // import UIKit import PulseController class MapViewController: UIViewController { /// Wraps all UI components for this ViewController var mapView: MapView /// Data model with route coordinates and average speed var speedDataModel: SpeedModel /// Latest value of progress set by user var currentProgress: CGFloat = 0.0 var pidController: Pulse? = nil override func viewDidLoad() { super.viewDidLoad() // Listen to slider changes mapView.sliderValueChanged = { [weak self] value in guard let `self` = self else { return } // value from 0.0 -> 1.0 self.pidController?.setPoint = value } let configuration = Pulse.Configuration(minimumValueStep: 0.005, Kp: 1.2, Ki: 0.1, Kd: 0.4) pidController = Pulse(configuration: configuration, measureClosure: { [weak self] () -> CGFloat in guard let `self` = self else { return 0 } return self.currentProgress }, outputClosure: { (output) in self.currentProgress = output self.mapView.updateData(for: self.currentProgress) }) } required init?(coder aDecoder: NSCoder) { guard let model = SpeedModel.with(file: "speedData") else { fatalError("Cannot read JSON data") } self.speedDataModel = model self.mapView = MapView(speedModel: self.speedDataModel) super.init(coder: aDecoder) mapView.dataProvider = self } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if let firstTouch = touches.first { let normalizedForce = firstTouch.force / firstTouch.maximumPossibleForce self.pidController?.setPoint = normalizedForce } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.pidController?.setPoint = 0 } override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) { if(motion == .motionShake) { pidController?.showTunningView(minimumValue: -1, maximumValue: 1) } } }
31.426667
107
0.618583
f581be90b9c8200065631ef5548db16f7e65bfe0
500
// // Publisher+Validation.swift // DicodingGames // // Created by Dhiky Aldwiansyah on 15/07/20. // Copyright © 2020 Dhiky Aldwiansyah. All rights reserved. // import Foundation import Combine import Regex extension Published.Publisher where Value == String { func nonEmptyValidator(_ errorMessage: @autoclosure @escaping ValidationErrorClosure) -> ValidationPublisher { return ValidationPublishers.nonEmptyValidation(for: self, errorMessage: errorMessage()) } }
25
114
0.736
d942cf70db2230081a0fe1f5c6755828b6b5d45d
8,129
// // ThreadTest.swift // leetcode // // Created by youzhuo wang on 2020/6/9. // Copyright © 2020 youzhuo wang. All rights reserved. // import Foundation class ThreadTest { func test() { // DispatchQueue.main.async { // DispatchQueue.main.async { // sleep(2) // print("1"+"\(Thread.current)") // } // print("2" + "\(Thread.current)") // DispatchQueue.main.async { // print("3" + "\(Thread.current)") // } // } // sleep(1) // 睡1s // 2. main // 睡2s // 1. main // 3. main // DispatchQueue.global().async { // DispatchQueue.global().async { // sleep(2) // print("1"+"\(Thread.current)") // } // print("2" + "\(Thread.current)") // DispatchQueue.global().async { // print("3" + "\(Thread.current)") // } // } // print("1-a" + "\(Thread.current)") // sleep(1) // print("1-b" + "\(Thread.current)") //let queen = OperationQueue() // 输出2 // 输出3 // 过2秒,输出1 // maxConcurrentOperationCount = 1 // 输出2 // 过2秒,输出1 // 输出3 // DispatchQueue.global().async 有可能与后面的异步执行 // 总是在后面执行,要在下一个runloop才能执行 // DispatchQueue.global().async { // for index in (0...100) { // print("\(index)--aa") // DispatchQueue.global().async { // //var i = 10 // //print("\(index)--\(i)") // print("\(index)--bb") // // DispatchQueue.global() // DispatchQueue.main.async { // print("\(index)--cc") // } // // //i = 20 // } // print("\(index)--dd") // } // } // 多个并行队列异步会复用线程 // N个串行队列异步会有N个线程 for index in (0...60) { // DispatchQueue.global().sync { // print("\(index)--", Thread.current) // } let queue1 = DispatchQueue.init(label: "queue\(index)", qos: .default, attributes: .concurrent) queue1.async { print("\(index)--", Thread.current) } // let queue1 = DispatchQueue.init(label: "queue1") // queue1.async { // DispatchQueue.main.sync { // print("\(index)--", Thread.current) // } // } } /* let queue1 = DispatchQueue.init(label: "queue1") let queue2 = DispatchQueue.init(label: "queue2") let queue3 = DispatchQueue.init(label: "queue3") let queue4 = DispatchQueue.init(label: "queue4") let queue5 = DispatchQueue.init(label: "queue5") let queue6 = DispatchQueue.init(label: "queue6") let queue7 = DispatchQueue.init(label: "queue7") let queue8 = DispatchQueue.init(label: "queue8") // 总需求: 一开始有100个下载图片请求,后续不断有新的下载图片请求任务加入 // 方案1: 最多三个任务同时执行,不用关心底层具体多少个线程 // 方案2: 最多三个线程同时执行 // 1. 需要指定在 queue1 , queue2, queue3上执行, 如何动态分配到其中一个执行 // 最多同时三个图片下载 // 1. 信号量 // 2. OprationQueue的maxOperaionCount for i in (0...100) { DispatchQueue.global().async { // 下载图片 } } for i in (0...10) { queue1.async { self.test(index: 1, count: i) } } for i in (0...10) { queue2.async { self.test(index: 2, count: i) } } for i in (0...10) { queue3.async { self.test(index: 3, count: i) } } for i in (0...10) { queue8.async { self.test(index: 8, count: i) } } for i in (0...10) { queue4.async { self.test(index: 4, count: i) } } for i in (0...10) { queue5.async { self.test(index: 5, count: i) } } for i in (0...10) { queue6.async { self.test(index: 6, count: i) } } for i in (0...10) { queue7.async { self.test(index: 7, count: i) } } let queue9 = DispatchQueue.init(label: "queue9") for i in (0...10) { queue9.async { self.test(index: 9, count: i) } } let queue10 = DispatchQueue.init(label: "queue10") for i in (0...10) { queue10.async { self.test(index: 10, count: i) } } let queue11 = DispatchQueue.init(label: "queue11") for i in (0...10) { queue11.async { self.test(index: 11, count: i) } } let queue12 = DispatchQueue.init(label: "queue12") for i in (0...10) { queue12.async { self.test(index: 12, count: i) } } let queue13 = DispatchQueue.init(label: "queue13") for i in (0...10) { queue13.async { self.test(index: 13, count: i) } } let queue14 = DispatchQueue.init(label: "queue14") for i in (0...10) { queue14.async { self.test(index: 14, count: i) } } let queue15 = DispatchQueue.init(label: "queue15") for i in (0...10) { queue15.async { self.test(index: 15, count: i) } } let queue16 = DispatchQueue.init(label: "queue16") for i in (0...10) { queue16.async { self.test(index: 16, count: i) } } let queue17 = DispatchQueue.init(label: "queue17") for i in (0...10) { queue17.async { self.test(index: 17, count: i) } } let queue18 = DispatchQueue.init(label: "queue18") for i in (0...10) { queue18.async { self.test(index: 18, count: i) } } */ } } // 锁 // 自旋锁 // 互斥锁 // 递归锁 // 读写锁 // 信号量
34.012552
115
0.330668
2645d6f02a41f4adcce66d43850b0f0a8eb000a8
385
// // XCUIApplication.swift // MobiliumDriver // // Created by Mateusz Mularski on 12/09/2019. // Copyright © 2019 Silvair. All rights reserved. // import XCTest extension XCUIApplication { func element(with accessibilityId: String, index: Int) -> XCUIElement { return descendants(matching: .any).matching(identifier: accessibilityId).element(boundBy: index) } }
24.0625
104
0.716883
bb7b21bcdc1e2d3e15dcce2677bae242fcf523e3
356
// // CGPoint+Swissors.swift // Swissors // // Created by viktor.volkov on 17.04.2022. // import CoreGraphics public extension CGPoint { init(x: CGFloat) { self.init(x: x, y: .zero) } init(y: CGFloat) { self.init(x: .zero, y: y) } init(value: CGFloat) { self.init(x: value, y: value) } }
14.833333
43
0.530899