label
int64
0
1
text
stringlengths
0
2.8M
0
// // DownloadTests.swift // ThunderRequestTests // // Created by Simon Mitchell on 14/12/2018. // Copyright © 2018 threesidedcube. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #endif import XCTest @testable import ThunderRequest class DownloadTests: XCTestCase { let requestBaseURL = URL(string: "https://via.placeholder.com/")! func testDownloadSavesToDisk() { let requestController = RequestController(baseURL: requestBaseURL) let finishExpectation = expectation(description: "App should correctly download body from server") requestController.download("500", progress: nil) { (response, url, error) in XCTAssertNotNil(url) XCTAssertNotNil(response) XCTAssertEqual(response?.status, .okay) XCTAssertTrue(FileManager.default.fileExists(atPath: url!.path)) let data = try? Data(contentsOf: url!) XCTAssertNotNil(data) XCTAssertNotNil(UIImage(data: data!)) finishExpectation.fulfill() } waitForExpectations(timeout: 35) { (error) in XCTAssertNil(error, "The download timed out") } } }
0
// // ProjectInspectorController.swift // Lingo // // Created by Wesley Byrne on 4/20/16. // Copyright © 2016 The Noun Project. All rights reserved. // import Foundation import CollectionView func ==(a: ListCell.SeperatorStyle, b: ListCell.SeperatorStyle) -> Bool { switch (a, b) { case (.none, .none): return true case (.default, .default): return true case (.full, .full): return true case (.custom(_, _), .custom(_, _)): return true default: return false } } func CGSizeIsEmpty(_ size: CGSize?) -> Bool { guard let s = size else { return true } if s.width <= 0 || s.height <= 0 { return true } return false } class ListCell : CollectionViewCell { let titleLabel = NSTextField(frame: NSZeroRect) private var _needsLayout = true var inset : CGFloat = 12 { didSet { _needsLayout = inset != oldValue || _needsLayout }} // override var wantsUpdateLayer: Bool { return seperatorStyle == SeperatorStyle.None } lazy var detailLabel : NSTextField = { let label = NSTextField(frame: NSZeroRect) label.usesSingleLineMode = true label.drawsBackground = false label.translatesAutoresizingMaskIntoConstraints = false label.backgroundColor = NSColor.clear label.isEditable = false label.isSelectable = false label.isBordered = false label.lineBreakMode = NSParagraphStyle.LineBreakMode.byTruncatingTail return label }() lazy var imageView : NSImageView = { let iv = NSImageView() iv.translatesAutoresizingMaskIntoConstraints = false return iv }() var imageSize: CGSize = CGSize.zero { didSet { _needsLayout = imageSize != oldValue || _needsLayout }} var seperatorStyle: SeperatorStyle = .default var seperatorColor : NSColor = NSColor(white: 0, alpha: 0.05) var seperatorWidth: CGFloat = 2 enum SeperatorStyle { case none case `default` case full case custom(left: CGFloat, right: CGFloat) } enum Style { case basic case basicImage case subtitle case subtitleImage case titleDetail case split } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.unbind(NSBindingName(rawValue: "stringValue")) } var highlightedBackgroundColor : NSColor? var selectedBackgroundColor : NSColor? var restingBackgroundColor: NSColor = NSColor.clear { didSet { if !self.highlighted { self.backgroundColor = restingBackgroundColor } } } /// If true, highlighting the cell does not change it's appearance var disableHighlight : Bool = false override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.alphaValue = selected ? 0.5 : 0.8 var color : NSColor? if selected, let bg = self.selectedBackgroundColor { color = bg } else if highlighted, let bg = self.highlightedBackgroundColor { color = bg } self.backgroundColor = color ?? self.restingBackgroundColor self.needsDisplay = true } override func setHighlighted(_ highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) guard !selected else { return } if highlighted, let hbg = self.highlightedBackgroundColor { self.backgroundColor = hbg } else { self.backgroundColor = restingBackgroundColor } self.needsDisplay = true } init() { super.init(frame: NSZeroRect) self.addSubview(titleLabel) titleLabel.usesSingleLineMode = true titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.drawsBackground = false titleLabel.backgroundColor = NSColor.clear titleLabel.lineBreakMode = NSParagraphStyle.LineBreakMode.byTruncatingTail titleLabel.isEditable = false titleLabel.isBordered = false titleLabel.isSelectable = false self.addSubview(titleLabel) self.setupForStyle(.basic) } required init?(coder: NSCoder) { super.init(coder: coder) } var style : Style = .basic { didSet { if style == oldValue && !_needsLayout { return } self.setupForStyle(style) } } fileprivate func setupForStyle(_ style: Style) { self.removeConstraints(self.constraints) switch style { case .basic, .basicImage: detailLabel.removeFromSuperview() titleLabel.alignment = .left titleLabel.font = NSFont.systemFont(ofSize: 14) titleLabel.textColor = NSColor.darkGray self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: titleLabel, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: inset)) if style == .basicImage { let iv = self.imageView iv.removeFromSuperview() self.addSubview(iv) iv.removeConstraints(iv.constraints) self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: iv, attribute: .left, multiplier: 1, constant: -inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iv, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .lessThanOrEqual, toItem: iv, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: iv, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1, constant: 6)) if CGSizeIsEmpty(self.imageSize) == false { iv.addSizeConstraints(self.imageSize) } else { iv.addConstraint(NSLayoutConstraint(item: iv, attribute: .width, relatedBy: .equal, toItem: iv, attribute: .height, multiplier: 1, constant: 0)) } } else { imageView.removeFromSuperview() self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .left, multiplier: 1, constant: -inset)) } case .subtitle, .subtitleImage: self.addSubview(detailLabel) titleLabel.alignment = .left titleLabel.font = NSFont.systemFont(ofSize: 14) titleLabel.textColor = NSColor.darkGray detailLabel.alignment = .left detailLabel.font = NSFont.systemFont(ofSize: 12) detailLabel.textColor = NSColor.gray self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: titleLabel, attribute: .right, multiplier: 1, constant: inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: titleLabel, attribute: .lastBaseline, multiplier: 1, constant: 1)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: detailLabel, attribute: .right, multiplier: 1, constant: inset)) self.addConstraint(NSLayoutConstraint(item: detailLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .lastBaseline, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: detailLabel, attribute: .left, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: detailLabel, attribute: .right, multiplier: 1, constant: 0)) if style == .subtitleImage { let iv = self.imageView self.addSubview(iv) iv.removeConstraints(iv.constraints) self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: iv, attribute: .left, multiplier: 1, constant: -inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iv, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .top, relatedBy: .lessThanOrEqual, toItem: iv, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: iv, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1, constant: 6)) if CGSizeIsEmpty(self.imageSize) == false { iv.addSizeConstraints(self.imageSize) } else { iv.addConstraint(NSLayoutConstraint(item: iv, attribute: .width, relatedBy: .equal, toItem: iv, attribute: .height, multiplier: 1, constant: 0)) } } else { self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .left, multiplier: 1, constant: -inset)) } case .split: imageView.removeFromSuperview() self.addSubview(detailLabel) titleLabel.alignment = .left titleLabel.font = NSFont.systemFont(ofSize: 14) titleLabel.textColor = NSColor.darkGray detailLabel.alignment = .right detailLabel.font = NSFont.systemFont(ofSize: 14) detailLabel.textColor = NSColor.gray self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .left, multiplier: 1, constant: -inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: titleLabel, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: detailLabel, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: detailLabel, attribute: .right, multiplier: 1, constant: inset)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: detailLabel, attribute: .left, multiplier: 1, constant: -2)) self.titleLabel.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 400), for: .horizontal) self.detailLabel.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 350), for: .horizontal) case .titleDetail: imageView.removeFromSuperview() self.addSubview(detailLabel) titleLabel.alignment = .right titleLabel.font = NSFont.systemFont(ofSize: 13) titleLabel.textColor = NSColor.gray detailLabel.alignment = .left detailLabel.font = NSFont.systemFont(ofSize: 13) detailLabel.textColor = NSColor.darkGray self.addConstraint(NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: titleLabel, attribute: .left, multiplier: 1, constant: -inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: titleLabel, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: detailLabel, attribute: .right, multiplier: 1, constant: inset)) self.addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: detailLabel, attribute: .centerY, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .equal, toItem: detailLabel, attribute: .left, multiplier: 1, constant: -4)) self.titleLabel.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 400), for: .horizontal) self.detailLabel.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 400), for: .horizontal) } } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) if (highlighted && !disableHighlight) || seperatorStyle == .none { return } let ctx = NSGraphicsContext.current?.cgContext switch seperatorStyle { case .full: ctx?.move(to: CGPoint(x: 0, y: 0)) ctx?.addLine(to: CGPoint(x: self.bounds.maxX, y: 0)) case let .custom(left, right): ctx?.move(to: CGPoint(x: left, y: 0)) ctx?.addLine(to: CGPoint(x: self.bounds.maxX - right, y: 0)) default: ctx?.move(to: CGPoint(x: self.titleLabel.frame.minX, y: 0)) ctx?.addLine(to: CGPoint(x: self.bounds.maxX, y: 0)) } ctx?.setStrokeColor(self.seperatorColor.cgColor) ctx?.setLineWidth(self.seperatorWidth) ctx?.strokePath() NSGraphicsContext.restoreGraphicsState() } }
0
import UIKit import main import SwiftKeychainWrapper /* * Copyright 2019 Simon Schubert Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let database = Database() database.setup() let url: String = KeychainWrapper.standard.string(forKey: "SERVER") ?? "" if(url.isEmpty) { return true } let email: String = KeychainWrapper.standard.string(forKey: "EMAIL") ?? "" let password: String = KeychainWrapper.standard.string(forKey: "PASSWORD") ?? "" let api = Api() api.setCredentials(url: url, email: email, password: password) let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "navigation") self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = initialViewController self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { } func applicationDidEnterBackground(_ application: UIApplication) { } func applicationWillEnterForeground(_ application: UIApplication) { } func applicationDidBecomeActive(_ application: UIApplication) { } func applicationWillTerminate(_ application: UIApplication) { } }
0
import Logging import XCTest @testable import AWSXRayRecorder final class ConfigTests: XCTestCase { func testDefaultConfig() { let config = XRayRecorder.Config() XCTAssertTrue(config.enabled) XCTAssertEqual("127.0.0.1:2000", config.daemonEndpoint) XCTAssertEqual(Logger.Level.info, config.logLevel) XCTAssertEqual("aws-xray-sdk-swift", config.serviceVersion) let emitterConfig = XRayUDPEmitter.Config() XCTAssertEqual("127.0.0.1:2000", emitterConfig.daemonEndpoint) XCTAssertEqual(Logger.Level.info, emitterConfig.logLevel) XCTAssertEqual(config.daemonEndpoint, emitterConfig.daemonEndpoint) XCTAssertEqual(config.logLevel, emitterConfig.logLevel) } func testCopyConfig() { let config = XRayRecorder.Config(daemonEndpoint: "127.0.0.1:4000", logLevel: .debug) let emitterConfig = XRayUDPEmitter.Config(config) XCTAssertEqual(config.daemonEndpoint, emitterConfig.daemonEndpoint) XCTAssertEqual(config.logLevel, emitterConfig.logLevel) } }
0
import Foundation final class RTMPHandshake { static let sigSize:Int = 1536 static let protocolVersion:UInt8 = 3 var timestamp:TimeInterval = 0 var c0c1packet:[UInt8] { let packet:ByteArray = ByteArray() .writeUInt8(RTMPHandshake.protocolVersion) .writeInt32(Int32(timestamp)) .writeBytes([0x00, 0x00, 0x00, 0x00]) for _ in 0..<RTMPHandshake.sigSize - 8 { packet.writeUInt8(UInt8(arc4random_uniform(0xff))) } return packet.bytes } func c2packet(_ s0s1packet:[UInt8]) -> [UInt8] { let packet:ByteArray = ByteArray() .writeBytes(Array<UInt8>(s0s1packet[1...4])) .writeInt32(Int32(Date().timeIntervalSince1970 - timestamp)) .writeBytes(Array<UInt8>(s0s1packet[9...RTMPHandshake.sigSize])) return packet.bytes } func clear() { timestamp = 0 } }
1
// RUN: not %target-swift-frontend %s -typecheck class A<A<T : b() -> Any) { struct c : B struct B<d where f: Sequence, Any) -> U { print((() let n1: ()!))->, end) enum a(t
0
// // Logger.swift // TinyLogger // // Created by Suren Khorenyan on 05.10.17. // Copyright © 2017 Suren Khorenyan. All rights reserved. // import Foundation class Logger { static let shared = Logger() var loggingLevel = 30 enum LogType: Int { case verbose = 0 case debug = 10 case info = 20 case warning = 30 case error = 40 case severe = 50 } private func sourceFileName(_ filePath: String) -> String { let components = filePath.components(separatedBy: "/") return components.isEmpty ? "" : components.last! } private func log(line: String, level: LogType) { #if DEBUG if level.rawValue >= loggingLevel { print(line) } #endif } private func formatLine(message: String, event: LogType, fileName: String, line: Int, column: Int, funcName: String) -> String { let eventEmoji: String switch event { case .verbose: eventEmoji = "🔎" case .debug: eventEmoji = "🐞" case .info: eventEmoji = "📝" case .warning: eventEmoji = "⚠️" case .error: eventEmoji = "📛" case .severe: eventEmoji = "‼️" } return "\(Date().formatted) [\(eventEmoji)] [\(sourceFileName(fileName))]:\(line) \(column) \(funcName) ➡️ \(message)" } func verbose(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .verbose, fileName: fileName, line: line, column: column, funcName: funcName), level: .verbose) } func debug(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .debug, fileName: fileName, line: line, column: column, funcName: funcName), level: .debug) } func info(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .info, fileName: fileName, line: line, column: column, funcName: funcName), level: .info) } func warning(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .warning, fileName: fileName, line: line, column: column, funcName: funcName), level: .warning) } func error(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .error, fileName: fileName, line: line, column: column, funcName: funcName), level: .error) } func severe(message: String, fileName: String = #file, line: Int = #line, column: Int = #column, funcName: String = #function) { self.log(line: formatLine(message: message, event: .severe, fileName: fileName, line: line, column: column, funcName: funcName), level: .severe) } }
0
../../RxCocoa/Traits/ControlProperty.swift
0
// // ABTestCommandTest.swift // // // Created by Vladislav Fitc on 28/05/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class ABTestCommandTest: XCTestCase, AlgoliaCommandTest { func testAdd() { let command = Command.ABTest.Add(abTest: test.abTest, requestOptions: test.requestOptions) check(command: command, callType: .write, method: .post, urlPath: "/2/abtests", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: test.abTest.httpBody, requestOptions: test.requestOptions) } func testGet() { let command = Command.ABTest.Get(abTestID: "testABTestID", requestOptions: test.requestOptions) check(command: command, callType: .read, method: .get, urlPath: "/2/abtests/testABTestID", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: nil, requestOptions: test.requestOptions) } func testStop() { let command = Command.ABTest.Stop(abTestID: "testABTestID", requestOptions: test.requestOptions) check(command: command, callType: .write, method: .post, urlPath: "/2/abtests/testABTestID/stop", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: nil, requestOptions: test.requestOptions) } func testDelete() { let command = Command.ABTest.Delete(abTestID: "testABTestID", requestOptions: test.requestOptions) check(command: command, callType: .write, method: .delete, urlPath: "/2/abtests/testABTestID", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: nil, requestOptions: test.requestOptions) } func testList() { let command = Command.ABTest.List(offset: 10, limit: 20, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .get, urlPath: "/2/abtests", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), .init(name: "offset", value: "10"), .init(name: "limit", value: "20"), ], body: nil, requestOptions: test.requestOptions) } }
0
// // Observable+StandardSequenceOperatorsTest.swift // Rx // // Created by Krunoslav Zaher on 2/17/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import XCTest import RxSwift class ObservableStandardSequenceOperators : RxTest { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } } func isPrime(i: Int) -> Bool { if i <= 1 { return false } let max = Int(sqrt(Float(i))) for (var j = 2; j <= max; ++j) { if i % j == 0 { return false } } return true } // where extension ObservableStandardSequenceOperators { func test_filterComplete() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600), next(610, 12), error(620, testError), completed(630) ]) let res = scheduler.start { () -> Observable<Int> in return xs.filter { (num: Int) -> Bool in invoked++; return isPrime(num); } } XCTAssertEqual(res.messages, [ next(230, 3), next(340, 5), next(390, 7), next(580, 11), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_filterTrue() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start { () -> Observable<Int> in return xs.filter { (num: Int) -> Bool in invoked++ return true } } XCTAssertEqual(res.messages, [ next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_filterFalse() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start { () -> Observable<Int> in return xs.filter { (num: Int) -> Bool in invoked++ return false } } XCTAssertEqual(res.messages, [ completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(9, invoked) } func test_filterDisposed() { let scheduler = TestScheduler(initialClock: 0) var invoked = 0 let xs = scheduler.createHotObservable([ next(110, 1), next(180, 2), next(230, 3), next(270, 4), next(340, 5), next(380, 6), next(390, 7), next(450, 8), next(470, 9), next(560, 10), next(580, 11), completed(600) ]) let res = scheduler.start(400) { () -> Observable<Int> in return xs.filter { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(230, 3), next(340, 5), next(390, 7) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) XCTAssertEqual(5, invoked) } } // takeWhile extension ObservableStandardSequenceOperators { func testTakeWhile_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(330), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(330) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 330) ]) XCTAssertEqual(4, invoked) } func testTakeWhile_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), error(270, testError), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), error(270, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) XCTAssertEqual(2, invoked) } func testTakeWhile_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(300) { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) XCTAssertEqual(3, invoked) } func testTakeWhile_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(400) { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), completed(390) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 390) ]) XCTAssertEqual(6, invoked) } func testTakeWhile_Zero() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) var invoked = 0 let res = scheduler.start(300) { () -> Observable<Int> in return xs.takeWhile { (num: Int) -> Bool in invoked++; return isPrime(num) } } XCTAssertEqual(res.messages, [ completed(205) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 205) ]) XCTAssertEqual(1, invoked) } func testTakeWhile_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start() { () -> Observable<Int> in return xs.takeWhile { num in invoked++ if invoked == 3 { throw testError } return isPrime(num) } } XCTAssertEqual(res.messages, [ next(210, 2), next(260, 5), error(290, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) XCTAssertEqual(3, invoked) } func testTakeWhile_Index1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError), ]) let res = scheduler.start { () -> Observable<Int> in return xs.takeWhileWithIndex { num, index in index < 5 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(350) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 350) ]) } func testTakeWhile_Index2() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) let res = scheduler.start { () -> Observable<Int> in return xs.takeWhileWithIndex { num , index in return index >= 0 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } func testTakeWhile_Index_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), error(400, testError) ]) let res = scheduler.start { () -> Observable<Int> in return xs.takeWhileWithIndex { num, index in index >= 0 } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), error(400, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } func testTakeWhile_Index_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) let res = scheduler.start { () -> Observable<Int> in return xs.takeWhileWithIndex { num, index in if index < 5 { return true } throw testError } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), error(350, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 350) ]) } } // map // these test are not port from Rx extension ObservableStandardSequenceOperators { func testMap_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs.map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(300) ]) let res = scheduler.start { xs.map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), completed(300) ]) let res = scheduler.start { xs.map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start { xs.map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), error(300, testError) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start(290) { xs.map { $0 * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), next(230, 2 * 2), next(240, 4 * 2), ] let correctSubscriptions = [ Subscription(200, 290) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 0), next(220, 1), next(230, 2), next(240, 4), error(300, testError) ]) let res = scheduler.start { xs.map { x throws -> Int in if x < 2 { return x * 2 } else { throw testError } } } let correctMessages: [Recorded<Int>] = [ next(210, 0 * 2), next(220, 1 * 2), error(230, testError) ] let correctSubscriptions = [ Subscription(200, 230) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Never() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), ]) let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ ] let correctSubscriptions = [ Subscription(200, 1000) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Empty() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), completed(300) ]) let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Range() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), completed(300) ]) let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), completed(300) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start { xs.mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), error(300, testError) ] let correctSubscriptions = [ Subscription(200, 300) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start(290) { xs.mapWithIndex { ($0 + $1) * 2 } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), next(230, (7 + 2) * 2), next(240, (8 + 3) * 2), ] let correctSubscriptions = [ Subscription(200, 290) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap1_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(150, 1), next(210, 5), next(220, 6), next(230, 7), next(240, 8), error(300, testError) ]) let res = scheduler.start { xs.mapWithIndex { x, i throws -> Int in if x < 7 { return ((x + i) * 2) } else { throw testError } } } let correctMessages: [Recorded<Int>] = [ next(210, (5 + 0) * 2), next(220, (6 + 1) * 2), error(230, testError) ] let correctSubscriptions = [ Subscription(200, 230) ] XCTAssertEqual(res.messages, correctMessages) XCTAssertEqual(xs.subscriptions, correctSubscriptions) } func testMap_DisposeOnCompleted() { _ = just("A") .map { a in return a } .subscribeNext { _ in } } func testMap1_DisposeOnCompleted() { _ = just("A") .mapWithIndex { (a, i) in return a } .subscribeNext { _ in } } } // flatMap extension ObservableStandardSequenceOperators { func testFlatMap_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), completed(960) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_InnerNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), ]) let res = scheduler.start { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_OuterNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 1000) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMap_Complete_ErrorOuter() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), error(900, testError) ]) let res = scheduler.start { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), error(900, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 900) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 900) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 900) ]) } func testFlatMap_Error_Inner() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), error(460, testError) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), error(760, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 760) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 760) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 760) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start(700) { xs.flatMap { $0 } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 700) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 700) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 700) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) var invoked = 0 let res = scheduler.start { return xs.flatMap { (x: ColdObservable<Int>) -> ColdObservable<Int> in invoked++ if invoked == 3 { throw testError } return x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), error(550, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 550) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 550) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 550) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMap_UseFunction() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) let res = scheduler.start { xs.flatMap { (x) in return interval(10, scheduler).map { _ in x } .take(x) } } XCTAssertEqual(res.messages, [ next(220, 4), next(230, 3), next(230, 4), next(240, 3), next(240, 4), next(250, 3), next(250, 4), next(260, 5), next(270, 5), next(280, 1), next(280, 5), next(290, 5), next(300, 5), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } func testFlatMapIndex_Index() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) let res = scheduler.start { xs.flatMapWithIndex { (x, i) in return just(ElementIndexPair(x, i)) } } XCTAssertEqual(res.messages, [ next(210, ElementIndexPair(4, 0)), next(220, ElementIndexPair(3, 1)), next(250, ElementIndexPair(5, 2)), next(270, ElementIndexPair(1, 3)), completed(290) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } func testFlatMapWithIndex_Complete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), completed(960) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_InnerNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), ]) let res = scheduler.start { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_OuterNotComplete() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), next(930, 401), next(940, 402), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 1000) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 960) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 950) ]) } func testFlatMapWithIndex_Complete_ErrorOuter() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), error(900, testError) ]) let res = scheduler.start { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), next(810, 304), next(860, 305), error(900, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 900) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 900) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 900) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 790) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ Subscription(850, 900) ]) } func testFlatMapWithIndex_Error_Inner() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), error(460, testError) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), next(740, 106), error(760, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 760) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 760) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 760) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ Subscription(750, 760) ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_Dispose() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) let res = scheduler.start(700) { xs.flatMapWithIndex { x, _ in x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), next(560, 301), next(580, 202), next(590, 203), next(600, 302), next(620, 303), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 700) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 700) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 605) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ Subscription(550, 700) ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(5, scheduler.createColdObservable([ error(1, testError) ])), next(105, scheduler.createColdObservable([ error(1, testError) ])), next(300, scheduler.createColdObservable([ next(10, 102), next(90, 103), next(110, 104), next(190, 105), next(440, 106), completed(460) ])), next(400, scheduler.createColdObservable([ next(180, 202), next(190, 203), completed(205) ])), next(550, scheduler.createColdObservable([ next(10, 301), next(50, 302), next(70, 303), next(260, 304), next(310, 305), completed(410) ])), next(750, scheduler.createColdObservable([ completed(40) ])), next(850, scheduler.createColdObservable([ next(80, 401), next(90, 402), completed(100) ])), completed(900) ]) var invoked = 0 let res = scheduler.start { return xs.flatMapWithIndex { (x: ColdObservable<Int>, _: Int) -> ColdObservable<Int> in invoked++ if invoked == 3 { throw testError } return x } } XCTAssertEqual(res.messages, [ next(310, 102), next(390, 103), next(410, 104), next(490, 105), error(550, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 550) ]) XCTAssertEqual(xs.recordedEvents[2].value.subscriptions, [ Subscription(300, 550) ]) XCTAssertEqual(xs.recordedEvents[3].value.subscriptions, [ Subscription(400, 550) ]) XCTAssertEqual(xs.recordedEvents[4].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[5].value.subscriptions, [ ]) XCTAssertEqual(xs.recordedEvents[6].value.subscriptions, [ ]) } func testFlatMapWithIndex_UseFunction() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(210, 4), next(220, 3), next(250, 5), next(270, 1), completed(290) ]) let res = scheduler.start { xs.flatMapWithIndex { (x, _) in return interval(10, scheduler).map { _ in x } .take(x) } } XCTAssertEqual(res.messages, [ next(220, 4), next(230, 3), next(230, 4), next(240, 3), next(240, 4), next(250, 3), next(250, 4), next(260, 5), next(270, 5), next(280, 1), next(280, 5), next(290, 5), next(300, 5), completed(300) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) } } // take extension ObservableStandardSequenceOperators { func testTake_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.take(20) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testTake_Complete_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.take(17) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(630) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 630) ]) } func testTake_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.take(10) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), completed(415) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 415) ]) } func testTake_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.take(20) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testTake_Error_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.take(17) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(630) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 630) ]) } func testTake_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start(250) { xs.take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testTake_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start(400) { xs.take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_0_DefaultScheduler() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13) ]) let res = scheduler.start { xs.take(0) } XCTAssertEqual(res.messages, [ completed(200) ]) XCTAssertEqual(xs.subscriptions, [ ]) } func testTake_Take1() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), completed(400) ]) let res = scheduler.start { xs.take(3) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), completed(270) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) } func testTake_DecrementCountsFirst() { let k = BehaviorSubject(value: false) _ = k.take(1).subscribeNext { n in k.on(.Next(!n)) } } } // skip extension ObservableStandardSequenceOperators { func testSkip_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.skip(20) } XCTAssertEqual(res.messages, [ completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Some() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.skip(17) } XCTAssertEqual(res.messages, [ completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.skip(10) } XCTAssertEqual(res.messages, [ next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Complete_Zero() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) let res = scheduler.start { xs.skip(0) } XCTAssertEqual(res.messages, [ next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), completed(690) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.skip(20) } XCTAssertEqual(res.messages, [ error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_Same() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.skip(17) } XCTAssertEqual(res.messages, [ error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) let res = scheduler.start { xs.skip(3) } XCTAssertEqual(res.messages, [ next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), error(690, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 690) ]) } func testSkip_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), ]) let res = scheduler.start(250) { xs.skip(3) } XCTAssertEqual(res.messages, [ ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 250) ]) } func testSkip_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(70, 6), next(150, 4), next(210, 9), next(230, 13), next(270, 7), next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), next(410, 15), next(415, 16), next(460, 72), next(510, 76), next(560, 32), next(570, -100), next(580, -3), next(590, 5), next(630, 10), ]) let res = scheduler.start(400) { xs.skip(3) } XCTAssertEqual(res.messages, [ next(280, 1), next(300, -1), next(310, 3), next(340, 8), next(370, 11), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } } // MARK: SkipWhile extension ObservableStandardSequenceOperators { func testSkipWhile_Complete_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), completed(330), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ completed(330) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 330) ]) XCTAssertEqual(4, invoked) } func testSkipWhile_Complete_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(6, invoked) } func testSkipWhile_Error_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), error(270, testError), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ error(270, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 270) ]) XCTAssertEqual(2, invoked) } func testSkipWhile_Error_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ next(390, 4), next(410, 17), next(450, 8), next(500, 23), error(600, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(6, invoked) } func testSkipWhile_Dispose_Before() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start(300) { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, []) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 300) ]) XCTAssertEqual(3, invoked) } func testSkipWhile_Dispose_After() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start(470) { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ next(390, 4), next(410, 17), next(450, 8) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 470) ]) XCTAssertEqual(6, invoked) } func testSkipWhile_Zero() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 return isPrime(x) } } XCTAssertEqual(res.messages, [ next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) XCTAssertEqual(1, invoked) } func testSkipWhile_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) var invoked = 0 let res = scheduler.start() { xs.skipWhile { x in invoked += 1 if invoked == 3 { throw testError } return isPrime(x) } } XCTAssertEqual(res.messages, [ error(290, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 290) ]) XCTAssertEqual(3, invoked) } func testSkipWhile_Index() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) let res = scheduler.start() { xs.skipWhileWithIndex { x, i in i < 5 } } XCTAssertEqual(res.messages, [ next(350, 7), next(390, 4), next(410, 17), next(450, 8), next(500, 23), completed(600) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 600) ]) } func testSkipWhile_Index_Throw() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), error(400, testError) ]) let res = scheduler.start() { xs.skipWhileWithIndex { x, i in i < 5 } } XCTAssertEqual(res.messages, [ next(350, 7), next(390, 4), error(400, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 400) ]) } func testSkipWhile_Index_SelectorThrows() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createHotObservable([ next(90, -1), next(110, -1), next(205, 100), next(210, 2), next(260, 5), next(290, 13), next(320, 3), next(350, 7), next(390, 4), completed(400) ]) let res = scheduler.start() { xs.skipWhileWithIndex { x, i in if i < 5 { return true } throw testError } } XCTAssertEqual(res.messages, [ error(350, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 350) ]) } }
0
// // AssignmentsViewModel.swift // Yellr // // Created by Debjit Saha on 6/5/15. // Copyright (c) 2015 wxxi. All rights reserved. // import Foundation class AssignmentsViewModel { func numberOfSections() -> Int { return 1 } func numberOfRowsInSection(section:Int) -> Int { return 5 } }
0
import UIKit import StyleKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let styleFile = Bundle.main.url(forResource: "style", withExtension: "json") { // Uses style parser within demo app //StyleKit(fileUrl: styleFile, styleParser: StyleParser())?.apply() // Uses default style parser StyleKit(fileUrl: styleFile, logLevel: .debug)?.apply() } return true } }
0
// // Tab2Main.swift // Aroha_SwiftUI // // Created by 김성헌 on 2020/07/25. // Copyright © 2020 김성헌. All rights reserved. // import Foundation import SwiftUI struct Tab4MainView:View{ var body:some View{ NavigationView{ Text("Hello World!") .navigationBarTitle(Text("마이 페이지").font(.subheadline), displayMode: .inline) } } }
0
// // Pagination.swift // GetStream-iOS // // Created by Alexey Bukhtin on 11/12/2018. // Copyright © 2018 Stream.io Inc. All rights reserved. // import Foundation /// Pagination options. public enum Pagination: Decodable { /// The default value for the pagination limit is 25. public static let defaultLimit = 25 /// Default limit is 25. (Defined in `FeedPagination.defaultLimit`) case none /// The amount of activities requested from the APIs. case limit(_ limit: Int) /// The offset of requesting activities. /// - Note: Using `lessThan` or `lessThanOrEqual` for pagination is preferable to using `offset`. case offset(_ offset: Int) /// Filter the feed on ids greater than the given value. case greaterThan(_ id: String) /// Filter the feed on ids greater than or equal to the given value. case greaterThanOrEqual(_ id: String) /// Filter the feed on ids smaller than the given value. case lessThan(_ id: String) /// Filter the feed on ids smaller than or equal to the given value. case lessThanOrEqual(_ id: String) /// Combine `Pagination`'s with each other. /// /// It's easy to use with the `+` operator. Examples: /// ``` /// var pagination = .limit(10) + .greaterThan("news123") /// pagination += .lessThan("news987") /// print(pagination) /// // It will print: /// // and(pagination: .and(pagination: .limit(10), another: .greaterThan("news123")), /// // another: .lessThan("news987")) /// ``` indirect case and(pagination: Pagination, another: Pagination) public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let urlString = try container.decode(String.self) var pagination: Pagination = .none if let urlComponents = URLComponents(string: urlString), let queryItems = urlComponents.queryItems { queryItems.forEach { queryItem in if let value = queryItem.value, !value.isEmpty { switch queryItem.name { case "limit": if let intValue = Int(value) { pagination += .limit(intValue) } case "offset": if let intValue = Int(value) { pagination += .offset(intValue) } case "id_gt": pagination += .greaterThan(value) case "id_gte": pagination += .greaterThanOrEqual(value) case "id_lt": pagination += .lessThan(value) case "id_lte": pagination += .lessThanOrEqual(value) default: break } } } } self = pagination } /// Parameters for a request. var parameters: [String: Any] { var params: [String: Any] = [:] switch self { case .none: return [:] case .limit(let limit): params["limit"] = limit case let .offset(offset): params["offset"] = offset case let .greaterThan(id): params["id_gt"] = id case let .greaterThanOrEqual(id): params["id_gte"] = id case let .lessThan(id): params["id_lt"] = id case let .lessThanOrEqual(id): params["id_lte"] = id case let .and(pagination1, pagination2): params = pagination1.parameters.merged(with: pagination2.parameters) } return params } } // MARK: - Helper Operator extension Pagination { /// An operator for combining Pagination's. public static func +(lhs: Pagination, rhs: Pagination) -> Pagination { if case .none = lhs { return rhs } if case .none = rhs { return lhs } return .and(pagination: lhs, another: rhs) } /// An operator for combining Pagination's. public static func +=(lhs: inout Pagination, rhs: Pagination) { lhs = lhs + rhs } }
0
// // JSONAPISwiftGen+JSONAPIViz.swift // // // Created by Mathew Polzin on 1/7/20. // import JSONAPISwiftGen import JSONAPIViz extension JSONAPISwiftGen.Relative.Relationship { public var vizRelationship: JSONAPIViz.Relationship { switch self { case .toMany(.required): return .toMany(.required) case .toMany(.optional): return .toMany(.optional) case .toOne(.required): return .toOne(.required) case .toOne(.optional): return .toOne(.optional) } } } extension JSONAPISwiftGen.Relative: JSONAPIViz.RelativeType { public var name: String { propertyName } public var typeName: String { swiftTypeName } public var relationship: JSONAPIViz.Relationship { relationshipType.vizRelationship } } extension ResourceObjectSwiftGen: JSONAPIViz.ResourceType { public var typeName: String { resourceTypeName } }
0
/// This file implements definition components that are allowed in any object-based definition — `ObjectDefinition`. /// So far only constants and functions belong to plain object. // MARK: - Constants /** Definition function setting the module's constants to export. */ public func constants(_ body: @escaping () -> [String: Any?]) -> AnyDefinition { return ConstantsDefinition(body: body) } /** Definition function setting the module's constants to export. */ public func constants(_ body: @autoclosure @escaping () -> [String: Any?]) -> AnyDefinition { return ConstantsDefinition(body: body) } // MARK: - Functions /** Function without arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R>( _ name: String, _ closure: @escaping () throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [], closure ) } /** Function with one argument. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument>( _ name: String, _ closure: @escaping (A0) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ArgumentType(A0.self)], closure ) } /** Function with two arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ArgumentType(A0.self), ArgumentType(A1.self)], closure ) } /** Function with three arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self) ], closure ) } /** Function with four arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self) ], closure ) } /** Function with five arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self) ], closure ) } /** Function with six arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self) ], closure ) } /** Function with seven arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument, A6: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5, A6) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self), ArgumentType(A6.self) ], closure ) } /** Function with eight arguments. */ @available(*, deprecated, renamed: "asyncFunction") public func function<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument, A6: AnyArgument, A7: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5, A6, A7) throws -> R ) -> AnyFunction { return ConcreteFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self), ArgumentType(A6.self), ArgumentType(A7.self) ], closure ) } // MARK: - Asynchronous functions /** Asynchronous function without arguments. */ public func asyncFunction<R>( _ name: String, _ closure: @escaping () throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [], closure ) } /** Asynchronous function with one argument. */ public func asyncFunction<R, A0: AnyArgument>( _ name: String, _ closure: @escaping (A0) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ArgumentType(A0.self)], closure ) } /** Asynchronous function with two arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ArgumentType(A0.self), ArgumentType(A1.self)], closure ) } /** Asynchronous function with three arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self) ], closure ) } /** Asynchronous function with four arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self) ], closure ) } /** Asynchronous function with five arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self) ], closure ) } /** Asynchronous function with six arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self) ], closure ) } /** Asynchronous function with seven arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument, A6: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5, A6) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self), ArgumentType(A6.self) ], closure ) } /** Asynchronous function with eight arguments. */ public func asyncFunction<R, A0: AnyArgument, A1: AnyArgument, A2: AnyArgument, A3: AnyArgument, A4: AnyArgument, A5: AnyArgument, A6: AnyArgument, A7: AnyArgument>( _ name: String, _ closure: @escaping (A0, A1, A2, A3, A4, A5, A6, A7) throws -> R ) -> AnyFunction { return AsyncFunction( name, argTypes: [ ArgumentType(A0.self), ArgumentType(A1.self), ArgumentType(A2.self), ArgumentType(A3.self), ArgumentType(A4.self), ArgumentType(A5.self), ArgumentType(A6.self), ArgumentType(A7.self) ], closure ) } // MARK: - Events /** Defines event names that the object can send to JavaScript. */ public func events(_ names: String...) -> AnyDefinition { return EventsDefinition(names: names) } /** Function that is invoked when the first event listener is added. */ public func onStartObserving(_ body: @escaping () -> Void) -> AnyFunction { return ConcreteFunction("startObserving", argTypes: [], body) } /** Function that is invoked when all event listeners are removed. */ public func onStopObserving(_ body: @escaping () -> Void) -> AnyFunction { return ConcreteFunction("stopObserving", argTypes: [], body) }
0
// // OAuthSwiftAlamofireTests.swift // OAuthSwiftAlamofireTests // // Created by phimage on 06/10/16. // Copyright © 2016 phimage. All rights reserved. // import XCTest @testable import OAuthSwiftAlamofire import OAuthSwift import Alamofire class OAuthSwiftAlamofireTests: XCTestCase { let callbackURL = "test://callback" let oauth = OAuth1Swift( consumerKey: "key", consumerSecret: "secret", requestTokenUrl: "http://term.ie/oauth/example/request_token.php", authorizeUrl: "automatic://host/autorize", accessTokenUrl: "http://term.ie/oauth/example/access_token.php" ) override func setUp() { super.setUp() oauth.allowMissingOAuthVerifier = true oauth.authorizeURLHandler = TestOAuthSwiftURLHandler( callbackURL: callbackURL, authorizeURL: "automatic://host/autorize", version: .oauth1 ) // 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 testOAuthbinSuccess() { let expectation = self.expectation(description: "auth should succeed") oauth.authorize( withCallbackURL: URL(string:callbackURL)!) { result in switch result { case .success: expectation.fulfill() case .failure (let error): XCTFail("The failure handler should not be called. \(error)") } } waitForExpectations(timeout: 20, handler: nil) let oauth_token = "accesskey" let oauth_token_secret = "accesssecret" XCTAssertEqual(oauth.client.credential.oauthToken, oauth_token) XCTAssertEqual(oauth.client.credential.oauthTokenSecret, oauth_token_secret) } func testAlamofire() { if oauth.client.credential.oauthToken.isEmpty { testOAuthbinSuccess() } let expectation = self.expectation(description: "auth should succeed") let interceptor = oauth.requestInterceptor let sessionManager = Session(interceptor: interceptor) let param = "method=foo&bar=baz" // TODO http://oauthbin.com no more exist, test could not be done sessionManager.request("http://term.ie/oauth/example/echo_api.php?\(param)", method: .get).validate().responseString { response in switch response.result { case .success(let value): XCTAssertEqual(param, value) expectation.fulfill() case .failure(let e): XCTFail("The failure handler should not be called. \(e)") } } waitForExpectations(timeout: 20, handler: nil) } // Note: oauthbin.com doesn't seem to exist anymore (domain name expire) and couldn't find another easily usable test server // This test case needs to be updated if and when oauthbin.com comes back. func testMultipleRequests() { let exp1 = self.expectation(description: "auth should retry 1st request") let exp2 = self.expectation(description: "auth should retry 2nd request") let oauth2 = OAuth2Swift( consumerKey: "tbd", consumerSecret: "tbd", authorizeUrl: "tbd", accessTokenUrl: "tbd", responseType: "code") let interceptor = oauth2.requestInterceptor let session = Session(interceptor: interceptor) session.request("tbd", method: .get).validate().response { response in XCTAssert(response.response?.statusCode == 200, "Failed request 1 auth") exp1.fulfill() } session.request("tbd").validate().response { response in XCTAssert(response.response?.statusCode == 200, "Failed request 2 auth") exp2.fulfill() } waitForExpectations(timeout: 5.0, handler: nil) } } // MARK: FROM Xcode test class TestOAuthSwiftURLHandler: NSObject, OAuthSwiftURLHandlerType { let callbackURL: String let authorizeURL: String let version: OAuthSwiftCredential.Version var accessTokenResponse: AccessTokenResponse? var authorizeURLComponents: URLComponents? { return URLComponents(url: URL(string: self.authorizeURL)!, resolvingAgainstBaseURL: false) } init(callbackURL: String, authorizeURL: String, version: OAuthSwiftCredential.Version) { self.callbackURL = callbackURL self.authorizeURL = authorizeURL self.version = version } @objc func handle(_ url: URL) { switch version { case .oauth1: handleV1(url) case .oauth2: handleV2(url) } } func handleV1(_ url: URL) { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) if let queryItems = urlComponents?.queryItems { for queryItem in queryItems { if let value = queryItem.value , queryItem.name == "oauth_token" { let url = "\(self.callbackURL)?oauth_token=\(value)" OAuthSwift.handle(url: URL(string: url)!) } } } urlComponents?.query = nil if urlComponents != authorizeURLComponents { print("bad authorizeURL \(url), must be \(authorizeURL)") return } // else do nothing } func handleV2(_ url: URL) { var url = "\(self.callbackURL)/" if let response = accessTokenResponse { switch response { case .accessToken(let token): url += "?access_token=\(token)" case .code(let code, let state): url += "?code='\(code)'" if let state = state { url += "&state=\(state)" } case .error(let error,let errorDescription): let e = error.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! let ed = errorDescription.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! url += "?error='\(e)'&errorDescription='\(ed)'" case .none: break // nothing } } OAuthSwift.handle(url: URL(string: url)!) } } enum AccessTokenResponse { case accessToken(String), code(String, state:String?), error(String,String), none var responseType: String { switch self { case .accessToken: return "token" case .code: return "code" case .error: return "code" case .none: return "code" } } }
0
import Foundation @testable import Frisbee class URLWithQueryTrhrowErrorFakeBuildable: URLQueriableAdapter { var errorToThrow: FrisbeeError! func build<Query: Encodable>(withUrl url: String, query: Query) throws -> URL { throw errorToThrow } func build<Query: Encodable>(withUrl url: URL, query: Query) throws -> URL { throw errorToThrow } }
0
// // KaleidoscopeLangTests.swift // KaleidoscopeLangTests // // Created by Ben Cochran on 11/8/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import XCTest @testable import KaleidoscopeLang class LexerTests: XCTestCase { func testIdentifier() { assertMatched(identifierToken, "a".characters) assertMatched(identifierToken, "some".characters) assertMatched(identifierToken, "_some".characters) assertMatched(identifierToken, "__some_".characters) assertMatched(identifierToken, "__some".characters) assertUnmatched(identifierToken, "2name".characters) assertUnmatched(identifierToken, "2".characters) } func testSimpleExpressions() { assertStringToTokens("a+b", [.Identifier("a"), .Character("+"), .Identifier("b")]) assertStringToTokens( "def add(a b) a + b", [ .Def, .Identifier("add"), .Character("("), .Identifier("a"), .Identifier("b"), .Character(")"), .Identifier("a"), .Character("+"), .Identifier("b") ] ) assertStringToTokens( "extern atan2(a b)", [ .Extern, .Identifier("atan2"), .Character("("), .Identifier("a"), .Identifier("b"), .Character(")") ] ) } func testMultilineExpressions() { assertStringToTokens( "def add(a b)\n\ta + b", [ .Def, .Identifier("add"), .Character("("), .Identifier("a"), .Identifier("b"), .Character(")"), .Identifier("a"), .Character("+"), .Identifier("b") ] ) } func testWhitespaceAtStart() { assertStringToTokens( "\textern atan2(y x);", [ .Extern, .Identifier("atan2"), .Character("("), .Identifier("y"), .Identifier("x"), .Character(")"), .EndOfStatement ] ) } } class ParserTests: XCTestCase { func testParser() { assertTokensToTopLevelExpression( [.Extern, .Identifier("sin"), .Character("("), .Identifier("angle"), .Character(")"), .EndOfStatement], PrototypeExpression(name: "sin", args: ["angle"]) ) } } class CombinedTests: XCTestCase { func testExtern() { assertStringToTopLevelExpression( "extern sin(angle);", PrototypeExpression(name: "sin", args: ["angle"]) ) } func testBinaryOperator() { assertStringToValueExpression( "a + b", BinaryOperatorExpression( code: "+", left: VariableExpression("a"), right: VariableExpression("b") ) ) } func testComplexBinaryOperator() { assertStringToValueExpression( "a + sin(b) - c", BinaryOperatorExpression( code: "+", left: VariableExpression("a"), right: BinaryOperatorExpression( code: "-", left: CallExpression( callee: "sin", args: [ VariableExpression("b") ] ), right: VariableExpression("c") ) ) ) } func testDefinition() { assertStringToTopLevelExpression( "def add(a b) a + b;", FunctionExpression( prototype: PrototypeExpression( name: "add", args: [ "a", "b" ] ), body: BinaryOperatorExpression( code: "+", left: VariableExpression("a"), right: VariableExpression("b") ) ) ) } func testComments() { assertStringToTokens( "a + b; # this is addition\n", [.Identifier("a"), .Character("+"), .Identifier("b"), .EndOfStatement] ) assertStringToTokens("# this is only a comment\n", []) } func testTopLevelNumbers() { assertStringToValueExpression("0", NumberExpression(0)) assertStringToValueExpression("00.00", NumberExpression(0)) assertStringToValueExpression("10.0", NumberExpression(10)) assertStringToValueExpression("10.01", NumberExpression(10.01)) } }
0
// // BuilderPatternApp.swift // Shared // // Created by Malav Soni on 13/09/20. // import SwiftUI @main struct BuilderPatternApp: App { var body: some Scene { WindowGroup { ContentView() } } }
0
// // AppRouter.swift // Sonar // // Created by NHSX on 03/04/2020. // Copyright © 2020 NHSX. All rights reserved. // import Foundation import UIKit protocol ScreenMaking { func makeViewController(for screen: Screen) -> UIViewController } class AppRouter { private let window: UIWindow private let screenMaker: ScreenMaking init(window: UIWindow, screenMaker: ScreenMaking) { self.window = window self.screenMaker = screenMaker } func route(to screen: Screen) { window.rootViewController = screenMaker.makeViewController(for: screen) } }
0
// // Attribute.swift // Introspective // // Created by Bryan Nova on 7/26/18. // Copyright © 2018 Bryan Nova. All rights reserved. // import Foundation import Common // sourcery: AutoMockable public protocol Attribute { /// This is a name that should be understandable by the user var name: String { get } var pluralName: String { get } /// This needs to be able to be used by an NSPredicate within a PredicateAttributeRestriction var variableName: String? { get } /// This is an explanation of this attribute that should be able to be presented to the user. var extendedDescription: String? { get } /// This represents whether or not this attribute is optional var optional: Bool { get } var valueType: Any.Type { get } /// This should be presentable to the user to understand what type of attribute this is var typeName: String { get } func isValid(value: Any?) -> Bool func equalTo(_ otherAttribute: Attribute) -> Bool func convertToDisplayableString(from value: Any?) throws -> String func valuesAreEqual(_ first: Any?, _ second: Any?) throws -> Bool } public extension Attribute { func equalTo(_ otherAttribute: Attribute) -> Bool { type(of: self) == type(of: otherAttribute) && name.lowercased() == otherAttribute.name.lowercased() && extendedDescription == otherAttribute.extendedDescription && variableName == otherAttribute.variableName && optional == otherAttribute.optional } } open class AttributeBase<ValueType>: Attribute { /// This is a name that should be understandable by the user public final let name: String public final let pluralName: String /// This needs to be able to be used by an NSPredicate within a PredicateAttributeRestriction public final let variableName: String? /// This is an explanation of this attribute that should be able to be presented to the user. public final let extendedDescription: String? /// This represents whether or not this attribute is optional public final let optional: Bool public let valueType: Any.Type = ValueType.self /// This should be presentable to the user to understand what type of attribute this is open var typeName: String { Log().error("Did not override typeName for %@", String(describing: type(of: self))) return "" } /// - Parameter pluralName: If nil, use `name` parameter. /// - Parameter description: If nil, no description is needed for the user to understand this attribute. /// - Parameter variableName: This should be usable by an NSPredicate to identify the associated variable. If nil, use `name` parameter. public init( name: String, pluralName: String? = nil, description: String? = nil, variableName: String? = nil, optional: Bool = false ) { self.name = name self.pluralName = pluralName ?? name extendedDescription = description self.variableName = variableName self.optional = optional } open func isValid(value: Any?) -> Bool { value != nil || optional } open func convertToDisplayableString(from _: Any?) throws -> String { throw NotOverriddenError(functionName: "convertToDisplayableString") } public final func valuesAreEqual(_ first: Any?, _ second: Any?) throws -> Bool { guard let first = first else { return second == nil } guard let second = second else { return false } guard let castedFirst = first as? ValueType else { Log().error("Failed to cast first value when testing equality: %@", String(describing: first)) return false } guard let castedSecond = second as? ValueType else { Log().error("Failed to cast second value when testing equality: %@", String(describing: first)) return false } return typedValuesAreEqual(castedFirst, castedSecond) } open func typedValuesAreEqual(_: ValueType, _: ValueType) -> Bool { Log().error("typedValuesAreEqual not overridden for %@", String(describing: type(of: self))) return true } }
0
// // ViewController.swift // TestWS // // Created by Rajan Shah on 10/04/18. // Copyright © 2018 Rajan Shah. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnGetDelegate_Clicked(_ sender: Any) { let ws = Webservice() ws.delegate = self ws.RequestForGet(strUrl: "https://jsonplaceholder.typicode.com/posts", apiIdentifier: "get") } @IBAction func btnGet_Clicked(_ sender: Any) { let ws = Webservice() ws.RequestForGet(strUrl: "https://jsonplaceholder.typicode.com/posts", completionHandler: { (response) in print("response complition",response) }, errorCompletionHandler: { (error) in print("response complition error",error.localizedDescription) }) { (response) in print("response complition fail",response) } } @IBAction func btnPostDelegate_Clicked(_ sender: Any) { let ws = Webservice() let parameterDic = [ "title": "foo", "body": "bar", "userId": 1 ] as [String : Any] ws.delegate = self ws.RequestForPost(url: "https://jsonplaceholder.typicode.com/posts", postData: parameterDic, apiIdentifier: "post") } @IBAction func btnPost_Clicked(_ sender: Any) { let ws = Webservice() let parameterDic = [ "title": "foo", "body": "bar", "userId": 1 ] as [String : Any] ws.RequestForPost(url: "https://jsonplaceholder.typicode.com/posts", postData: parameterDic, completionHandler: { (response) in print("response complition",response) }, errorCompletionHandler: { (error) in print("response complition error",error.localizedDescription) }) { (response) in print("response complition fail",response) } } } extension ViewController : WebserviceDelegate { func webserviceResponseInArraySuccess(response: [Any], apiIdentifier: String) { if apiIdentifier == "get"{ print(response) } else if apiIdentifier == "post"{ print(response) } } func webserviceResponseSuccess(response: [String : Any], apiIdentifier: String) { if apiIdentifier == "get"{ print(response) } else if apiIdentifier == "post"{ print(response) } } func webserviceResponseError(error: Error?, apiIdentifier: String) { print(error?.localizedDescription ?? "") } func webserviceResponseFail(response: [String : Any], apiIdentifier: String) { print(response) } }
0
// // ViewController.swift // LightBulb // // Created by Jim Campagno on 9/17/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lightBulb: UIImageView! override func viewDidLoad() { super.viewDidLoad() lightBulb.backgroundColor = UIColor.blue } @IBAction func colorSelected(_ sender: UISegmentedControl) { print(sender.selectedSegmentIndex) switch sender.selectedSegmentIndex { case 0: lightBulb.backgroundColor = UIColor.red case 1: lightBulb.backgroundColor = UIColor.yellow case 2: lightBulb.backgroundColor = UIColor.blue case 3: lightBulb.backgroundColor = UIColor.green default: lightBulb.backgroundColor = UIColor.black } } }
0
// // ChildProtocol.swift // MockingbirdTestsHost // // Created by Andrew Chang on 8/17/19. // Copyright © 2019 Bird Rides, Inc. All rights reserved. // import Foundation protocol ChildProtocol: ParentProtocol { // MARK: Instance var childPrivateSetterInstanceVariable: Bool { get } var childInstanceVariable: Bool { get set } func childTrivialInstanceMethod() func childParameterizedInstanceMethod(param1: Bool, _ param2: Int) -> Bool // MARK: Static static var childPrivateSetterStaticVariable: Bool { get } static var childStaticVariable: Bool { get set } static func childTrivialStaticMethod() static func childParameterizedStaticMethod(param1: Bool, _ param2: Int) -> Bool }
0
// // PKMPokemon+Utils.swift // Pokedex // // Created by Marlon David Ruiz Arroyave on 27/02/21. // import SwiftUI import PokemonAPI enum PokemonType: String, Decodable, CaseIterable, Identifiable { var id: String { rawValue } case fire = "fire" case grass = "grass" case water = "water" case poison = "poison" case flying = "flying" case electric = "electric" case bug = "bug" case normal = "normal" } extension PKMPokemon { func formattedNumber() -> String { String(format: "#%03d", arguments: [id ?? 0]) } func primaryType() -> String? { guard let primary = types?.first else { return nil } return primary.type?.name?.capitalized } func secondaryType() -> String? { let index = 2 guard index < types?.count ?? 0, let secondary = types?[2] else { return nil } return secondary.type?.name?.capitalized } static func pokemonMock() -> PKMPokemon? { guard let path = Bundle.main.path(forResource: "bulbasaur", ofType: "json") else { return nil } guard let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path)) else { print("failed data") return nil } guard let pokemon: PKMPokemon = try? PKMPokemon.decoder.decode(PKMPokemon.self, from: jsonData) else { print("failed decoder") return nil } return pokemon } }
0
// // ViewNavigation.swift // Donations // // Created by Daniel Mandea on 25/06/2020. // Copyright © 2020 IBM CJ COVID. All rights reserved. // import SwiftUI protocol TransitionLinkType { var transition: AnyTransition { get } } struct TransitionLink<Content, Destination>: View where Content: View, Destination: View { @Binding var isPresented: Bool var content: () -> Content var destination: () -> Destination var linkType: TransitionLinkType init(isPresented: Binding<Bool>, linkType: TransitionLinkType, @ViewBuilder destination: @escaping () -> Destination, @ViewBuilder content: @escaping () -> Content) { self.content = content self.destination = destination self._isPresented = isPresented self.linkType = linkType } var body: some View { ZStack { if self.isPresented { self.destination() .transition(self.linkType.transition) } else { self.content() } } } } struct ModaLinkViewModifier<Destination>: ViewModifier where Destination: View { @Binding var isPresented: Bool var linkType: TransitionLinkType var destination: () -> Destination func body(content: Self.Content) -> some View { TransitionLink(isPresented: self.$isPresented, linkType: linkType, destination: { self.destination() }, content: { content }) } } extension View { func modalLink<Destination: View>(isPresented: Binding<Bool>, linkType: TransitionLinkType, destination: @escaping () -> Destination) -> some View { self.modifier(ModaLinkViewModifier(isPresented: isPresented, linkType: linkType, destination: destination)) } }
0
import Foundation public struct SuggestResponse: Decodable { public let took: Int public let timedOut: Bool public let shards: Shards public let hits: HitsContainer? public let suggest: [String: [SuggestResult]] public var suggestions: [String] { return suggest.values .flatMap { $0 } .flatMap { $0.options } .compactMap { $0.text } } public struct Shards: Decodable { public let total: Int public let successful: Int public let skipped: Int public let failed: Int } public struct HitsContainer: Decodable { public let total: Int public let maxScore: Decimal? } public struct SuggestResult: Decodable { public let text: String public let offset: Int public let length: Int public let options: [SuggestOption] } public struct SuggestOption: Decodable { public let id: String public let text: String enum CodingKeys: String, CodingKey { case id = "_id" case text } } enum CodingKeys: String, CodingKey { case took case timedOut = "timed_out" case shards = "_shards" case hits case suggest } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.took = try container.decode(Int.self, forKey: .took) self.timedOut = try container.decode(Bool.self, forKey: .timedOut) self.shards = try container.decode(Shards.self, forKey: .shards) self.hits = try container.decode(HitsContainer.self, forKey: .hits) self.suggest = try container.decode([String: [SuggestResult]].self, forKey: .suggest) } }
0
// // NewsView.swift // ManaGuide // // Created by Vito Royeca on 3/30/22. // import SwiftUI import BetterSafariView import FeedKit import SDWebImageSwiftUI struct NewsView: View { #if os(iOS) @Environment(\.horizontalSizeClass) private var horizontalSizeClass #endif @StateObject var viewModel = NewsViewModel() @State private var currentFeed: FeedItem? = nil var body: some View { Group { if viewModel.isBusy { BusyView() } else if viewModel.isFailed { ErrorView { viewModel.fetchData() } } else { #if os(iOS) if horizontalSizeClass == .compact { compactView } else { regularView } #else regularView #endif } } .onAppear { viewModel.fetchData() } } func safariView(with url: URL) -> SafariView { return SafariView( url: url, configuration: SafariView.Configuration( entersReaderIfAvailable: true, barCollapsingEnabled: true) ) .preferredBarAccentColor(.clear) .preferredControlAccentColor(.accentColor) .dismissButtonStyle(.close) } var compactView: some View { List { ForEach(viewModel.feeds, id:\.id) { feed in let tap = TapGesture() .onEnded { _ in currentFeed = feed } NewsFeedRowView(item: feed) .gesture(tap) .listRowSeparator(.hidden) .padding(.bottom) } } .listStyle(.plain) .safariView(item: $currentFeed) { currentFeed in SafariView( url: URL(string: currentFeed.url ?? "")!, configuration: SafariView.Configuration( entersReaderIfAvailable: false, barCollapsingEnabled: true) ) .preferredBarAccentColor(.clear) // .preferredControlAccentColor(.accentColor) .dismissButtonStyle(.close) } .navigationBarTitle("News") } var regularView: some View { ScrollView() { LazyVGrid(columns: [GridItem](repeating: GridItem(.flexible()), count: 2), pinnedViews: []) { ForEach(viewModel.feeds, id:\.id) { feed in let tap = TapGesture() .onEnded { _ in currentFeed = feed } NewsFeedRowView(item: feed) .frame(height: 200) .padding() .gesture(tap) } } .safariView(item: $currentFeed) { currentFeed in SafariView( url: URL(string: currentFeed.url ?? "")!, configuration: SafariView.Configuration( entersReaderIfAvailable: false, barCollapsingEnabled: true) ) .preferredBarAccentColor(.clear) // .preferredControlAccentColor(.accentColor) .dismissButtonStyle(.close) } .padding() .navigationBarTitle("News") } } } // MARK: - Previous struct NewsView_Previews: PreviewProvider { static var previews: some View { NavigationView { NewsView() } } }
0
// // AwardsTests.swift // PerformanceTests // // Created by Tor Rafsol Løseth on 2021-02-11. // import XCTest @testable import TourDeForce class AwardTests: BaseTestCase { func testAwardCalculationPerformance() throws { // Create a significant amount of test data. for _ in 1...100 { try dataController.createSampleData() } // Simulate lots of awards to check. let awards = Array(repeating: Award.allAwards, count: 25).joined() XCTAssertEqual(awards.count, 500, "This checks the awards count is constant. Change this if you add awards.") measure { _ = awards.filter(dataController.hasEarned) } } }
0
import UIKit final class AddCustomNodeViewLayout: UIView { let navigationBar: BaseNavigationBar = { let navBar = BaseNavigationBar() navBar.set(.present) return navBar }() let contentView: ScrollableContainerView = { let view = ScrollableContainerView() view.stackView.isLayoutMarginsRelativeArrangement = true view.stackView.layoutMargins = UIEdgeInsets(top: 24.0, left: 0.0, bottom: 0.0, right: 0.0) return view }() let nodeNameInputView = UIFactory.default.createCommonInputView() let nodeAddressInputView = UIFactory.default.createCommonInputView() let addNodeButton = TriangularedButton() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .black setupLayout() addNodeButton.applyEnabledStyle() applyLocalization() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } var locale = Locale.current { didSet { applyLocalization() } } private func applyLocalization() { nodeNameInputView.animatedInputField.title = R.string.localizable.networkInfoName( preferredLanguages: locale.rLanguages ) nodeAddressInputView.animatedInputField.title = R.string.localizable.networkInfoAddress( preferredLanguages: locale.rLanguages ) addNodeButton.imageWithTitleView?.title = R.string.localizable.addNodeButtonTitle( preferredLanguages: locale.rLanguages ) navigationBar.setTitle(R.string.localizable.addNodeButtonTitle( preferredLanguages: locale.rLanguages )) } private func setupLayout() { addSubview(navigationBar) addSubview(contentView) addSubview(addNodeButton) contentView.stackView.addArrangedSubview(nodeNameInputView) contentView.stackView.addArrangedSubview(nodeAddressInputView) navigationBar.snp.makeConstraints { make in make.leading.top.trailing.equalToSuperview() } addNodeButton.snp.makeConstraints { make in make.leading.equalToSuperview().offset(UIConstants.bigOffset) make.trailing.equalToSuperview().inset(UIConstants.bigOffset) make.bottom.equalTo(safeAreaLayoutGuide).inset(UIConstants.bigOffset) make.height.equalTo(UIConstants.actionHeight) } contentView.snp.makeConstraints { make in make.top.equalTo(navigationBar.snp.bottom) make.leading.trailing.equalToSuperview() make.bottom.equalTo(addNodeButton.snp.top).inset(UIConstants.bigOffset) } nodeNameInputView.snp.makeConstraints { make in make.width.equalToSuperview().inset(UIConstants.defaultOffset * 2) make.height.equalTo(UIConstants.actionHeight) } nodeAddressInputView.snp.makeConstraints { make in make.width.equalToSuperview().inset(UIConstants.defaultOffset * 2) make.height.equalTo(UIConstants.actionHeight) } contentView.stackView.setCustomSpacing(UIConstants.bigOffset, after: nodeNameInputView) } func handleKeyboard(frame: CGRect) { addNodeButton.snp.updateConstraints { make in make.bottom.equalTo(safeAreaLayoutGuide).inset(frame.height + UIConstants.bigOffset) } } }
0
// // SendAdditionalFields.swift // Tangem // // Created by Andrew Son on 17/12/20. // Copyright © 2020 Tangem AG. All rights reserved. // import Foundation import TangemSdk import BlockchainSdk enum SendAdditionalFields { case memo case destinationTag case none static func fields(for blockchain: Blockchain) -> SendAdditionalFields { switch blockchain { case .stellar, .binance: return .memo case .xrp: return .destinationTag default: return .none } } }
0
// // AppDelegate.swift // LotifyMe // // Created by Daniel K. Chan on 1/24/15. // Copyright (c) 2015 LocoLabs. All rights reserved. // import UIKit import CoreData import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // Allow Notifications var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound; var setting = UIUserNotificationSettings(forTypes: type, categories: nil); application.registerUserNotificationSettings(setting); application.registerForRemoteNotifications(); // Nav Bar Styling var navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = UIColor.whiteColor() navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.whiteColor()] navigationBarAppearace.barTintColor = navBarBackgroundColorGlobal // Status Bar Styling UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) return true } // Notifications vvv // var localNotification:UILocalNotification = UILocalNotification() // localNotification.alertAction = "Testing notifications on iOS8" // localNotification.alertBody = "Woww it works!!" // localNotification.fireDate = NSDate(timeIntervalSinceNow: 10) // UIApplication.sharedApplication().scheduleLocalNotification(localNotification) // Notifications ^^^ func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Fabric.with([Crashlytics()]) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "LocoLabs.asasdasd" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Session", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Session.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
0
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(PQVExtensionTests.allTests), ] } #endif
0
// // HomeViewModel.swift // Todo // // Created by Fei Yun on 2021-06-13. // import SwiftUI import CoreData class HomeViewModel:ObservableObject{ @Published var content = "" @Published var date = Date() // create new sheet @Published var isNewData = false // checking and update date //storage updated item @Published var updateItem : Task! let calender = Calendar.current func checkDate()->String{ if calender.isDateInToday(date){ return "Today" } else if calender.isDateInTomorrow(date){ return "Tomorrow" } else{ return "Other Date" } } func updateDate(value:String){ if value == "Today"{ date=Date() } else if value == "Tomorrow" { date = calender.date(byAdding: .day, value: 1, to: Date())! } else { // do sth } } func writeData(context:NSManagedObjectContext){ //update data if updateItem != nil{ updateItem.date = date updateItem.content = content try! context.save() //remove updating item after updated updateItem = nil isNewData.toggle() content = "" date = Date() return } let newTask = Task(context: context) newTask.date=date newTask.content=content // saving do{ try context.save() isNewData.toggle() content = "" date = Date() } catch{ print(error.localizedDescription) } } func editItem(item:Task){ updateItem=item //toggle the item date=item.date! content=item.content! isNewData.toggle() } }
0
//: [Previous](@previous) /* Contiguous Subarrays You are given an array arr of N integers. For each index i, you are required to determine the number of contiguous subarrays that fulfill the following conditions: The value at index i must be the maximum element in the contiguous subarrays, and These contiguous subarrays must either start from or end on index i. Signature int[] countSubarrays(int[] arr) Input Array arr is a non-empty list of unique integers that range between 1 to 1,000,000,000 Size N is between 1 and 1,000,000 Output An array where each index i contains an integer denoting the maximum number of contiguous subarrays of arr[i] Example: arr = [3, 4, 1, 6, 2] output = [1, 3, 1, 5, 1] Explanation: For index 0 - [3] is the only contiguous subarray that starts (or ends) with 3, and the maximum value in this subarray is 3. For index 1 - [4], [3, 4], [4, 1] For index 2 - [1] For index 3 - [6], [6, 2], [1, 6], [4, 1, 6], [3, 4, 1, 6] For index 4 - [2] So, the answer for the above input is [1, 3, 1, 5, 1] */ import Foundation func countSubarrays(arr: [Int]) -> [Int] { // Write your code here var result: [Int] = [] func backtracking(_ currentNumber: Int, _ index: Int,_ increasing: Bool) -> Int { if index < 0 || index >= arr.count { return 0 } if arr[currentNumber] > arr[index] { if increasing { return 1 + backtracking(currentNumber, index+1, true) } else { return 1 + backtracking(currentNumber, index-1, false) } } else { return 0 } } for index in 0..<arr.count { let sum = backtracking(index, index+1, true) + backtracking(index, index-1, false) + 1 if sum > 0 { result.append(sum) } } return result; } countSubarrays(arr: [3, 4, 1, 6, 2]) //: [Next](@next)
0
// // TreeNode.swift // TreePrinterTests // // Created by Casey Liss on 3/3/20. // Copyright © 2020 Limitliss LLC. All rights reserved. // import Foundation import TreePrinter struct TreeNode { let title: String let subNodes: [TreeNode] } extension TreeNode { static var sampleTree: TreeNode { let depthThree = TreeNode(title: "Leaf Depth Three", subNodes: []) let depthTwoA = TreeNode(title: "Branch Depth Two A", subNodes: []) let depthTwoB = TreeNode(title: "Branch Depth Two B", subNodes: [depthThree]) let depthTwoC = TreeNode(title: "Branch Depth Two C", subNodes: []) let depthOneA = TreeNode(title: "Branch Depth One A", subNodes: [depthTwoA, depthTwoB, depthTwoC]) let depthOneB = TreeNode(title: "Branch Depth One B", subNodes: []) let root = TreeNode(title: "Root", subNodes: [depthOneA, depthOneB]) return root } static var sampleOneItemAtDepthZeroTree: TreeNode { return TreeNode(title: "Zero Depth", subNodes: [ TreeNode(title: "Depth One", subNodes: [ TreeNode(title: "Depth Two A", subNodes: []), TreeNode(title: "Depth Two B", subNodes: [ TreeNode(title: "Depth Three", subNodes: []) ]), TreeNode(title: "Depth Two C", subNodes: []) ]) ]) } } extension TreeNode: TreeRepresentable { var name: String { self.title } var subnodes: [TreeNode] { self.subNodes} }
0
struct Link { static var links = [JSON]() static func load(config: Config) throws { let linkJSON = try config.get("link") as JSON links = linkJSON["linklist"]?.array ?? [] } }
0
// // YFNavigationViewController.swift // YFLiveTV // // Created by guopenglai on 2018/1/24. // Copyright © 2018年 guopenglai. All rights reserved. // import UIKit class YFNavigationViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() //隐藏系统导航栏 self.isNavigationBarHidden = true // Do any additional setup after loading the view. } 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. } */ }
0
// // Upgrade.swift // // // Created by phimage on 26/04/2020. // import Foundation import ArgumentParser struct Upgrade: ParsableCommand { static let configuration = CommandConfiguration(abstract: "Upgrade kaluza") let url = URL(string: "https://mesopelagique.github.io/kaluza-cli/install.sh")! func run() { let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("install-kaluza.sh") try? FileManager.default.removeItem(at: tempURL) guard url.download(to: tempURL) else { log(.error, "Failed to download the upgrade script") return } do { // TODO maybe process must be killed to be replaced if let output = try Bash.execute(commandName: "bash", arguments: [tempURL.path]) { log(.info, output) } } catch { log(.error, "\(error)") } try? FileManager.default.removeItem(at: tempURL) } }
0
// // File.swift // // // Created by Igor Savelev on 04/12/2021. // import Foundation public enum ImageIOError: Error { case canNotCreateImageSource case canNotCopyImageSource case canNotCreateImageDestination case canNotFinalizeImageDestination }
0
import XCTest @testable import KauppaAccountsTests @testable import KauppaCartTests @testable import KauppaCoreTests @testable import KauppaCouponTests @testable import KauppaNaamioTests @testable import KauppaOrdersTests @testable import KauppaProductsTests @testable import KauppaShipmentsTests @testable import KauppaTaxTests XCTMain([ testCase(TestAccountsService.allTests), testCase(TestAccountsRepository.allTests), testCase(TestAccountTypes.allTests), testCase(TestArraySet.allTests), testCase(TestCache.allTests), testCase(TestCoreTypes.allTests), testCase(TestDatabase.allTests), testCase(TestMailService.allTests), testCase(TestRouting.allTests), testCase(TestServiceClient.allTests), testCase(TestCartRepository.allTests), testCase(TestCartService.allTests), testCase(TestCartTypes.allTests), testCase(TestOrdersRepository.allTests), testCase(TestOrdersService.allTests), testCase(TestOrdersWithCoupons.allTests), testCase(TestRefunds.allTests), testCase(TestReturns.allTests), testCase(TestShipmentUpdates.allTests), testCase(TestCouponRepository.allTests), testCase(TestCouponService.allTests), testCase(TestCouponTypes.allTests), testCase(TestNaamioBridgeService.allTests), testCase(TestProductsRepository.allTests), testCase(TestProductsService.allTests), testCase(TestProductTypes.allTests), testCase(TestProductVariants.allTests), testCase(TestProductAttributes.allTests), testCase(TestShipmentsRepository.allTests), testCase(TestShipmentsService.allTests), testCase(TestTaxRepository.allTests), testCase(TestTaxService.allTests), testCase(TestTaxTypes.allTests) ])
0
// // PeripheralTableRow.swift // UUSwiftBluetoothTester // // Created by Ryan DeVore on 8/13/21. // import UIKit import UUSwiftBluetooth class PeripheralTableRow: UITableViewCell { @IBOutlet weak var friendlyNameLabel: UILabel! @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var rssiLabel: UILabel! @IBOutlet weak var connectionStateLabel: UILabel! @IBOutlet weak var timeSinceLastUpdateLabel: UILabel! func update(peripheral: UUPeripheral) { friendlyNameLabel.text = peripheral.friendlyName idLabel.text = "\(peripheral.identifier)\nConnectable: \(peripheral.isConnectable)" rssiLabel.text = "\(peripheral.rssi)" connectionStateLabel.text = UUCBPeripheralStateToString(peripheral.peripheralState); timeSinceLastUpdateLabel.text = String(format: "%.3f", Date().timeIntervalSince(peripheral.lastAdvertisementTime)) } }
0
// // OSKeyChainSecureDataStoreTests.swift // BitcoinSwift // // Created by Kevin Greene on 1/29/15. // Copyright (c) 2015 DoubleSha. All rights reserved. // import BitcoinSwift import XCTest class OSKeyChainSecureDataStoreTests: XCTestCase { let key = "key" var secureDataStore = OSKeyChainSecureDataStore(service: "com.BitcoinSwift.test") override func setUp() { if secureDataStore.dataForKey(key) != nil { secureDataStore.deleteDataForKey(key) } } override func tearDown() { if secureDataStore.dataForKey(key) != nil { secureDataStore.deleteDataForKey(key) } } func testStoreSecureData() { let bytes: [UInt8] = [0x00, 0x01, 0x02, 0x03] let data = SecureData(bytes: bytes, length: UInt(bytes.count)) XCTAssertTrue(secureDataStore.saveData(data, forKey: key)) XCTAssertEqual(secureDataStore.dataForKey(key)!, data) secureDataStore.deleteDataForKey(key) XCTAssertTrue(secureDataStore.dataForKey(key) == nil) } }
0
// // FocusStateChangeModel.swift // Science_Plus // // Created by Mac on 16/6/4. // Copyright © 2016年 Chem_Plus. All rights reserved. // import Foundation class FocusStateChangeModel{ fileprivate var question_id=0 fileprivate var isFocused=true func changeFocusState(_ question_id:Int,isFocused:Bool){ self.isFocused = isFocused self.question_id = question_id if(self.isFocused){ HttpHandler.httpDelete(HttpAPI.api_focus, parameters: ["question_id" : self.question_id]){ json in print(json) } } else{ HttpHandler.httpPost(HttpAPI.api_focus, parameters: ["question_id" : self.question_id]){ json in print(json) } } } }
0
#!/usr/bin/swift import Foundation enum Result { case success(Any?) case fail(String) } let timerQueue: DispatchQueue = DispatchQueue(label: "timerQueue") var timeoutWorkItem: DispatchWorkItem? var isTerminating: Bool = false func script_processor(launchPath: String, arguments: [String], needOutput: Bool) -> Result { let task: Process = Process() task.launchPath = launchPath task.arguments = arguments let outputPipe: Pipe? = needOutput ? Pipe() : nil let errorPipe: Pipe = Pipe() task.standardOutput = outputPipe task.standardError = errorPipe task.launch() timeoutWorkItem = DispatchWorkItem { isTerminating = true task.terminate() } let timeout: Int = 600 timerQueue.asyncAfter( deadline: .now() + .seconds(timeout), execute: timeoutWorkItem! ) task.waitUntilExit() timeoutWorkItem?.cancel() timeoutWorkItem = nil if isTerminating { isTerminating = false return .fail( """ ❌❌❌ Timeout with Command: [\(arguments.joined(separator: " "))]. In general, there are two cases. 1. Task Process Deadlock 2. The running time of the Task Process is more than Timeout('\(timeout)' seconds) If it's the secondary case, you can change the Timeout. """ ) } var outputString: String? = nil if let outputData: Data = outputPipe?.fileHandleForReading.readDataToEndOfFile(), let outputStr: String = String.init(data: outputData, encoding: .utf8), !outputStr.isEmpty { outputString = outputStr } if task.terminationStatus == 0 { if outputString == nil { outputString = """ ✅✅✅ Command [\(launchPath) \(arguments.joined(separator: " "))] Success. """ } return .success(outputString) } else { let errorData: Data = errorPipe.fileHandleForReading.readDataToEndOfFile() let errorString: String = String.init(data: errorData, encoding: .utf8)! if let outputStr: String = outputString { return .fail( """ ❌❌❌ \(outputStr) \(errorString) """ ) } else { return .fail( """ ❌❌❌ \(errorString) """ ) } } } func bash(command: String, arguments: [String]) -> Result { let commandPathResult: Result = script_processor( launchPath: "/bin/bash", arguments: [ "-l", "-c", "which \(command)" ], needOutput: true ) switch commandPathResult { case .success(let string): guard let path: String = (string as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) else { return .fail( """ ❌❌❌ Not found a path for '\(command)'. """ ) } return script_processor( launchPath: path, arguments: arguments, needOutput: true ) case .fail(_): return commandPathResult } } func xcodebuild_list(projectPath: String) -> Result { let arguments: [String] = [ "-list", "-project", projectPath ] let result: Result = bash( command: "xcodebuild", arguments: arguments ) switch result { case .success(let string): guard let output: String = string as? String else { fatalError() } let lines: [String] = output.components(separatedBy: CharacterSet.newlines) .map { (item: String) -> (String) in return item.trimmingCharacters(in: CharacterSet.whitespaces) } return .success(lines) case .fail(_): return result } } func get_project_all_valid_schemes(lines: [String]) -> [String] { guard var startIndex: Int = lines.index(of: "Schemes:") else { return [] } guard let endIndex: Int = lines[startIndex...].index(of: "") else { return [] } startIndex += 1 guard startIndex < endIndex else { return [] } let arraySlice: ArraySlice<String> = lines[startIndex..<endIndex] .filter { (item: String) -> Bool in let isFiltered = !(item.hasSuffix("Tests") || item.hasSuffix("Demo")) return isFiltered } return Array(arraySlice) } func get_project_all_buildConfigurations(lines: [String]) -> [String] { guard var startIndex: Int = lines.index(of: "Build Configurations:") else { return [] } guard let endIndex: Int = lines[startIndex...].index(of: "") else { return [] } startIndex += 1 guard startIndex < endIndex else { return [] } let arraySlice: ArraySlice<String> = lines[startIndex..<endIndex] return Array(arraySlice) } func xcodebuild_building_schemes(projectPath: String, schemes: [String], buildConfigurations: [String]) -> Result { for scheme in schemes { for buildConfiguration in buildConfigurations { let arguments: [String] = [ "-project", projectPath, "-scheme", scheme, "-configuration", buildConfiguration, "build", "-quiet" ] let result: Result = bash( command: "xcodebuild", arguments: arguments ) switch result { case .success(let string): guard let output: String = string as? String else { fatalError() } print(output) case .fail(_): return result } } } return .success( """ ✅✅✅ The Build of All Schemes are Success. """ ) } func check_if_installed_xcodebuild() -> Result { let result: Result = bash( command: "xcodebuild", arguments: ["-version"] ) return result } func main() { let projectPath: String = "AVOS/AVOS.xcodeproj" switch check_if_installed_xcodebuild() { case .success(_): break case .fail(let error): print(error) return } switch xcodebuild_list(projectPath: projectPath) { case .success(let stringArray): guard let lines: [String] = stringArray as? [String] else { fatalError() } let schemes: [String] = get_project_all_valid_schemes(lines: lines) let buildConfigurations: [String] = get_project_all_buildConfigurations(lines: lines) for _ in 0..<5 { switch xcodebuild_building_schemes( projectPath: projectPath, schemes: schemes, buildConfigurations: buildConfigurations ) { case .success(let string): guard let output: String = string as? String else { fatalError() } print(output) return case .fail(let error): print(error) } } case .fail(let error): print(error) } } main()
0
import Foundation extension MOptionReformaCrossingFoe { class func randomFoe( model:MOptionReformaCrossing, lane:MOptionReformaCrossingLane) -> MOptionReformaCrossingFoeItem? { guard let foeType:MOptionReformaCrossingFoeItem.Type = foeTypeFrom(lane:lane) else { return nil } let foe:MOptionReformaCrossingFoeItem = foeType.init( model:model, lane:lane) return foe } //MARK: private private class func foeTypeFrom(lane:MOptionReformaCrossingLane) -> MOptionReformaCrossingFoeItem.Type? { let countIds:UInt32 = UInt32(lane.possibleFoes.count) if countIds > 0 { let randomId:Int = Int(arc4random_uniform(countIds)) let foeType:MOptionReformaCrossingFoeItem.Type = lane.possibleFoes[randomId] return foeType } return nil } }
0
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <[email protected]> // // SPDX-License-Identifier: MIT // import ApodiniUtils import OpenAPIKit extension Dictionary where Key == String, Value == AnyEncodable { func mapToOpenAPICodable() -> [String: AnyCodable] { mapValues { AnyCodable.fromComplex($0) } } }
0
// // VNOfficeHourPickerTests.swift // VNOfficeHourPickerTests // // Created by Varun Naharia on 20/07/17. // Copyright © 2017 Varun. All rights reserved. // import XCTest @testable import VNOfficeHourPicker class VNOfficeHourPickerTests: 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. } } }
0
// // InventoryControlVC.swift // NMBusinessModules // // Created by Nazif MASMANACI on 4.05.2021. // Copyright © 2021 Turkish Technic. All rights reserved. // import UIKit import TTBaseView class InventoryControlVC: BaseTableViewController { var viewModel: InventoryControlVM! override func viewDidLoad() { super.viewDidLoad() setupView() setupTableView() setupViewModel() } private func setupView() { barNav.setBar(type: .onlyBack, vc: self, title: viewModel.title) } private func setupTableView() { tableView.allowsSelection = false tableView.separatorStyle = .none tableView.tableFooterView = UIView() tableView.register(UINib(nibName: CellInventoryControl.className,bundle: Bundle(for: self.classForCoder)), forCellReuseIdentifier: CellInventoryControl.className) } private func setupViewModel() { viewModel.state.bind { [unowned self] in self.stateHandle($0) }.disposed(by: disposeBag) viewModel.errorState.bind { [unowned self] in self.errorHandle($0) }.disposed(by: disposeBag) viewModel.getData() } // MARK: - TableView override func numberOfSections(in tableView: UITableView) -> Int { return viewModel.numberOfSection() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfRows(in: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = viewModel.item(at: indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: CellInventoryControl.identifier, for: indexPath) as! CellInventoryControl cell.configure(with: item) return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return viewModel.titleForHeader(in: section) } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return viewModel.titleForFooter(in: section) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 40 } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { switch ThemeManager.shared.style { case .dark: headerView.contentView.backgroundColor = .lightGray case .light: headerView.contentView.backgroundColor = .clear case .mobilCabin: headerView.contentView.backgroundColor = #colorLiteral(red: 0.361360997, green: 0.4262621403, blue: 0.722029984, alpha: 1) } headerView.textLabel?.textColor = ThemeManager.shared.textColor headerView.textLabel?.font = ThemeManager.shared.topTitleFont } } }
0
// // ExampleUITests.swift // ExampleUITests // // Created by Krunoslav Zaher on 1/1/16. // Copyright © 2016 kzaher. All rights reserved. // import XCTest import CoreLocation class ExampleUITests: XCTestCase { override func setUp() { super.setUp() continueAfterFailure = false XCUIApplication().launch() } override func tearDown() { super.tearDown() } func testExample() { XCUIApplication().tables.element(boundBy: 0).cells.staticTexts["Randomize Example"].tap() let time: TimeInterval = 120.0 RunLoop.current.run(until: Date().addingTimeInterval(time)) } }
0
// // Copyright 2017 Mobile Jazz SL // // 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 Alamofire public class BaseURLRequestAdapter: RequestInterceptor { // Example of usage of a bearer token public let baseURL : URL private var retriers : [RequestRetrier] = [] public init(_ baseURL: URL, _ retriers : [RequestRetrier]) { self.baseURL = baseURL self.retriers = retriers } public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) { guard let incomingURL = urlRequest.url else { completion(.success(urlRequest)) return } if incomingURL.scheme != nil { completion(.success(urlRequest)) return } var request = urlRequest var components = URLComponents() components.scheme = baseURL.scheme components.host = baseURL.host components.path = "\(baseURL.path)\(incomingURL.path)" if let query = incomingURL.query { components.query = query } request.url = components.url completion(.success(request)) } public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) { should(0, session, retry: request, with: error, completion: completion) } private func should(_ index: Int, _ manager: Session, retry request: Request, with error: Error, completion: @escaping (RetryResult) -> Void) { if index < retriers.count { let retrier = retriers[index] retrier.retry(request, for: manager, dueTo: error) { retryResult in switch retryResult { case .retry, .retryWithDelay(_), .doNotRetry: completion(retryResult) case .doNotRetryWithError(_): self.should(index+1, manager, retry: request, with: error, completion: completion) } } } else { completion(.doNotRetry) } } }
0
// // main.swift // IPATool // // Created by Majd Alfhaily on 22.05.21. // import Foundation IPATool.main()
0
import Foundation import RxSwift import SwiftGRPC public class Param { private let service: Mavsdk_Rpc_Param_ParamServiceService private let scheduler: SchedulerType public convenience init(address: String = "localhost", port: Int32 = 50051, scheduler: SchedulerType = ConcurrentDispatchQueueScheduler(qos: .background)) { let service = Mavsdk_Rpc_Param_ParamServiceServiceClient(address: "\(address):\(port)", secure: false) self.init(service: service, scheduler: scheduler) } init(service: Mavsdk_Rpc_Param_ParamServiceService, scheduler: SchedulerType) { self.service = service self.scheduler = scheduler } public struct RuntimeParamError: Error { public let description: String init(_ description: String) { self.description = description } } public struct ParamError: Error { public let code: Param.ParamResult.Result public let description: String } public struct ParamResult: Equatable { public let result: Result public let resultStr: String public enum Result: Equatable { case unknown case success case timeout case connectionError case wrongType case paramNameTooLong case UNRECOGNIZED(Int) internal var rpcResult: Mavsdk_Rpc_Param_ParamResult.Result { switch self { case .unknown: return .unknown case .success: return .success case .timeout: return .timeout case .connectionError: return .connectionError case .wrongType: return .wrongType case .paramNameTooLong: return .paramNameTooLong case .UNRECOGNIZED(let i): return .UNRECOGNIZED(i) } } internal static func translateFromRpc(_ rpcResult: Mavsdk_Rpc_Param_ParamResult.Result) -> Result { switch rpcResult { case .unknown: return .unknown case .success: return .success case .timeout: return .timeout case .connectionError: return .connectionError case .wrongType: return .wrongType case .paramNameTooLong: return .paramNameTooLong case .UNRECOGNIZED(let i): return .UNRECOGNIZED(i) } } } public init(result: Result, resultStr: String) { self.result = result self.resultStr = resultStr } internal var rpcParamResult: Mavsdk_Rpc_Param_ParamResult { var rpcParamResult = Mavsdk_Rpc_Param_ParamResult() rpcParamResult.result = result.rpcResult rpcParamResult.resultStr = resultStr return rpcParamResult } internal static func translateFromRpc(_ rpcParamResult: Mavsdk_Rpc_Param_ParamResult) -> ParamResult { return ParamResult(result: Result.translateFromRpc(rpcParamResult.result), resultStr: rpcParamResult.resultStr) } public static func == (lhs: ParamResult, rhs: ParamResult) -> Bool { return lhs.result == rhs.result && lhs.resultStr == rhs.resultStr } } public func getParamInt(name: String) -> Single<Int32> { return Single<Int32>.create { single in var request = Mavsdk_Rpc_Param_GetParamIntRequest() request.name = name do { let response = try self.service.getParamInt(request) if (response.paramResult.result != Mavsdk_Rpc_Param_ParamResult.Result.success) { single(.error(ParamError(code: ParamResult.Result.translateFromRpc(response.paramResult.result), description: response.paramResult.resultStr))) return Disposables.create() } let value = response.value single(.success(value)) } catch { single(.error(error)) } return Disposables.create() } } public func setParamInt(name: String, value: Int32) -> Completable { return Completable.create { completable in var request = Mavsdk_Rpc_Param_SetParamIntRequest() request.name = name request.value = value do { let response = try self.service.setParamInt(request) if (response.paramResult.result == Mavsdk_Rpc_Param_ParamResult.Result.success) { completable(.completed) } else { completable(.error(ParamError(code: ParamResult.Result.translateFromRpc(response.paramResult.result), description: response.paramResult.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } public func getParamFloat(name: String) -> Single<Float> { return Single<Float>.create { single in var request = Mavsdk_Rpc_Param_GetParamFloatRequest() request.name = name do { let response = try self.service.getParamFloat(request) if (response.paramResult.result != Mavsdk_Rpc_Param_ParamResult.Result.success) { single(.error(ParamError(code: ParamResult.Result.translateFromRpc(response.paramResult.result), description: response.paramResult.resultStr))) return Disposables.create() } let value = response.value single(.success(value)) } catch { single(.error(error)) } return Disposables.create() } } public func setParamFloat(name: String, value: Float) -> Completable { return Completable.create { completable in var request = Mavsdk_Rpc_Param_SetParamFloatRequest() request.name = name request.value = value do { let response = try self.service.setParamFloat(request) if (response.paramResult.result == Mavsdk_Rpc_Param_ParamResult.Result.success) { completable(.completed) } else { completable(.error(ParamError(code: ParamResult.Result.translateFromRpc(response.paramResult.result), description: response.paramResult.resultStr))) } } catch { completable(.error(error)) } return Disposables.create() } } }
0
// // Character.swift // AsYouTypeFormatter // // Created by Philip on 16/03/19. // Copyright © 2018 Next Generation. All rights reserved. // import Foundation extension Character { var isUTF16: Bool { return unicodeScalars.count == 1 && !unicodeScalars.contains(where: { unicodeScalar -> Bool in unicodeScalar.value > UTF16Char.max }) } }
0
// // DirectoryType.swift // XcodeCleaner // // Created by Kirill Pustovalov on 05.07.2020. // Copyright © 2020 Kirill Pustovalov. All rights reserved. // import Foundation public enum DirectoryType { case derivedData case deviceSupport case archives case iOSDeviceLogs case documentationCache }
0
// // ShoppingList.swift // ArrayChallenge // // Created by Jim Campagno on 9/17/16. // Copyright © 2016 Flatiron School. All rights reserved. // class ShoppingList { func createShoppingList(withItems items: [String], amountOfEachItem amounts: [String]) -> [String] { var completeList: [String] = [] for (index, item) in items.enumerated() { completeList.append("\(index + 1). \(item)(\(amounts[index]))") } print (items) print(amounts) return completeList } }
0
// // The MIT License // // Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.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. // // // SecureContainerCommandTests.swift // HMKitTests // // Created by Mikk Rätsep on 14/06/2018. // @testable import HMKit import HMUtilities import XCTest /* 0x36 Secure command container - Needs Authentication before using. With this request you can send signed command to device and get signed response back Req: Data[2]: Requires HMAC Ack Data[3]: Command size Data[4]: Command size Data[5 to A]: Command Data[A to B]: HMAC ( command id + command size + container command ) ( 32 bytes ) Ack: Data[3]: Response size Data[4]: Response size Data[5 to A]: Response ( Contains full Ack response ) Data[A to B]: HMAC ( Ack + response size + response ) ( 32 bytes ) Error: 0x01 - Internal error 0x04 - Invalid data 0x07 - Unauthorised 0x08 - Invalid HMAC */ class SecureContainerCommandTests: XCTestCase { static var allTests = [("testResponse", testResponse), ("testRequest", testRequest)] // MARK: XCTestCase func testResponse() throws { let bytes = "013600007D3BFC6BE25A497C313209EB92E36E64C92F15267D712D33CBAA7B109463C21F".hexBytes let response = try HMSecureContainerCommandResponse(bytes: bytes) XCTAssertEqual(response.response, []) XCTAssertEqual(response.hmac, "7D3BFC6BE25A497C313209EB92E36E64C92F15267D712D33CBAA7B109463C21F".hexBytes) // Check the HMAC XCTAssertTrue(try response.isSignatureValid(forKey: "393CAB697CB6CE241AB485E93AE62027DE87BCF9B5DC65B55F32C02DC119CE8C".hexBytes), "Invalid HMAC") } func testRequest() throws { let bytes = "3601003A0020010100030001010100030101010100030201010100030300010200020001020002010102000202010200020301A2000812060E0D080B00B4154BA1380A9D7004CFB514890450887D94C7CAE46F4943BD3FBA48D68B263AAC".hexBytes let request = try HMSecureContainerCommandRequest(bytes: bytes) XCTAssertEqual(request.command, "0020010100030001010100030101010100030201010100030300010200020001020002010102000202010200020301A2000812060E0D080B00B4".hexBytes) XCTAssertEqual(request.header, "36".hexBytes) XCTAssertEqual(request.signature, "154BA1380A9D7004CFB514890450887D94C7CAE46F4943BD3FBA48D68B263AAC".hexBytes) XCTAssertEqual(request.requiresHMAC, true) // Check the HMAC XCTAssertTrue(try request.isSignatureValid(forKey:"393CAB697CB6CE241AB485E93AE62027DE87BCF9B5DC65B55F32C02DC119CE8C".hexBytes), "Invalid HMAC") } }
0
// // Links.swift // MyMonero // // Created by Paul Shapiro on 6/3/17. // Copyright (c) 2014-2019, MyMonero.com // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // import UIKit extension UICommonComponents { class LinkButtonView: UIButton { // // Constants static var h: CGFloat { // a computed property, so that we can override it return 24 } // static let marginAboveLabelForUnderneathField_textInputView__visualSqueezing_y: CGFloat = UIFont.shouldStepDownLargerFontSizes ? 14 : 24 static let visuallySqueezed_marginAboveLabelForUnderneathField_textInputView = UICommonComponents.Form.FieldLabel.marginAboveLabelForUnderneathField_textInputView - marginAboveLabelForUnderneathField_textInputView__visualSqueezing_y // enum Mode { case mono_default case mono_destructive case sansSerif_default } enum Size { case larger case normal case hidden var isHidden: Bool { return (self == .hidden) } } // // Init var mode: Mode! var size: Size! init(mode: Mode, size: Size, title: String) { let frame = CGRect( x: 0, y: 0, width: 0, height: LinkButtonView.h // increased height for touchability ) super.init(frame: frame) self.mode = mode self.size = size self.setTitleText(to: title, size: self.size) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // func setTitleText(to title: String) { // use this instead of setTitle let color_normal = self.mode == .mono_destructive ? UIColor.standaloneValidationTextOrDestructiveLinkContentColor : UIColor.utilityOrConstructiveLinkColor let font = self.size == .larger ? UIFont.middlingBoldMonospace : UIFont.smallRegularMonospace let normal_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: color_normal, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: 0 ] ) let selected_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: color_normal, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ] ) let disabled_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.disabledLinkColor, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: 0 ] ) self.setAttributedTitle(normal_attributedTitle, for: .normal) self.setAttributedTitle(selected_attributedTitle, for: .highlighted) self.setAttributedTitle(selected_attributedTitle, for: .selected) self.setAttributedTitle(disabled_attributedTitle, for: .disabled) // // now that we have title and font… var frame = self.frame frame.size.height = LinkButtonView.h self.frame = frame } func setTitleText(to title: String, size: Size) { // use this instead of setTitle let color_normal = self.mode == .mono_destructive ? UIColor.standaloneValidationTextOrDestructiveLinkContentColor : UIColor.utilityOrConstructiveLinkColor let font = self.size == .larger ? UIFont.middlingBoldMonospace : UIFont.smallRegularMonospace let normal_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: color_normal, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: 0 ] ) let selected_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: color_normal, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue ] ) let disabled_attributedTitle = NSAttributedString( string: title, attributes: [ NSAttributedString.Key.foregroundColor: UIColor.disabledLinkColor, NSAttributedString.Key.font: font, NSAttributedString.Key.underlineStyle: 0 ] ) self.setAttributedTitle(normal_attributedTitle, for: .normal) self.setAttributedTitle(selected_attributedTitle, for: .highlighted) self.setAttributedTitle(selected_attributedTitle, for: .selected) self.setAttributedTitle(disabled_attributedTitle, for: .disabled) // // now that we have title and font… if (size.isHidden == true) { debugPrint("hidden"); self.frame = CGRect( x: -5000, y: 0, width: 0, height: 0 // increased height for touchability ) } else { self.sizeToFit() var frame = self.frame frame.size.height = LinkButtonView.h self.frame = frame } } } }
0
// // SceneDelegate.swift // CubiCaptureDemo // // Created by Rauli Puuperä on 8.12.2020. // import UIKit import CubiCapture class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } func windowScene(_ windowScene: UIWindowScene, didUpdate previousCoordinateSpace: UICoordinateSpace, interfaceOrientation previousInterfaceOrientation: UIInterfaceOrientation, traitCollection previousTraitCollection: UITraitCollection) { if #available(iOS 16, *), windowScene.interfaceOrientation == ScanHostViewController.requiredOrientation { ScanHostViewController.completion?() ScanHostViewController.completion = nil } } }
0
// // HCIError.swift // BlueZ // // Created by Alsey Coleman Miller on 1/3/16. // Copyright © 2016 PureSwift. All rights reserved. // import SwiftFoundation public extension Bluetooth { /// HCI Errors public enum HCIError: Byte, ErrorType { case UnknownCommand = 0x01 case NoConnection = 0x02 case HardwareFailure = 0x03 // TODO: Add all errors case HostBusyPairing = 0x38 } }
0
// // AppDelegate.swift // Accent // // Created by Jack Cook on 4/9/16. // Copyright © 2016 Tiny Pixels. All rights reserved. // import Crashlytics import DigitsKit import Fabric import UIKit let AccentApplicationWillEnterForeground = "AccentApplicationWillEnterForeground" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { Fabric.with([Crashlytics.self, Digits.self]) UserDefaults(suiteName: "group.io.tinypixels.Accent")?.set(UserDefaults(suiteName: "group.io.tinypixels.Accent")?.stringArray(forKey: "AccentArticlesToRetrieve") ?? [String](), forKey: "AccentArticlesToRetrieve") if Language.savedLanguage() != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let avc = storyboard.instantiateViewController(withIdentifier: "ArticlesViewController") as! ArticlesViewController let navController = UINavigationController() window?.rootViewController = navController navController.pushViewController(avc, animated: false) } return true } func applicationWillEnterForeground(_ application: UIApplication) { NotificationCenter.default.post(name: Notification.Name(rawValue: AccentApplicationWillEnterForeground), object: nil) } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { guard let host = url.host else { return true } switch host { case "auth": if url.pathComponents.count > 0 { switch url.pathComponents[1] { case "quizlet": Quizlet.sharedInstance.handleAuthorizationResponse(url) default: break } } default: break } return true } }
0
//// //// SendMessage.swift //// Chat //// //// Created by Mahyar Zhiani on 6/4/1397 AP. //// Copyright © 1397 Mahyar Zhiani. All rights reserved. //// // //import Foundation //import SwiftyJSON //import Async // //class SendMessageClass { // // var params: JSON // var serverName: String // var priority: Int // var ttl: Int // // var async: Async // // var token: String // var tokenIssuer: String // // var hasResult: Bool // var hasSentDeliverSeen: Bool // // init(params: JSON, serverName: String, priority: Int, ttl: Int, async: Async, token: String, tokenIssuer: String, hasResult: Bool, hasSentDeliverSeen: Bool) { // self.params = params // self.serverName = serverName // self.priority = priority // self.ttl = ttl // // self.async = async // // self.token = token // self.tokenIssuer = tokenIssuer // // self.hasResult = hasResult // self.hasSentDeliverSeen = hasSentDeliverSeen // //// handleParamsAndSendMessage() // } // //// var isResult: Bool = false //// var isSent: Bool = false //// var isDeliver: Bool = false //// var isSeen: Bool = false // //} // // //class SendMessageClass2 { // // var params: JSON // // var peerName: String // var priority: Int // var ttl: Int // // var async: Async // // var token: String // var tokenIssuer: String // // init(params: JSON, peerName: String, priority: Int, ttl: Int, async: Async, token: String, tokenIssuer: String) { // self.params = params // self.peerName = peerName // self.priority = priority // self.ttl = ttl // // self.async = async // // self.token = token // self.tokenIssuer = tokenIssuer // // } // // // var isResult: Bool = false // // var isSent: Bool = false // // var isDeliver: Bool = false // // var isSeen: Bool = false // // // func createContent2() { // // } // // // //} // // // // // //extension SendMessageClass { // // func handleParamsAndSendMessage() { // /* // * Message to send through async SDK // * // * + MessageWrapperVO {object} // * - type {int} Type of ASYNC message based on content // * + content {string} // * -peerName {string} Name of receiver Peer // * -receivers[] {long} Array of receiver peer ids (if you use this, peerName will be ignored) // * -priority {int} Priority of message 1-10, lower has more priority // * -messageId {long} Id of message on your side, not required // * -ttl {long} Time to live for message in milliseconds // * -content {string} Chat Message goes here after stringifying // * - trackId {long} Tracker id of message that you receive from DIRANA previously (if you are replying a sync message) // */ // // var type: Int // if let theType = params["pushMsgType"].int { // type = theType // } else { // type = 3 // } // // let contentStr = messageVOAsStringOfJSON // // let msgSend: JSON = ["peerName": serverName, // "priority": priority, // "content": contentStr, // "ttl": ttl] // // let msgToSendStr: String = "\(msgSend)" // async.pushSendData(type: type, content: msgToSendStr) // // } // // func messageVOAsJSON() -> JSON { // /* // * + ChatMessage {object} // * - token {string} // * - tokenIssuer {string} // * - type {int} // * - subjectId {long} // * - uniqueId {string} // * - content {string} // * - time {long} // * - medadata {string} // * - systemMedadata {string} // * - repliedTo {long} // */ // var messageVO: JSON = ["token": token, "tokenIssuer": tokenIssuer] // // let type = params["chatMessageVOTypes"].intValue // messageVO.appendIfDictionary(key: "type", json: JSON(type)) // // var uniqueId: String // if let theUniqueId = params["uniqueId"].string { // uniqueId = theUniqueId // } else if let uId = params["uniqueId"].array { // let uuuIddd = "\(uId)" // uniqueId = uuuIddd // } else { // uniqueId = generateUUID() // } // messageVO.appendIfDictionary(key: "uniqueId", json: JSON(uniqueId)) // // // if let theSubjectId = params["subjectId"].int { // messageVO.appendIfDictionary(key: "threadId", json: JSON(theSubjectId)) // messageVO.appendIfDictionary(key: "subjectId", json: JSON(theSubjectId)) // } // // if let theContent = params["content"].string { // messageVO.appendIfDictionary(key: "content", json: JSON(theContent)) // } // // if let theTime = params["time"].string { // messageVO.appendIfDictionary(key: "time", json: JSON(theTime)) // } // // if let theMetaData = params["metadata"].string { // messageVO.appendIfDictionary(key: "metadata", json: JSON(theMetaData)) // } // // if let theSystemMetaData = params["systemMetadata"].string { // messageVO.appendIfDictionary(key: "systemMetadata", json: JSON(theSystemMetaData)) // } // // if let theRepliedTo = params["repliedTo"].int { // messageVO.appendIfDictionary(key: "repliedTo", json: JSON(theRepliedTo)) // } // // return messageVO // } // // func messageVOAsStringOfJSON() -> String { // let contentJSON = messageVOAsJSON() // let contentStr = "\(contentJSON)" // return contentStr // } // // func generateUUID() -> String { // // return "" // } // // // //} // // // // // // ////// public functions ////extension SendMessageClass { //// //// public func isMessageSent() -> Bool { //// return isSent //// } //// //// public func isMessageDeliver() -> Bool { //// return isDeliver //// } //// //// public func isMessageSeen() -> Bool { //// return isSeen //// } ////} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
0
// RUN: %empty-directory(%t) // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %clang-importer-sdk-path/swift-modules/Foundation.swift // FIXME: END -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -typecheck %s -verify // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) %s -dump-ast -verify 2>&1 | %FileCheck %s // REQUIRES: objc_interop import Foundation func testDowncastObjectToArray(obj: AnyObject, objImplicit: AnyObject!) { var nsstrArr1 = (obj as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}}{{39-40=}} var strArr1 = (obj as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}}{{35-36=}} var nsstrArr2 = (objImplicit as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}}{{47-48=}} var strArr2 = (objImplicit as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}}{{43-44=}} } func testArrayDowncast(arr: [AnyObject], arrImplicit: [AnyObject]!) { var nsstrArr1 = (arr as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}} {{39-40=}} var strArr1 = (arr as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}} {{35-36=}} var nsstrArr2 = (arrImplicit as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}} {{47-48=}} var strArr2 = (arrImplicit as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}} {{43-44=}} } func testDowncastNSArrayToArray(nsarray: NSArray) { _ = nsarray as! [NSString] _ = nsarray as! [String] } // CHECK-LABEL: testDowncastOptionalObject func testDowncastOptionalObject(obj: AnyObject?!) -> [String]? { // CHECK: (optional_evaluation_expr implicit type='[String]?' // CHECK-NEXT: (inject_into_optional implicit type='[String]?' // CHECK: (forced_checked_cast_expr type='[String]'{{.*value_cast}} // CHECK: (bind_optional_expr implicit type='AnyObject' // CHECK-NEXT: (force_value_expr implicit type='AnyObject?' // CHECK-NEXT: (declref_expr type='AnyObject?!' return obj as! [String]? } // CHECK-LABEL: testDowncastOptionalObjectConditional func testDowncastOptionalObjectConditional(obj: AnyObject?!) -> [String]?? { // CHECK: (optional_evaluation_expr implicit type='[String]??' // CHECK-NEXT: (inject_into_optional implicit type='[String]??' // CHECK-NEXT: (optional_evaluation_expr implicit type='[String]?' // CHECK-NEXT: (inject_into_optional implicit type='[String]?' // CHECK-NEXT: (bind_optional_expr implicit type='[String]' // CHECK-NEXT: (conditional_checked_cast_expr type='[String]?' {{.*value_cast}} writtenType='[String]?' // CHECK-NEXT: (bind_optional_expr implicit type='AnyObject' // CHECK-NEXT: (bind_optional_expr implicit type='AnyObject?' // CHECK-NEXT: (declref_expr type='AnyObject?!' return obj as? [String]? } // Do not crash examining the casted-to (or tested) type if it is // invalid (null or error_type). class rdar28583595 : NSObject { public func test(i: Int) { if i is Array {} // expected-error {{generic parameter 'Element' could not be inferred}} // expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} } }
0
// // Dictionary+AdditionsTests.swift // // // Created by Harry Brown on 21/12/2021. // import XCTest @testable import Checkout class DictionaryAdditionsTests: XCTestCase { func test_mapKeys() { let subject = [1: "test", 2: "value", 3: "world"] let expected = [5: "test", 10: "value", 15: "world"] XCTAssertEqual(subject.mapKeys { $0 * 5 }, expected) } func test_unpackEnumKeys() { let subject: [TestKey: String] = [.abc: "test", .def: "value", .ghi: "world"] let expected = [1: "test", 13: "value", 72: "world"] XCTAssertEqual(subject.unpackEnumKeys(), expected) } private enum TestKey: Int { case abc = 1 case def = 13 case ghi = 72 } }
0
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import _Differentiation /// A max pooling layer for temporal data. @frozen public struct MaxPool1D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: Int /// The stride of the sliding window for temporal dimension. @noDerivative public let stride: Int /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates a max pooling layer. /// /// - Parameters: /// - poolSize: The size of the sliding reduction window for pooling. /// - stride: The stride of the sliding window for temporal dimension. /// - padding: The padding algorithm for pooling. public init(poolSize: Int, stride: Int, padding: Padding) { precondition(poolSize > 0, "The pooling window size must be greater than 0.") precondition(stride > 0, "The stride must be greater than 0.") self.poolSize = poolSize self.stride = stride self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { maxPool2D( input.expandingShape(at: 1), filterSize: (1, 1, poolSize, 1), strides: (1, 1, stride, 1), padding: padding ).squeezingShape(at: 1) } } /// A max pooling layer for spatial data. @frozen public struct MaxPool2D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: (Int, Int, Int, Int) /// The strides of the sliding window for each dimension of a 4-D input. /// Strides in non-spatial dimensions must be `1`. @noDerivative public let strides: (Int, Int, Int, Int) /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates a max pooling layer. public init(poolSize: (Int, Int, Int, Int), strides: (Int, Int, Int, Int), padding: Padding) { precondition( poolSize.0 > 0 && poolSize.1 > 0 && poolSize.2 > 0 && poolSize.3 > 0, "Pooling window sizes must be greater than 0.") precondition( strides.0 > 0 && strides.1 > 0 && strides.2 > 0 && strides.3 > 0, "Strides must be greater than 0.") self.poolSize = poolSize self.strides = strides self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { maxPool2D(input, filterSize: poolSize, strides: strides, padding: padding) } } extension MaxPool2D { /// Creates a max pooling layer. /// /// - Parameters: /// - poolSize: Vertical and horizontal factors by which to downscale. /// - strides: The strides. /// - padding: The padding. public init(poolSize: (Int, Int), strides: (Int, Int), padding: Padding = .valid) { self.init( poolSize: (1, poolSize.0, poolSize.1, 1), strides: (1, strides.0, strides.1, 1), padding: padding) } } /// A max pooling layer for spatial or spatio-temporal data. @frozen public struct MaxPool3D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: (Int, Int, Int, Int, Int) /// The strides of the sliding window for each dimension of a 5-D input. /// Strides in non-spatial dimensions must be `1`. @noDerivative public let strides: (Int, Int, Int, Int, Int) /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates a max pooling layer. public init( poolSize: (Int, Int, Int, Int, Int), strides: (Int, Int, Int, Int, Int), padding: Padding ) { precondition( poolSize.0 > 0 && poolSize.1 > 0 && poolSize.2 > 0 && poolSize.3 > 0 && poolSize.4 > 0, "Pooling window sizes must be greater than 0." ) precondition( strides.0 > 0 && strides.1 > 0 && strides.2 > 0 && strides.3 > 0 && strides.4 > 0, "Strides must be greater than 0." ) self.poolSize = poolSize self.strides = strides self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { maxPool3D(input, filterSize: poolSize, strides: strides, padding: padding) } } extension MaxPool3D { /// Creates a max pooling layer. /// /// - Parameters: /// - poolSize: Vertical and horizontal factors by which to downscale. /// - strides: The strides. /// - padding: The padding. public init(poolSize: (Int, Int, Int), strides: (Int, Int, Int), padding: Padding = .valid) { self.init( poolSize: (1, poolSize.0, poolSize.1, poolSize.2, 1), strides: (1, strides.0, strides.1, strides.2, 1), padding: padding) } } extension MaxPool3D { /// Creates a max pooling layer with the specified pooling window size and stride. All pooling /// sizes and strides are the same. public init(poolSize: Int, stride: Int, padding: Padding = .valid) { self.init( poolSize: (poolSize, poolSize, poolSize), strides: (stride, stride, stride), padding: padding) } } /// An average pooling layer for temporal data. @frozen public struct AvgPool1D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: Int /// The stride of the sliding window for temporal dimension. @noDerivative public let stride: Int /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates an average pooling layer. /// /// - Parameters: /// - poolSize: The size of the sliding reduction window for pooling. /// - stride: The stride of the sliding window for temporal dimension. /// - padding: The padding algorithm for pooling. public init(poolSize: Int, stride: Int, padding: Padding) { precondition(poolSize > 0, "The pooling window size must be greater than 0.") precondition(stride > 0, "The stride must be greater than 0.") self.poolSize = poolSize self.stride = stride self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { avgPool2D( input.expandingShape(at: 1), filterSize: (1, 1, poolSize, 1), strides: (1, 1, stride, 1), padding: padding ).squeezingShape(at: 1) } } /// An average pooling layer for spatial data. @frozen public struct AvgPool2D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: (Int, Int, Int, Int) /// The strides of the sliding window for each dimension of a 4-D input. /// Strides in non-spatial dimensions must be `1`. @noDerivative public let strides: (Int, Int, Int, Int) /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates an average pooling layer. public init(poolSize: (Int, Int, Int, Int), strides: (Int, Int, Int, Int), padding: Padding) { precondition( poolSize.0 > 0 && poolSize.1 > 0 && poolSize.2 > 0 && poolSize.3 > 0, "Pooling window sizes must be greater than 0.") precondition( strides.0 > 0 && strides.1 > 0 && strides.2 > 0 && strides.3 > 0, "Strides must be greater than 0.") self.poolSize = poolSize self.strides = strides self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { avgPool2D(input, filterSize: poolSize, strides: strides, padding: padding) } } extension AvgPool2D { /// Creates an average pooling layer. /// /// - Parameters: /// - poolSize: Vertical and horizontal factors by which to downscale. /// - strides: The strides. /// - padding: The padding. public init(poolSize: (Int, Int), strides: (Int, Int), padding: Padding = .valid) { self.init( poolSize: (1, poolSize.0, poolSize.1, 1), strides: (1, strides.0, strides.1, 1), padding: padding) } } /// An average pooling layer for spatial or spatio-temporal data. @frozen public struct AvgPool3D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// The size of the sliding reduction window for pooling. @noDerivative public let poolSize: (Int, Int, Int, Int, Int) /// The strides of the sliding window for each dimension of a 5-D input. /// Strides in non-spatial dimensions must be `1`. @noDerivative public let strides: (Int, Int, Int, Int, Int) /// The padding algorithm for pooling. @noDerivative public let padding: Padding /// Creates an average pooling layer. public init( poolSize: (Int, Int, Int, Int, Int), strides: (Int, Int, Int, Int, Int), padding: Padding ) { precondition( poolSize.0 > 0 && poolSize.1 > 0 && poolSize.2 > 0 && poolSize.3 > 0 && poolSize.4 > 0, "Pooling window sizes must be greater than 0." ) precondition( strides.0 > 0 && strides.1 > 0 && strides.2 > 0 && strides.3 > 0 && strides.4 > 0, "Strides must be greater than 0." ) self.poolSize = poolSize self.strides = strides self.padding = padding } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { avgPool3D(input, filterSize: poolSize, strides: strides, padding: padding) } } extension AvgPool3D { /// Creates an average pooling layer. /// /// - Parameters: /// - poolSize: Vertical and horizontal factors by which to downscale. /// - strides: The strides. /// - padding: The padding. public init(poolSize: (Int, Int, Int), strides: (Int, Int, Int), padding: Padding = .valid) { self.init( poolSize: (1, poolSize.0, poolSize.1, poolSize.2, 1), strides: (1, strides.0, strides.1, strides.2, 1), padding: padding) } } extension AvgPool3D { /// Creates an average pooling layer with the specified pooling window size and stride. All /// pooling sizes and strides are the same. public init(poolSize: Int, strides: Int, padding: Padding = .valid) { self.init( poolSize: (poolSize, poolSize, poolSize), strides: (strides, strides, strides), padding: padding) } } /// A global average pooling layer for temporal data. @frozen public struct GlobalAvgPool1D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global average pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 3, "The rank of the input must be 3.") return input.mean(squeezingAxes: 1) } } /// A global average pooling layer for spatial data. @frozen public struct GlobalAvgPool2D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global average pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 4, "The rank of the input must be 4.") return input.mean(squeezingAxes: [1, 2]) } } /// A global average pooling layer for spatial and spatio-temporal data. @frozen public struct GlobalAvgPool3D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global average pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 5, "The rank of the input must be 5.") return input.mean(squeezingAxes: [1, 2, 3]) } } /// A global max pooling layer for temporal data. @frozen public struct GlobalMaxPool1D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global max pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameters: /// - input: The input to the layer. /// - context: The contextual information for the layer application, e.g. the current learning /// phase. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 3, "The rank of the input must be 3.") return input.max(squeezingAxes: 1) } } /// A global max pooling layer for spatial data. @frozen public struct GlobalMaxPool2D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global max pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 4, "The rank of the input must be 4.") return input.max(squeezingAxes: [1, 2]) } } /// A global max pooling layer for spatial and spatio-temporal data. @frozen public struct GlobalMaxPool3D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Creates a global max pooling layer. public init() {} /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { precondition(input.rank == 5, "The rank of the input must be 5.") return input.max(squeezingAxes: [1, 2, 3]) } } /// A fractional max pooling layer for spatial data. /// Note: `FractionalMaxPool` does not have an XLA implementation, and thus may have performance implications. @frozen public struct FractionalMaxPool2D<Scalar: TensorFlowFloatingPoint>: ParameterlessLayer { public typealias TangentVector = EmptyTangentVector /// Pooling ratios for each dimension of input of shape (batch, height, width, channels). /// Currently pooling in only height and width is supported. @noDerivative public let poolingRatio: (Double, Double, Double, Double) /// Determines whether pooling sequence is generated by pseudorandom fashion. @noDerivative public let pseudoRandom: Bool /// Determines whether values at the boundary of adjacent pooling cells are used by both cells @noDerivative public let overlapping: Bool /// Determines whether a fixed pooling region will be /// used when iterating over a FractionalMaxPool2D node in the computation graph. @noDerivative public let deterministic: Bool /// Seed for the random number generator @noDerivative public let seed: Int64 /// A second seed to avoid seed collision @noDerivative public let seed2: Int64 /// Initializes a `FractionalMaxPool` layer with configurable `poolingRatio`. public init( poolingRatio: (Double, Double, Double, Double), pseudoRandom: Bool = false, overlapping: Bool = false, deterministic: Bool = false, seed: Int64 = 0, seed2: Int64 = 0 ) { precondition( poolingRatio.0 == 1.0 && poolingRatio.3 == 1.0, "Pooling on batch and channels dimensions not supported.") precondition( poolingRatio.1 >= 1.0 && poolingRatio.2 >= 1.0, "Pooling ratio for height and width dimensions must be at least 1.0") self.poolingRatio = poolingRatio self.pseudoRandom = pseudoRandom self.overlapping = overlapping self.deterministic = deterministic self.seed = seed self.seed2 = seed2 } /// Returns the output obtained from applying the layer to the given input. /// /// - Parameter input: The input to the layer. /// - Returns: The output. @differentiable public func forward(_ input: Tensor<Scalar>) -> Tensor<Scalar> { fractionalMaxPool2D( input, poolingRatio: poolingRatio, pseudoRandom: pseudoRandom, overlapping: overlapping, deterministic: deterministic, seed: seed, seed2: seed2) } } extension FractionalMaxPool2D { /// Creates a fractional max pooling layer. /// /// - Parameters: /// - poolingRatio: Pooling ratio for height and width dimensions of input. /// - pseudoRandom: Determines wheter the pooling sequence is generated /// in a pseudorandom fashion. /// - overlapping: Determines whether values at the boundary of adjacent /// pooling cells are used by both cells. /// - deterministic: Determines whether a fixed pooling region will be /// used when iterating over a FractionalMaxPool2D node in the computation graph. /// - seed: A seed for random number generator. /// - seed2: A second seed to avoid seed collision. public init( poolingRatio: (Double, Double), pseudoRandom: Bool = false, overlapping: Bool = false, deterministic: Bool = false, seed: Int64 = 0, seed2: Int64 = 0 ) { self.init( poolingRatio: (1.0, poolingRatio.0, poolingRatio.1, 1.0), pseudoRandom: pseudoRandom, overlapping: overlapping, deterministic: deterministic, seed: seed, seed2: seed2) } }
0
import XCTest @testable import InstaZoomTests XCTMain([ testCase(InstaZoomTests.allTests), ])
0
// // LoggedOutInteractor.swift // PFXRibs // // Created by succorer on 2020/02/10. // Copyright © 2020 PFXStudio. All rights reserved. // import RIBs import RxSwift // 인터랙터에서 라우터로 통신을 하기 위한 프로토콜, 라우터에서 기능 구현을 해야 함 protocol LoggedOutRouting: ViewableRouting { // TODO: Declare methods the interactor can invoke to manage sub-tree via the router. func messageToRouter(message: String) } extension LoggedOutRouting { // 공부 중.. func messageToRouter(message: String = "") { } func messageToClass(message: String) where Self: Hashable { } } // Presentable 프로토콜을 통해 LoggedOutViewController를 연결 해 준다. // LoggedOutViewController에서 이벤트가 발생하면 Presentable 프로토콜을 통해 Interactor에게 전달한다. // 뷰컨에서 인터랙터로 전달이 필요할 때 Presentable 채택해서 정의 한다. protocol LoggedOutPresentable: Presentable { var listener: LoggedOutPresentableListener? { get set } // TODO: Declare methods the interactor can invoke the presenter to present data. } // Interactor에 접근 할 수 있는 함수 프로토콜. 즉 Interactor에 접근 할 수 있는 함수 목록 기재. // RootInteractor에서 사용함. 프로토콜을 통해서 다른 RIB interactor 호출은 괜찮은 것인가?? protocol LoggedOutListener: class { func didLogin(withPlayer1Name player1Name: String, player2Name: String) } // LoggedOutInteractor 클래스. LoggedOutPresentable, LoggedOutInteractable, LoggedOutPresentableListener 프로토콜을 받는다. final class LoggedOutInteractor: PresentableInteractor<LoggedOutPresentable>, LoggedOutInteractable, LoggedOutPresentableListener { // LoggedOutRouting 참조 변수 weak var router: LoggedOutRouting? // LoggedOutListener 참조 변수 // 인터랙터 끼리 통신이 필요 한 경우에는 리스너 프로토콜을 이용 해 전달한다. weak var listener: LoggedOutListener? // TODO: Add additional dependencies to constructor. Do not perform any logic // 생성 시 LoggedOutViewController를 받는다. override init(presenter: LoggedOutPresentable) { super.init(presenter: presenter) // LoggedOutViewController에서 LoggedOutInteractor 호출이 가능 하도록 listener에 LoggedOutInteractor 값을 참조 시킨다. presenter.listener = self } // RIB 생명주기 함수 override func didBecomeActive() { super.didBecomeActive() // TODO: Implement business logic here. } // RIB 생명주기 함수 override func willResignActive() { super.willResignActive() // TODO: Pause any business logic. } // MARK: - LoggedOutPresentableListener // LoggedOutViewController 호출되는 함수 정의. LoggedOutPresentableListener 프로토콜에 정의 되어 있음. func login(withPlayer1Name player1Name: String?, player2Name: String?) { let player1NameWithDefault = playerName(player1Name, withDefaultName: "Player 1") let player2NameWithDefault = playerName(player2Name, withDefaultName: "Player 2") // RootInteractor에 didLogin을 호출한다. listener?.didLogin(withPlayer1Name: player1NameWithDefault, player2Name: player2NameWithDefault) } // playerName을 값 체크 하여 리턴해 주는 함수. private func playerName(_ name: String?, withDefaultName defaultName: String) -> String { if let name = name { return name.isEmpty ? defaultName : name } else { return defaultName } } }
0
// // RegistrationContract.swift // AnimalHelper // // Created by Mike Martyniuk on 14.12.2020. // Copyright © 2020 animalHelper. All rights reserved. // import UIKit protocol RegistrationViewInterface: class { func reloadProfile() func activityIndicatorChange(_ state: Bool) func initSaveButtonState(state: Bool) } protocol RegistrationPresentation: class { func onViewDidLoad() func getData() ->[RegistrationTypeField] func textFieldChange(dataType: RegistrationTypeField, text: String?) func getFields() -> UserRegistrationFields func register() }
0
// // Copyright © 2019 An Tran. All rights reserved. // import SuperArcCoreComponent import SuperArcCoreUI // MARK: - DashboardComponentBuilder protocol DashboardComponentBuilder: ViewBuildable { func makeDashboardViewController() -> DashboardViewController } // MARK: - DashboardComponent class DashboardComponent: Component<EmptyDependency, DashboardComponentBuilder, EmptyInterface, EmptyComponentRoute>, DashboardComponentBuilder { // MARK: Properties var featureAComponent: FeatureAComponent! var featureBComponent: FeatureBComponent! // MARK: APIs func makeDashboardViewController() -> DashboardViewController { featureAComponent = FeatureAComponent(dependency: self, viewControllerContext: viewControllerContext, dependencyProvider: dependencyProvider) featureBComponent = FeatureBComponent(dependency: self, viewControllerContext: viewControllerContext, dependencyProvider: dependencyProvider) let dashboardViewController = DashboardViewController.instantiate(with: viewControllerContext) dashboardViewController.viewControllers = [ featureAComponent.makeFeatureAViewController().viewController, featureBComponent.makeFeatureBViewController().viewController ] return dashboardViewController } } // MARK: - Dependencies extension DashboardComponent: FeatureADependency {} extension DashboardComponent: FeatureBDependency {}
1
import SwiftUI import Combine final class MyObservableObject: ObservableObject { @Published private(set) var isDoingTheThing = false } struct MyView: View { @EnvironmentObject var observableObject: MyObservableObject var body: some View { MyBindingView(doTheThing: $observableObject.isDoingTheThing) // expected-error{{cannot assign to property: 'isDoingTheThing' setter is inaccessible}} } } struct MyBindingView: View { @Binding var doTheThing: Bool var body: some View { Text(doTheThing ? "Doing The Thing" : "Doing Sweet Nothing") } }
0
// // DULocationView.swift // DeUrgenta // // Created by Cristi Habliuc on 04.04.2021. // import UIKit @IBDesignable class DULocationView: UIView { private let stackView = UIStackView(frame: .zero) @IBInspectable var addressKindSetting: String = "" { didSet { addressKind = DUAddress.Kind(rawValue: addressKindSetting) ?? .home } } @IBInspectable var descriptionText: String = "" { didSet { descriptionLabel.text = descriptionText } } @IBInspectable var name: String = "" { didSet { nameLabel.text = name } } private var addressKind: DUAddress.Kind = .home { didSet { configureIcon() } } private let VerticalSpacing = CGFloat(4) private let HorizontalSpacing = CGFloat(8) private(set) var icon = UIImageView(frame: .zero) private(set) var nameLabel = DULabel(frame: .zero) private(set) var descriptionLabel = DULabel(frame: .zero) private(set) var isSetup = false override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder: NSCoder) { super.init(coder: coder) setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() } private func setup() { guard !isSetup else { return } defer { isSetup = true } backgroundColor = .clear stackView.axis = .vertical stackView.spacing = VerticalSpacing addSubview(stackView) stackView.snp.makeConstraints { make in make.edges.equalTo(self) } stackView.addArrangedSubview(descriptionLabel) let container = UIView(frame: .zero) stackView.addArrangedSubview(container) container.layer.cornerRadius = .buttonCornerRadius container.layer.borderWidth = 1 container.layer.borderColor = UIColor.inputBorder.cgColor let horizontalStack = UIStackView(frame: .zero) horizontalStack.axis = .horizontal horizontalStack.spacing = HorizontalSpacing container.addSubview(horizontalStack) horizontalStack.snp.makeConstraints { make in make.edges.equalTo(container).inset(UIEdgeInsets(top: 9, left: 13, bottom: 9, right: 13)) } horizontalStack.addArrangedSubview(icon) horizontalStack.addArrangedSubview(nameLabel) icon.snp.contentHuggingHorizontalPriority = 1000 icon.contentMode = .center icon.tintColor = .lighterText descriptionLabel.snp.contentCompressionResistanceVerticalPriority = 1000 descriptionLabel.snp.contentHuggingVerticalPriority = 1000 descriptionLabel.font = AppFontPreset.formSmallLabel.font() descriptionLabel.textColor = .lighterText nameLabel.font = AppFontPreset.formTextField.font() nameLabel.textColor = .regularText nameLabel.snp.makeConstraints { make in make.height.equalTo(CGFloat.formTextFieldHeight) } nameLabel.snp.contentCompressionResistanceVerticalPriority = 1000 nameLabel.snp.contentHuggingVerticalPriority = 1000 nameLabel.numberOfLines = 1 configureIcon() } private func configureIcon() { icon.image = UIImage.addressIcon(ofKind: addressKind) } }
0
// // BrickDimension.swift // BrickKit // // Created by Ruben Cagnie on 9/20/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import Foundation extension UIView { var isPortrait: Bool { return UIScreen.mainScreen().bounds.width <= UIScreen.mainScreen().bounds.height } var horizontalSizeClass: UIUserInterfaceSizeClass { return UIScreen.mainScreen().traitCollection.horizontalSizeClass } var verticalSizeClass: UIUserInterfaceSizeClass { return UIScreen.mainScreen().traitCollection.verticalSizeClass } } public indirect enum BrickDimension { case Ratio(ratio: CGFloat) case Fixed(size: CGFloat) case Auto(estimate: BrickDimension) case Orientation(landscape: BrickDimension, portrait: BrickDimension) case HorizontalSizeClass(regular: BrickDimension, compact: BrickDimension) case VerticalSizeClass(regular: BrickDimension, compact: BrickDimension) public func isEstimate(in view: UIView) -> Bool { switch self.dimension(in: view) { case .Auto(_): return true default: return false } } func dimension(in view: UIView) -> BrickDimension { switch self { case .Orientation(let landScape, let portrait): let isPortrait: Bool = view.isPortrait return (isPortrait ? portrait : landScape).dimension(in: view) case .HorizontalSizeClass(let regular, let compact): let isRegular = view.horizontalSizeClass == .Regular return (isRegular ? regular : compact).dimension(in: view) case .VerticalSizeClass(let regular, let compact): let isRegular = view.verticalSizeClass == .Regular return (isRegular ? regular : compact).dimension(in: view) default: return self } } func value(for otherDimension: CGFloat, in view: UIView) -> CGFloat { let actualDimension = dimension(in: view) switch actualDimension { case .Auto(let dimension): return dimension.value(for: otherDimension, in: view) default: return BrickDimension._rawValue(for: otherDimension, in: view, with: actualDimension) } } /// Function that gets the raw value of a BrickDimension. As of right now, only Ratio and Fixed are allowed static func _rawValue(for otherDimension: CGFloat, in view: UIView, with dimension: BrickDimension) -> CGFloat { switch dimension { case .Ratio(let ratio): return ratio * otherDimension case .Fixed(let size): return size default: fatalError("Only Ratio and Fixed are allowed") } } } extension BrickDimension: Equatable { } public func ==(lhs: BrickDimension, rhs: BrickDimension) -> Bool { switch (lhs, rhs) { case (let .Auto(estimate1), let .Auto(estimate2)): return estimate1 == estimate2 case (let .Ratio(ratio1), let .Ratio(ratio2)): return ratio1 == ratio2 case (let .Fixed(size1), let .Fixed(size2)): return size1 == size2 case (let .Orientation(landscape1, portrait1), let .Orientation(landscape2, portrait2)): return landscape1 == landscape2 && portrait1 == portrait2 case (let .HorizontalSizeClass(regular1, compact1), let .HorizontalSizeClass(regular2, compact2)): return regular1 == regular2 && compact1 == compact2 case (let .VerticalSizeClass(regular1, compact1), let .VerticalSizeClass(regular2, compact2)): return regular1 == regular2 && compact1 == compact2 default: return false } }
0
// // Post.swift // DemoAppL // // Created by Karol Zmysłowski on 29/05/2019. // Copyright © 2019 Karol. All rights reserved. // import Foundation // MARK: - Post struct Post: Codable { let userId, id: Int let title, body: String }
0
// // CAAnimationController.swift // POPAnimation // // Created by quanjunt on 2018/12/19. // Copyright © 2018 iOS-Jun. All rights reserved. // import UIKit class CAAnimationController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() titles = ["QQ粘性动画", "跑马灯效果", "录音动画效果", "水波纹效果"] vcArr = [QQAnimationViewController(), CarouseViewController(), TKWaterWaveViewController(), WaterWaveController()] } /* // 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. } */ }
0
import SwiftUI import SDWebImageSwiftUI enum ActiveSheet { case follower, following } struct TopView: View { @ObservedObject var userViewModel:UserObserver @State private var showSheet = false @State private var activeSheet: ActiveSheet = .follower var body: some View { HStack { //Image("test") AnimatedImage(url:URL(string: userViewModel.singleUserData.user?.pic ?? "")) .resizable() .clipShape(Circle()) .frame(width: 80, height: 80) .padding(.trailing) .shadow(color:Color.primary.opacity(0.04),radius: 2) HStack { VStack { Text("\(userViewModel.singleUserData.posts?.count ?? 0)") .bold() Text("Posts") .bold() } VStack { Text("\(userViewModel.singleUserData.user?.followers?.count ?? 0)") .bold() Text("Followers") .bold() .onTapGesture { if userViewModel.singleUserData.user?.followers?.count != 0{ self.showSheet = true self.activeSheet = .follower } } } VStack { Text("\(userViewModel.singleUserData.user?.following?.count ?? 0)") .bold() Text("Following") .bold() .onTapGesture { if userViewModel.singleUserData.user?.following?.count != 0{ self.showSheet = true self.activeSheet = .following } } } } } .sheet(isPresented: $showSheet) { if self.activeSheet == .follower { FollowerView(userViewModel: userViewModel) } else { FollowingView(userViewModel: userViewModel) } } } } //struct TopView_Previews: PreviewProvider { // static var previews: some View { // TopView() // .previewLayout(.sizeThatFits) // .padding() // } //}
0
// // WeatherWorker.swift // BHWeatherControl // // Created by Bassem Hatira on 18/01/2021. // import Foundation /** WeatherWorker. - Author: Bassem Hatira - Note: WeatherWorker class implement the weather services */ class WeatherWorker: AbstractService<WeatherRouter> { /** fetchCurrentWeathers return array of WeatherWrapper & Error, for multiple locations. - parameter locations: Multiple objects type of Location( lon: String, lat: String ). - parameter onCompleted: Callback contains ([WeatherWrapper], Error). # Notes: # 1. Parameter location must be an array of **BHWeatherCopntrol.Location** type */ func fetchCurrentWeathers(locations: [Location], onCompleted: @escaping ([WeatherWrapper], Error?) -> Void) { // DispatchGroup automatically manages the thread creation for multiple asynch tasks let group = DispatchGroup() var weathers: [WeatherWrapper] = [] var error: Error? locations.forEach { location in group.enter() // set routerType proprety of AbstractService to define a specific router routerType = WeatherRouter(type: .getCurrentWeather(location: location)) self.execute { (weather: WeatherObject) in // get a simple weatherWrapper object weathers.append(weather.getWeatherWrapper()) group.leave() } onError: { (theError) in error = theError group.leave() } } // notify the main thread when all task are completed group.notify(queue: .main) { //handle response onCompleted(weathers, error) } } /** fetchWeatherDetails return details of weathers for specific location. - parameter location: Location( lon: String, lat: String ). - parameter onSuccess: Callback contains WeatherWrapper Object. - parameter onError: Callback contains error in case of failure. # Notes: # 1. Parameter location must be **BHWeatherCopntrol.Location** type */ func fetchWeatherDetails(location: Location, onSuccess: @escaping (WeatherWrapper?) -> Void, onError: @escaping (Error?) -> Void) { // set routerType proprety of AbstractService to define a specific router routerType = WeatherRouter(type: .getWeatherDetails(location: location)) self.execute { (weather: WeatherObject) in //handle success onSuccess(weather.getWeatherWrapper()) } onError: { (error) in //handle error onError(error) } } }
0
// RUN: %target-swift-ide-test -repl-code-completion -source-filename %s | %FileCheck %s // CHECK: Begin completions // CHECK-NEXT: .self: _ // CHECK-NEXT: {{^}}true: Bool{{$}} // CHECK-NEXT: End completions tru
0
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { if true { let b = " " [ 1 ) let a { let : a { } protocol a { { } typealias e : e
0
// // AppDelegate.swift // SyncKitRealmSwift // // Created by Manuel Entrena on 29/08/2017. // Copyright © 2017 Manuel Entrena. All rights reserved. // import UIKit import RealmSwift import SyncKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var realmConfiguration: Realm.Configuration = { var configuration = Realm.Configuration() configuration.schemaVersion = 1 configuration.migrationBlock = { migration, oldSchemaVersion in if (oldSchemaVersion < 1) { } } configuration.objectTypes = [QSCompany.self, QSEmployee.self] return configuration }() var realm: Realm! lazy var synchronizer: QSCloudKitSynchronizer! = QSCloudKitSynchronizer.cloudKitPrivateSynchronizer(containerName: "your-container-name", configuration: self.realmConfiguration) lazy var sharedSynchronizer: QSCloudKitSynchronizer! = QSCloudKitSynchronizer.cloudKitSharedSynchronizer(containerName: "your-container-name", configuration: self.realmConfiguration) func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. realm = try! Realm(configuration: realmConfiguration) if let tabBarController = window?.rootViewController as? UITabBarController { if let navController = tabBarController.viewControllers![0] as? UINavigationController, let companyVC = navController.topViewController as? QSCompanyTableViewController { companyVC.realm = realm companyVC.synchronizer = synchronizer } if let navController = tabBarController.viewControllers![1] as? UINavigationController, let sharedCompanyVC = navController.topViewController as? QSSharedCompanyTableViewController { sharedCompanyVC.synchronizer = sharedSynchronizer } if let navController = tabBarController.viewControllers![2] as? UINavigationController, let settingsVC = navController.topViewController as? QSSettingsTableViewController { settingsVC.privateSynchronizer = synchronizer settingsVC.sharedSynchronizer = sharedSynchronizer } } 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:. } //MARK: - Accepting shares func application(_ application: UIApplication, userDidAcceptCloudKitShareWith cloudKitShareMetadata: CKShareMetadata) { let container = CKContainer(identifier: cloudKitShareMetadata.containerIdentifier) let acceptSharesOperation = CKAcceptSharesOperation(shareMetadatas: [cloudKitShareMetadata]) acceptSharesOperation.qualityOfService = .userInteractive acceptSharesOperation.acceptSharesCompletionBlock = { error in if let error = error { let alertController = UIAlertController(title: "Error", message: "Could not accept CloudKit share: \(error.localizedDescription)", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) } else { self.sharedSynchronizer.synchronize(completion: nil) } } container.add(acceptSharesOperation) } }
0
// // UIColor.swift // toytt // // Created by user on 2018/7/19. // Copyright © 2018年 grayworm. All rights reserved. // import UIKit extension UIColor { convenience init(hexValue: UInt, alpha: CGFloat = 1.0) { let r = Float((hexValue & 0xFF0000) >> 16) / 255.0 let g = Float((hexValue & 0xFF00) >> 8) / 255.0 let b = Float(hexValue & 0xFF) / 255.0 self.init(red: r.cgFloat, green: g.cgFloat, blue: b.cgFloat, alpha: alpha) } }
0
// // SimctlShared.swift // // // Created by Christian Treffs on 18.03.20. // import Foundation public typealias Port = UInt16 public enum PushNotificationContent { /// Path to a push payload .json/.apns file. /// /// The file must reside on the host machine! /// The file must be a JSON file with a valid Apple Push Notification Service payload, including the “aps” key. /// It must also contain a top-level “Simulator Target Bundle” with a string value /// that matches the target application‘s bundle identifier. case file(URL) /// Arbitrary json encoded push notification payload. /// /// The payload must be JSON with a valid Apple Push Notification Service payload, including the “aps” key. /// It must also contain a top-level “Simulator Target Bundle” with a string value /// that matches the target application‘s bundle identifier. case jsonPayload(Data) } extension PushNotificationContent { enum Keys: String, CodingKey { case file case jsonPayload } } extension PushNotificationContent: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Keys.self) switch self { case let .file(url): try container.encode(url, forKey: .file) case let .jsonPayload(data): try container.encode(data, forKey: .jsonPayload) } } } extension PushNotificationContent: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) if let url = try container.decodeIfPresent(URL.self, forKey: .file) { self = .file(url) } else if let data = try container.decodeIfPresent(Data.self, forKey: .jsonPayload) { self = .jsonPayload(data) } else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "unknown case")) } } } /// Swifter makes all header field keys lowercase so we define them lowercase from the start. public enum HeaderFieldKey: String { case bundleIdentifier = "bundleidentifier" case deviceUdid = "deviceudid" case privacyAction = "privacyaction" case privacyService = "privacyservice" } public enum ServerPath: String { case pushNotification = "/simctl/pushNotification" case privacy = "/simctl/privacy" } /// Some permission changes will terminate the application if running. public enum PrivacyAction: String { /// Grant access without prompting. Requires bundle identifier. case grant /// Revoke access, denying all use of the service. Requires bundle identifier. case revoke /// Reset access, prompting on next use. Bundle identifier optional. case reset } public enum PrivacyService: String { /// Apply the action to all services. case all /// Allow access to calendar. case calendar /// Allow access to basic contact info. case contactsLimited = "contacts-limited" /// Allow access to full contact details. case contacts /// Allow access to location services when app is in use. case location /// Allow access to location services at all times. case locationAllways = "location-always" /// Allow adding photos to the photo library. case photosAdd = " photos-add" /// Allow full access to the photo library. case photos ///ibrary - Allow access to the media library. case media /// Allow access to audio input. case microphone /// Allow access to motion and fitness data. case motion /// Allow access to reminders. case reminders /// Allow use of the app with Siri. case siri } public struct SimulatorDeviceListing { public enum Keys: String, CodingKey { case devices } public let devices: [SimulatorDevice] } extension SimulatorDeviceListing: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) let dict = try container.decode([String: [SimulatorDevice]].self, forKey: .devices) self.devices = dict.values.flatMap { $0 } } } public struct SimulatorDevice { public let udid: UUID public let name: String public let isAvailable: Bool public let deviceTypeIdentifier: String public let state: State public let logPath: URL public let dataPath: URL } extension SimulatorDevice { public var deviceId: String { udid.uuidString } } extension SimulatorDevice: CustomStringConvertible { public var description: String { "<SimulatorDevice[\(deviceId)]: \(name) (\(state))>" } } extension SimulatorDevice { public enum State: String { case shutdown = "Shutdown" case booted = "Booted" } } extension SimulatorDevice: Decodable { } extension SimulatorDevice.State: Decodable { }
0
import Foundation import HTTP public final class FileMiddleware: Middleware { private var publicDir: String private let loader = DataFile() @available(*, deprecated: 1.2, message: "This has been renamed to publicDir: and now represents the absolute path. Use `workDir.finished(\"/\") + \"Public/\"` to reproduce existing behavior.") public init(workDir: String) { self.publicDir = workDir.finished(with: "/") + "Public/" } public init(publicDir: String) { // Remove last "/" from the publicDir if present, so we can directly append uri path from the request. self.publicDir = publicDir.finished(with: "/") } public func respond(to request: Request, chainingTo next: Responder) throws -> Response { do { return try next.respond(to: request) } catch Abort.notFound { // Check in file system var path = request.uri.path if path.hasPrefix("/") { path = String(path.characters.dropFirst()) } let filePath = publicDir + path guard let attributes = try? Foundation.FileManager.default.attributesOfItem(atPath: filePath), let modifiedAt = attributes[.modificationDate] as? Date, let fileSize = attributes[.size] as? NSNumber else { throw Abort.notFound } var headers: [HeaderKey: String] = [:] // Generate ETag value, "HEX value of last modified date" + "-" + "file size" let fileETag = "\(modifiedAt.timeIntervalSince1970)-\(fileSize.intValue)" headers["ETag"] = fileETag // Check if file has been cached already and return NotModified response if the etags match if fileETag == request.headers["If-None-Match"] { return Response(status: .notModified, headers: headers, body: .data([])) } // File exists and was not cached, returning content of file. if let fileBody = try? loader.load(path:filePath) { if let fileExtension = filePath.components(separatedBy: ".").last, let type = mediaTypes[fileExtension] { headers["Content-Type"] = type } return Response(status: .ok, headers: headers, body: .data(fileBody)) } else { print("unable to load path") throw Abort.notFound } } } }
0
// // CurrentlyForecast.swift // WeatherApp // // Created by Ilias Pavlidakis on 25/06/2019. // Copyright © 2019 Ilias Pavlidakis. All rights reserved. // import Foundation struct CurrentlyForecast: Codable, Equatable { let apparentTemperature: Float? let cloudCover: Float? let dewPoint: Float? let humidity: Float? let icon: ForecastIcon? let moonPhase: Float? let nearestStormBearing: Float? let nearestStormDistance: Float? let ozone: Float? let precipIntensity: Float? let precipIntensityError: Float? let precipProbability: Float? let precipType: ForecastPrecipType? let pressure: Float? let summary: String? let temperature: Float? let time: TimeInterval let uvIndex: Float? let visibility: Float? let windBearing: Float? let windGust: Float? let windSpeed: Float? }
0
// // CouponConfirmationViewController.swift // aboon // // Created by 原口和音 on 2018/08/12. // Copyright © 2018年 aboon. All rights reserved. // import UIKit import RxSwift import RxCocoa class CouponConfirmationViewController: UIViewController { let disposeBag = DisposeBag() let coupon: Coupon let members: [Member] let roomId: String let image: UIImage lazy var couponConfirmationView = CouponConfirmationView() lazy var model = CouponConfirmationModel() init(coupon: Coupon, members: [Member], roomId: String, image: UIImage) { self.coupon = coupon self.members = members self.roomId = roomId self.image = image super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .overCurrentContext } override func loadView() { self.view = couponConfirmationView } override func viewDidLoad() { super.viewDidLoad() couponConfirmationView.configure(coupon: coupon, image: image) couponConfirmationView .couponConfirmed .subscribe(onNext: { [weak self] (isPressed) in guard let `self` = self else { return } if isPressed { self.model.useCoupon(roomId: self.roomId, members: self.members) guard let presentingViewController = self.presentingViewController else { return } let confirmedAlert = UIAlertController(title: "完了", message: "クーポンが承認されました!aboonのまたのご利用をお待ちしております!", preferredStyle: .alert) confirmedAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (_) in self.dismiss(animated: true, completion: { (presentingViewController as! NavigationController).popToRootViewController(animated: true) }) })) self.present(confirmedAlert, animated: true, completion: nil) } }) .disposed(by: disposeBag) couponConfirmationView .dismissPressed .subscribe(onNext: { [weak self] (isPressed) in guard let `self` = self else { return } if isPressed { self.dismiss(animated: true, completion: nil) } }) .disposed(by: disposeBag) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } 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. } */ }
0
// // TrafficLight.swift // TinyCoreTests // // Created by Roy Hsu on 23/01/2018. // Copyright © 2018 TinyWorld. All rights reserved. // // MARK: - TouchEvent import TinyCore internal enum TrafficLight: String { case red, green, yellow }
0
// // ScheduleHeaderCell.swift // SwiftIsland // // Created by Paul Peelen on 2019-04-21. // Copyright © 2019 AppTrix AB. All rights reserved. // import UIKit class ScheduleHeaderCell: UITableViewCell { @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timelineLine: UIView! lazy var dateFormatter: DateFormatter = { let dateFormatter = DateFormatter.init() dateFormatter.timeStyle = .none dateFormatter.dateStyle = .full return dateFormatter }() override func prepareForReuse() { super.prepareForReuse() dateLabel.text = "" } func setup(with schedule: Schedule, faded: Bool) { selectionStyle = .none dateLabel.text = dateFormatter.string(from: schedule.date) timelineLine.alpha = faded ? Theme.fadedAlpha : 1 } }
0
// // User.swift // PlisterTests // // Created by Mohammad reza Koohkan on 2/21/1399 AP. // Copyright © 1399 AP Apple Code. All rights reserved. // import Foundation struct User: Codable, Equatable { var uuid: String = UUID().uuidString var name: String var age: Int var createdAt: Date static func == (lhs: Self, rhs: Self) -> Bool { lhs.uuid == rhs.uuid } }
0
// // BreweryBrowseTableViewController.swift // growlers // // Created by Chris Budro on 9/8/15. // Copyright (c) 2015 chrisbudro. All rights reserved. // import UIKit class BreweryBrowseTableViewController: BaseBrowseViewController { //MARK: Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() title = "Breweries" cellReuseIdentifier = kBreweryCellReuseIdentifier tableView.registerNib(UINib(nibName: kBreweryNibName, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier) dataSource = TableViewDataSource(cellReuseIdentifier:cellReuseIdentifier, configureCell: configureCell) tableView.dataSource = dataSource updateBrowseList() } } //MARK: Table View Delegate extension BreweryBrowseTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = BreweryDetailTableViewController(style: .Plain) if let brewery = dataSource?.objectAtIndexPath(indexPath) as? Brewery { vc.brewery = brewery if let queryManager = queryManager { let breweryQueryManager = QueryManager(type: .Tap, filter: queryManager.filter) vc.queryManager = breweryQueryManager } } navigationController?.pushViewController(vc, animated: true) } }
0
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import PackageModel import SourceControl extension PackageDependencyDescription { /// Create the package reference object for the dependency. public func createPackageRef(config: SwiftPMConfig) -> PackageReference { let effectiveURL = config.mirroredURL(forURL: url) // FIXME: The identity of a package dependency is currently based on // on a name computed from the package's effective URL. This // is because the name of the package that's in the manifest // is not known until the manifest has been parsed. // We should instead use the declared URL of a package dependency // as its identity, as it will be needed for supporting package // registries. let identity = PackageReference.computeIdentity(packageURL: effectiveURL) return PackageReference( identity: identity, path: effectiveURL, kind: requirement == .localPackage ? .local : .remote ) } } extension Manifest { /// Constructs constraints of the dependencies in the raw package. public func dependencyConstraints(productFilter: ProductFilter, config: SwiftPMConfig) -> [RepositoryPackageConstraint] { return dependenciesRequired(for: productFilter).map({ return RepositoryPackageConstraint( container: $0.createPackageRef(config: config), requirement: $0.requirement.toConstraintRequirement(), products: $0.productFilter) }) } } extension RepositoryPackageConstraint { internal func nodes() -> [DependencyResolutionNode] { switch products { case .everything: return [.root(package: identifier)] case .specific: switch products { case .everything: fatalError("Attempted to enumerate a root package’s product filter; root packages have no filter.") case .specific(let set): if set.isEmpty { // Pointing at the package without a particular product. return [.empty(package: identifier)] } else { return set.sorted().map { .product($0, package: identifier) } } } } } } extension PackageReference { /// The repository of the package. /// /// This should only be accessed when the reference is not local. public var repository: RepositorySpecifier { precondition(kind == .remote) return RepositorySpecifier(url: path) } }
0
// // TypeScriptJS.swift // cs2js // // Created by Kenta Kubo on 3/29/16. // Copyright © 2016 Kenta Kubo. All rights reserved. // import JavaScriptCore public struct TypeScriptCompiler: JSCompiler { public static let instance = TypeScriptCompiler() public let context: JSContext = { let ctx: JSContext = JSContext() do { let str = try String(contentsOfFile: Bundle.main.path(forResource: "typescriptServices", ofType: "js")!, encoding: .utf8) ctx.evaluateScript(str) } catch { } return ctx }() public func compile(code: String, options: [String: Any]? = nil) -> String { return context.objectForKeyedSubscript("ts").invokeMethod("transpile", withArguments: [code, options ?? [:]]).description } }
0
// // CBPeripheralProtcolDelegate.swift // factory-tourguide-iOS // // Created by kazuya ito on 2020/10/28. // import Foundation import CoreBluetooth // MARK: - CBPeripheral protocol CBPeripheralProtocolDelegate { func didDiscoverServices(_ peripheral: CBPeripheralProtocol, error: Error?) func didDiscoverCharacteristics(_ peripheral: CBPeripheralProtocol, service: CBService, error: Error?) func didUpdateValue(_ peripheral: CBPeripheralProtocol, characteristic: CBCharacteristic, error: Error?) func didWriteValue(_ peripheral: CBPeripheralProtocol, descriptor: CBDescriptor, error: Error?) } public protocol CBPeripheralProtocol { var delegate: CBPeripheralDelegate? { get set } var name: String? { get } var identifier: UUID { get } var state: CBPeripheralState { get } var services: [CBService]? { get } var debugDescription: String { get } func discoverServices(_ serviceUUIDs: [CBUUID]?) func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: CBService) func discoverDescriptors(for characteristic: CBCharacteristic) func writeValue(_ data: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType) func readValue(for characteristic: CBCharacteristic) func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic) } extension CBPeripheral : CBPeripheralProtocol {} // MARK: - CBCentralManager public protocol CBCentralManagerProtocolDelegate { func didUpdateState(_ central: CBCentralManagerProtocol) func willRestoreState(_ central: CBCentralManagerProtocol, dict: [String : Any]) func didDiscover(_ central: CBCentralManagerProtocol, peripheral: CBPeripheralProtocol, advertisementData: [String : Any], rssi: NSNumber) func didConnect(_ central: CBCentralManagerProtocol, peripheral: CBPeripheralProtocol) func didFailToConnect(_ central: CBCentralManagerProtocol, peripheral: CBPeripheralProtocol, error: Error?) func didDisconnect(_ central: CBCentralManagerProtocol, peripheral: CBPeripheralProtocol, error: Error?) func connectionEventDidOccur(_ central: CBCentralManagerProtocol, event: CBConnectionEvent, peripheral: CBPeripheralProtocol) func didUpdateANCSAuthorization(_ central: CBCentralManagerProtocol, peripheral: CBPeripheralProtocol) } public protocol CBCentralManagerProtocol { var delegate: CBCentralManagerDelegate? { get set } var state: CBManagerState { get } var isScanning: Bool { get } init(delegate: CBCentralManagerDelegate?, queue: DispatchQueue?, options: [String : Any]?) func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String : Any]?) func stopScan() func connect(_ peripheral: CBPeripheralProtocol, options: [String : Any]?) func cancelPeripheralConnection(_ peripheral: CBPeripheralProtocol) func retrievePeripherals(_ identifiers: [UUID]) -> [CBPeripheralProtocol] } extension CBCentralManager : CBCentralManagerProtocol { public func connect(_ peripheral: CBPeripheralProtocol, options: [String: Any]?) { guard let peripheral = peripheral as? CBPeripheral else { return } connect(peripheral, options: options) } public func cancelPeripheralConnection(_ peripheral: CBPeripheralProtocol) { guard let peripheral = peripheral as? CBPeripheral else { return } cancelPeripheralConnection(peripheral) } public func retrievePeripherals(_ identifiers: [UUID]) -> [CBPeripheralProtocol] { return retrievePeripherals(withIdentifiers: identifiers) } }
0
// // ViewController.swift // collectionViewDemo // // Created by 梁亦明 on 16/3/17. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit import Alamofire let SCREEN_WIDTH : CGFloat = UIScreen.mainScreen().bounds.width let SCREEN_HEIGHT : CGFloat = UIScreen.mainScreen().bounds.height let UI_NAV_HEIGHT : CGFloat = 64 class ViewController: UIViewController { //MARK: --------------------------- LifeCycle -------------------------- override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(collectionView) getTodayData() } //MARK: --------------------------- Network -------------------------- private func getTodayData() { let api = "http://baobab.wandoujia.com/api/v2/feed?date=1458120409379&num=7" Alamofire.request(.GET, api).responseSwiftyJSON ({[unowned self](request, Response, json, error) -> Void in if json != .null && error == nil{ self.model = Model(dict: json.rawValue as! NSDictionary) self.collectionView.reloadData() } }) } //MARK: --------------------------- Getter or Setter -------------------------- /// 模型数据 var model : Model? /// tableView private lazy var collectionView : UICollectionView = { /// 布局 var layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: SCREEN_WIDTH, height: 235) layout.sectionInset = UIEdgeInsetsZero layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 var collectionView : UICollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout:layout) // 注册cell collectionView.registerClass(EYEChoiceCell.self, forCellWithReuseIdentifier: EYEChoiceCell.reuseIdentifier) // 注册header collectionView.registerClass(EYEChoiceHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier) collectionView.delegate = self collectionView.dataSource = self return collectionView }() } //MARK: --------------------------- UICollectionViewDelegate, UICollectionViewDataSource -------------------------- extension ViewController : UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { if let _ = model { return (model?.issueList.count)! } return 0 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let issueList : [Model.IssueModel] = (model?.issueList)! let issueModel : Model.IssueModel = issueList[section] let itemList = issueModel.itemList return itemList.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let issueModel = model?.issueList[indexPath.section] let cell : EYEChoiceCell = collectionView.dequeueReusableCellWithReuseIdentifier(EYEChoiceCell.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceCell cell.model = issueModel?.itemList[indexPath.row] return cell } /** * section HeaderView */ func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // if kind == UICollectionElementKindSectionHeader { let headerView : EYEChoiceHeaderView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: EYEChoiceHeaderView.reuseIdentifier, forIndexPath: indexPath) as! EYEChoiceHeaderView let issueModel = model?.issueList[indexPath.section] if let image = issueModel?.headerImage { headerView.image = image print ("image:\(image)") } else { headerView.title = issueModel?.headerTitle print ("title:\(issueModel?.headerTitle)") } return headerView // } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { // 获取cell的类型 let issueModel = model?.issueList[section] if issueModel!.isHaveSectionView { return CGSize(width: SCREEN_WIDTH, height: 50) } else { return CGSizeZero } } }
0
// // 🦠 Corona-Warn-App // import UIKit final class HomeLoadingItemView: UIView, HomeItemView, HomeItemViewSeparatorable { // MARK: - Overrides override func awakeFromNib() { super.awakeFromNib() stackView.isLayoutMarginsRelativeArrangement = true stackView.layoutMargins = UIEdgeInsets(top: 16.0, left: 0.0, bottom: 16.0, right: 0.0) configureActivityIndicatorView() configureStackView() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) configureActivityIndicatorView() configureStackView() } // MARK: - Protocol HomeItemView func configure(with viewModel: HomeLoadingItemViewModel) { activityIndicatorView.color = viewModel.titleColor textLabel?.text = viewModel.title textLabel?.textColor = viewModel.titleColor separatorView?.backgroundColor = viewModel.separatorColor if viewModel.isActivityIndicatorOn { activityIndicatorView.startAnimating() } else { activityIndicatorView.stopAnimating() } backgroundColor = viewModel.color } // MARK: - Protocol RiskItemViewSeparatorable func hideSeparator() { separatorView.isHidden = true } // MARK: - Private @IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView! @IBOutlet private weak var textLabel: ENALabel! @IBOutlet private weak var separatorView: UIView! @IBOutlet private weak var stackView: UIStackView! private func configureActivityIndicatorView() { let greaterThanAccessibilityMedium = traitCollection.preferredContentSizeCategory >= .accessibilityLarge if #available(iOS 13.0, *) { activityIndicatorView.style = greaterThanAccessibilityMedium ? .large : .medium } else { activityIndicatorView.style = greaterThanAccessibilityMedium ? .whiteLarge : .white } } private func configureStackView() { if traitCollection.preferredContentSizeCategory >= .accessibilityLarge { stackView.spacing = 8.0 } else { stackView.spacing = 16.0 } } }
0
import Foundation enum Endpoint { struct Overview: Codable { let active_subscribers_count: Int let active_trials_count: Int let active_users_count: Int let installs_count: Int let mrr: Double let revenue: Double } struct Transaction: Codable, Hashable { let store_transaction_identifier: String } struct Transactions: Codable, Hashable { let transactions: [Transaction] } struct Error: Decodable { let code: Int let message: String } struct Response { let transactions: Set<Endpoint.Transaction> let overview: Endpoint.Overview } }
0
// // CropView+Touches.swift // Mantis // // Created by Echo on 5/24/19. // import Foundation import UIKit extension CropView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let newPoint = self.convert(point, to: self) if let rotationDial = rotationDial, rotationDial.frame.contains(newPoint) { return rotationDial } if isHitGridOverlayView(by: newPoint) { return self } if self.bounds.contains(newPoint) { return self.scrollView } return nil } private func isHitGridOverlayView(by touchPoint: CGPoint) -> Bool { let hotAreaUnit = cropViewConfig.cropBoxHotAreaUnit return gridOverlayView.frame.insetBy(dx: -hotAreaUnit/2, dy: -hotAreaUnit/2).contains(touchPoint) && !gridOverlayView.frame.insetBy(dx: hotAreaUnit/2, dy: hotAreaUnit/2).contains(touchPoint) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) guard touches.count == 1, let touch = touches.first else { return } // A resize event has begun by grabbing the crop UI, so notify delegate delegate?.cropViewDidBeginResize(self) if touch.view is RotationDial { viewModel.setTouchRotationBoardStatus() return } let point = touch.location(in: self) viewModel.prepareForCrop(byTouchPoint: point) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) guard touches.count == 1, let touch = touches.first else { return } if touch.view is RotationDial { return } let point = touch.location(in: self) updateCropBoxFrame(with: point) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if viewModel.needCrop() { gridOverlayView.handleEdgeUntouched() let contentRect = getContentBounds() adjustUIForNewCrop(contentRect: contentRect) {[weak self] in self?.delegate?.cropViewDidEndResize(self!) self?.viewModel.setBetweenOperationStatus() self?.scrollView.updateMinZoomScale() } } else { delegate?.cropViewDidEndResize(self) viewModel.setBetweenOperationStatus() } } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer is UIPanGestureRecognizer { return false } return true } }
0
// // HECryptoModule.swift // IntegerHomomorphicEncryption // // Created by Nicklas Körtge on 09.04.21. // import Foundation class HECryproModule { let securityParameter : Int let degree : Int let distribution : Distribution let context : Context struct Context { let decomposeBase : Double let messageSpace : Double let parameter_q : Int64 let ringPolynomial : Polynomial func equals(context: Context) -> Bool { return (self.decomposeBase == context.decomposeBase && self.messageSpace == context.messageSpace && self.parameter_q == context.parameter_q && self.ringPolynomial == context.ringPolynomial) } } struct PublicKey { let context: Context let pk0 : Polynomial let pk1 : Polynomial let evaluationKey : EvaluationKey } struct EvaluationKey { let rlks0 : [Polynomial] let rlks1 : [Polynomial] } struct PrivateKey { let sk : Polynomial } init(securityParameter : Int, degree : Int, decomposeBase : Int, messageSpace : Int, parameter_q : Int, ringPolynomial : Polynomial, distribution: Distribution) { self.securityParameter = Int(securityParameter) self.degree = Int(degree) self.context = Context(decomposeBase: Double(decomposeBase), messageSpace: Double(messageSpace), parameter_q: Int64(parameter_q), ringPolynomial: ringPolynomial) self.distribution = distribution } init() { self.securityParameter = 4 self.degree = Int(pow(2.0, Double(securityParameter))) self.context = Context(decomposeBase: 2, messageSpace: pow(2.0, 10.0), parameter_q: Int64(pow(2.0, 20.0) * Double(Int(pow(2.0, 10.0)))), ringPolynomial: Polynomial(coefficients: Array<Int64>([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))) //x^16+1 self.distribution = NormalDistribution(mean: 0.0, deviation: 2.0) } /// This function creates the public and private key for the encryption /// - Returns: tuple of public key and private key func createKeypair() -> (PublicKey, PrivateKey) { // private key let s = createPolynomial(of: self.degree, in: 0...1) // public key let a = createPolynomial(of: self.degree, in: 0...self.context.parameter_q-1) //%% self.parameter_q let e = createPolynomial(of: self.degree, with: distribution) %% self.context.parameter_q let pk0 = HECryproModule.stripPolynomial(polynomial: ((a * s) * -1.0) + e, moduloPolynomial: self.context.ringPolynomial, moduloInt: self.context.parameter_q) let pk1 = a // evaluation key let l = Int(floor(log_b(Double(self.context.parameter_q), Double(self.context.decomposeBase)))) var rlks0 = [Polynomial]() var rlks1 = [Polynomial]() for i in 0..<(l + 1) { let a_i = createPolynomial(of: self.degree, in: 0...self.context.parameter_q-1) let e_i = createPolynomial(of: self.degree, with: distribution) %% self.context.parameter_q let rlk0_t = (((a_i * s) * -1.0) + e_i) + ((powP(lhs: s, rhs: 2)) * pow(self.context.decomposeBase, Double(i))) let rlk0 = HECryproModule.stripPolynomial(polynomial: rlk0_t, moduloPolynomial: self.context.ringPolynomial, moduloInt: self.context.parameter_q) rlks0.append(rlk0) let rlk1 = a_i rlks1.append(rlk1) } let evalKey = EvaluationKey(rlks0: rlks0, rlks1: rlks1) return (PublicKey(context: context, pk0: pk0, pk1: pk1, evaluationKey: evalKey), PrivateKey(sk: s)) } func encrypt(message: Int, with publickey: PublicKey) -> EncryptedInteger { let u = createPolynomial(of: self.degree, with: distribution) %% self.context.parameter_q let e1 = createPolynomial(of: self.degree, with: distribution) %% self.context.parameter_q let e2 = createPolynomial(of: self.degree, with: distribution) %% self.context.parameter_q let delta = floor(Double(self.context.parameter_q) / self.context.messageSpace) let c0 = HECryproModule.stripPolynomial(polynomial: (publickey.pk0 * u) + e1 + (delta * Double(message)), moduloPolynomial: self.context.ringPolynomial, moduloInt: self.context.parameter_q) let c1 = HECryproModule.stripPolynomial(polynomial: (publickey.pk1 * u) + e2, moduloPolynomial: self.context.ringPolynomial, moduloInt: self.context.parameter_q) return EncryptedInteger(c0: c0, c1: c1, context: self.context) } func encrypt(message: String, with publickey: PublicKey) -> EncryptedString { let lzw_compressed = LZW.shared.compress(message) var encryptedCodes = [EncryptedInteger]() for code in lzw_compressed { encryptedCodes.append(encrypt(message: code, with: publickey)) } return EncryptedString(code: encryptedCodes) } func decrypt(cipher: EncryptedInteger, with privatekey: PrivateKey) -> Int { let q2 = self.context.messageSpace / Double(self.context.parameter_q) let v = HECryproModule.stripPolynomial(polynomial: cipher.c0 + cipher.c1 * privatekey.sk, moduloPolynomial: self.context.ringPolynomial, moduloInt: self.context.parameter_q) var res = (v * q2).roundP() res = res %% Int64(self.context.messageSpace) return Int(res.coefficients[0]) } func decrypt(cipher: EncryptedString, with privatekey: PrivateKey) -> String? { var lzw_encoded = [Int]() for encryptedCode in cipher.code { lzw_encoded.append(decrypt(cipher: encryptedCode, with: privatekey)) } return LZW.shared.decompress(lzw_encoded) } static func baseDecomposition(polynomial: Polynomial, base: Int64, moduloInt: Int64) -> [Polynomial] { let l = Int(floor(log_b(Double(moduloInt), Double(base)))) var result = [Polynomial]() for i in 0..<(l + 1) { let rebase = (polynomial / (pow(Double(base), Double(i)))).floorP() result.append(rebase %% base) } return result } static func stripPolynomial(polynomial: Polynomial, moduloPolynomial: Polynomial, moduloInt: Int64) -> Polynomial { let poly_div = polynomial / moduloPolynomial let poly_res = poly_div.0.floorP() let poly_mod = poly_res %% moduloInt return poly_mod } } class EncryptedString { var code : [EncryptedInteger] init(code: [EncryptedInteger]) { self.code = code } } class EncryptedInteger { var c0 : Polynomial var c1 : Polynomial let context : HECryproModule.Context init(c0: Polynomial, c1: Polynomial, context: HECryproModule.Context) { self.c0 = c0 self.c1 = c1 self.context = context } func mult(value rhs: EncryptedInteger, with publicKey: HECryproModule.PublicKey) -> EncryptedInteger? { guard self.context.equals(context: rhs.context) else { return nil } let q2 = Double(context.messageSpace) / Double(context.parameter_q) let c0_t = ((self.c0 * rhs.c0) * q2).roundP() let c0 = HECryproModule.stripPolynomial(polynomial: c0_t, moduloPolynomial: context.ringPolynomial, moduloInt: context.parameter_q) let c1_t = (((self.c0 * rhs.c1) + (self.c1 * rhs.c0)) * q2).roundP() let c1 = HECryproModule.stripPolynomial(polynomial: c1_t, moduloPolynomial: context.ringPolynomial, moduloInt: context.parameter_q) let c2_t = ((self.c1 * rhs.c1) * q2).roundP() let c2 = HECryproModule.stripPolynomial(polynomial: c2_t, moduloPolynomial: context.ringPolynomial, moduloInt: context.parameter_q) let l = Int(floor(log_b(Double(self.context.parameter_q), Double(self.context.decomposeBase)))) let decompose_c2 = HECryproModule.baseDecomposition(polynomial: c2, base: Int64(context.decomposeBase), moduloInt: context.parameter_q) var sum_with_rlk0 : Polynomial = Polynomial(coefficients: [Double](repeating: 0.0, count: publicKey.evaluationKey.rlks0[0].coefficients.count + decompose_c2[0].coefficients.count-1)) var sum_with_rlk1 = sum_with_rlk0 for i in 0..<(l + 1) { sum_with_rlk0 = sum_with_rlk0 + (publicKey.evaluationKey.rlks0[i] * decompose_c2[i]) sum_with_rlk1 = sum_with_rlk1 + (publicKey.evaluationKey.rlks1[i] * decompose_c2[i]) } let res_c0 = c0 + sum_with_rlk0 let res_c1 = c1 + sum_with_rlk1 return EncryptedInteger(c0: res_c0, c1: res_c1, context: self.context) } } func +(lhs: EncryptedInteger, rhs: EncryptedInteger) -> EncryptedInteger? { guard lhs.context.equals(context: rhs.context) else { return nil } let c0 = HECryproModule.stripPolynomial(polynomial: (lhs.c0 + rhs.c0), moduloPolynomial: lhs.context.ringPolynomial, moduloInt: lhs.context.parameter_q) let c1 = HECryproModule.stripPolynomial(polynomial: (lhs.c1 + rhs.c1), moduloPolynomial: lhs.context.ringPolynomial, moduloInt: lhs.context.parameter_q) return EncryptedInteger(c0: c0, c1: c1, context: lhs.context) }
0
import SwiftUI // Thanks to https://www.avanderlee.com/swiftui/withanimation-completion-callback/ struct AnimationCompletionObserverModifier<Value>: AnimatableModifier where Value: VectorArithmetic { var animatableData: Value { didSet { self.callCompletionIfFinished() } } // Private private var targetValue: Value private var onComplete: () -> Void // MARK: Initialization init(observedValue: Value, onComplete: @escaping () -> Void) { self.onComplete = onComplete self.animatableData = observedValue self.targetValue = observedValue } // MARK: Body func body(content: Content) -> some View { content } // MARK: Helpers private func callCompletionIfFinished() { guard self.animatableData == self.targetValue else { return } Task { self.onComplete() } } } // MARK: View extension View { func onAnimationCompletion<Value: VectorArithmetic>( with value: Value, onComplete: @escaping () -> Void ) -> ModifiedContent<Self, AnimationCompletionObserverModifier<Value>> { self.modifier( AnimationCompletionObserverModifier( observedValue: value, onComplete: onComplete ) ) } }
0
import UIKit import Spots @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var navigationController: UINavigationController? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) SpotFactory.register("cards", spot: CardSpot.self) CarouselSpot.views["card"] = CardSpotCell.self CarouselSpot.configure = { collectionView in collectionView.backgroundColor = UIColor(red:0.110, green:0.110, blue:0.110, alpha: 1) } SpotsController.configure = { $0.backgroundColor = UIColor.whiteColor() } let controller = JSONController() controller.title = "Spots Cards".uppercaseString navigationController = UINavigationController(rootViewController: controller) window?.rootViewController = navigationController applyStyles() window?.makeKeyAndVisible() return true } func applyStyles() { UIApplication.sharedApplication().statusBarStyle = .LightContent let navigationBar = UINavigationBar.appearance() navigationBar.barTintColor = UIColor(red:0.000, green:0.000, blue:0.000, alpha: 1) navigationBar.tintColor = UIColor(red:1.000, green:1.000, blue:1.000, alpha: 1) navigationBar.shadowImage = UIImage() navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor(red:1.000, green:1.000, blue:1.000, alpha: 1) ] } }
0
// // Amatino Swift // Transaction.swift // // author: [email protected] // import Foundation public final class Transaction: EntityObject, Denominated { internal init( _ entity: Entity, _ attributes: Transaction.Attributes ) { self.entity = entity self.attributes = attributes return } internal let attributes: Transaction.Attributes public static let maxDescriptionLength = 1024 public static let maxArguments = 10 private static let path = "/transactions" private static let urlKey = "transaction_id" public let entity: Entity public var session: Session { get { return entity.session } } public var id: Int { get { return attributes.id } } public var transactionTime: Date { get { return attributes.transactionTime}} public var versionTime: Date { get { return attributes.versionTime} } public var description: String { get { return attributes.description } } public var version: Int { get { return attributes.version } } public var globalUnitId: Int? { get { return attributes.globalUnitId } } public var customUnitId: Int? { get { return attributes.customUnitId } } public var authorId: Int? { get { return attributes.authorId } } public var active: Bool { get { return attributes.active } } public var entries: [Entry] { get { return attributes.entries } } public static func create ( in entity: Entity, at transactionTime: Date, description: String, denominatedIn denomination: Denomination, composedOf entries: [Entry], then callback: @escaping (_: Error?, _: Transaction?) -> Void ) { do { let arguments = try CreateArguments( transactionTime: transactionTime, description: description, denomination: denomination, entries: entries ) let _ = executeCreate(entity, arguments, callback) } catch { callback(error, nil) return } return } public static func create ( in entity: Entity, at transactionTime: Date, description: String, denominatedIn denomination: Denomination, composedOf entries: [Entry], then callback: @escaping (Result<Transaction, Error>) -> Void ) { Transaction.create( in: entity, at: transactionTime, description: description, denominatedIn: denomination, composedOf: entries ) { (error, transaction) in guard let transaction = transaction else { callback(.failure(error ?? AmatinoError(.inconsistentState))) return } callback(.success(transaction)) return } } public static func createMany( in entity: Entity, arguments: [Transaction.CreateArguments], then callback: @escaping (_: Error?, _: [Transaction]?) -> Void ) { do { guard arguments.count <= maxArguments else { throw ConstraintError(.tooManyArguments) } let urlParameters = UrlParameters(singleEntity: entity) let requestData = try RequestData(arrayData: arguments) let _ = try AmatinoRequest( path: path, data: requestData, session: entity.session, urlParameters: urlParameters, method: .POST, callback: { (error, data) in let _ = asyncInitMany( entity, callback, error, data ) return }) } catch { callback(error, nil) return } } private static func executeCreate( _ entity: Entity, _ arguments: Transaction.CreateArguments, _ callback: @escaping (_: Error?, _: Transaction?) -> Void ) { do { let requestData = try RequestData(data: arguments) let _ = try AmatinoRequest( path: Transaction.path, data: requestData, session: entity.session, urlParameters: UrlParameters(singleEntity: entity), method: .POST, callback: { (error, data) in let _ = asyncInit( entity, callback, error, data ) return }) } catch { callback(error, nil) return } } public static func retrieve( from entity: Entity, withId transactionId: Int, denominatedIn denomination: Denomination? = nil, atVersion version: Int? = nil, then callback: @escaping (_: Error?, _: Transaction?) -> Void ) { do { let arguments = Transaction.RetrieveArguments( transactionId: transactionId, denomination: denomination, version: version ) let urlParameters = UrlParameters(singleEntity: entity) let requestData = try RequestData(data: arguments) let _ = try AmatinoRequest( path: path, data: requestData, session: entity.session, urlParameters: urlParameters, method: .GET, callback: { (error, data) in let _ = asyncInit( entity, callback, error, data ) return }) } catch { callback(error, nil) } } public static func retrieve( from entity: Entity, withId transactionId: Int, denominatedIn denomination: Denomination? = nil, atVersion version: Int? = nil, then callback: @escaping (Result<Transaction, Error>) -> Void ) { Transaction.retrieve( from: entity, withId: transactionId, denominatedIn: denomination, atVersion: version ) { (error, transaction) in guard let transaction = transaction else { callback(.failure(error ?? AmatinoError(.inconsistentState))) return } callback(.success(transaction)) } return } public func update( transactionTime: Date? = nil, description: String? = nil, denomination: Denomination? = nil, entries: [Entry]? = nil, then callback: @escaping(_: Error?, _: Transaction?) -> Void ) { do { let globalUnitId: Int? let customUnitId: Int? let updateDescription: String let updateEntries: [Entry] let updateTime: Date if let transactionTime = transactionTime { updateTime = transactionTime } else { updateTime = self.transactionTime } if denomination == nil { globalUnitId = self.globalUnitId customUnitId = self.customUnitId } else if let globalUnit = denomination as? GlobalUnit { globalUnitId = globalUnit.id customUnitId = nil } else if let customUnit = denomination as? CustomUnit { globalUnitId = nil customUnitId = customUnit.id } else { fatalError("unknown denomination type") } if let entries = entries { updateEntries = entries } else { updateEntries = self.entries } if let description = description { updateDescription = description } else { updateDescription = self.description } let arguments = try UpdateArguments( transaction: self, transactionTime: updateTime, description: updateDescription, customUnitId: customUnitId, globalUnitId: globalUnitId, entries: updateEntries ) let _ = executeUpdate(arguments: arguments, callback: callback) } catch { callback(error, nil) } return } public func update( transactionTime: Date? = nil, description: String? = nil, denomination: Denomination? = nil, entries: [Entry]? = nil, then callback: @escaping (Result<Transaction, Error>) -> Void ) { self.update( transactionTime: transactionTime, description: description, denomination: denomination, entries: entries) { (error, transaction) in guard let transaction = transaction else { callback(.failure( error ?? AmatinoError(.inconsistentState)) ) return } callback(.success(transaction)) return } } private func executeUpdate( arguments: UpdateArguments, callback: @escaping(_: Error?, _: Transaction?) -> Void ) { do { let _ = try AmatinoRequest( path: Transaction.path, data: try RequestData(data: arguments), session: session, urlParameters: UrlParameters(singleEntity: entity), method: .PUT, callback: { (error, data) in let _ = Transaction.asyncInit( self.entity, callback, error, data ) return }) } catch { callback(error, nil) } return } public func delete( then callback: @escaping(_: Error?, _: Transaction?) -> Void ) { do { let target = UrlTarget(integerValue: id, key: Transaction.urlKey) let urlParameters = UrlParameters(entity: entity, targets: [target]) let _ = try AmatinoRequest( path: Transaction.path, data: nil, session: session, urlParameters: urlParameters, method: .DELETE, callback: { (error, data) in let _ = Transaction.asyncInit( self.entity, callback, error, data ) }) } catch { callback(error, nil) } return } public func delete ( then callback: @escaping(Result<Transaction, Error>) -> Void ) { self.delete { (error, transaction) in guard let transaction = transaction else { callback(.failure(error ?? AmatinoError(.inconsistentState))) return } callback(.success(transaction)) return } } internal struct Attributes: Decodable { let id: Int let transactionTime: Date let versionTime: Date let description: String let version: Int let globalUnitId: Int? let customUnitId: Int? let authorId: Int let active: Bool let entries: [Entry] internal init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: JSONObjectKeys.self) id = try container.decode(Int.self, forKey: .id) let rawTransactionTime = try container.decode( String.self, forKey: .transactionTime ) let formatter = DateFormatter() formatter.dateFormat = RequestData.dateStringFormat guard let tTime: Date = formatter.date(from: rawTransactionTime) else { throw AmatinoError(.badResponse) } transactionTime = tTime let rawVersionTime = try container.decode( String.self, forKey: .versionTime ) guard let vTime: Date = formatter.date(from: rawVersionTime) else { throw AmatinoError(.badResponse) } versionTime = vTime description = try container.decode(String.self, forKey: .description) version = try container.decode(Int.self, forKey: .version) globalUnitId = try container.decode(Int?.self, forKey: .globalUnitId) customUnitId = try container.decode(Int?.self, forKey: .customUnitId) authorId = try container.decode(Int.self, forKey: .authorId) active = try container.decode(Bool.self, forKey: .active) entries = try container.decode([Entry].self, forKey: .entries) return } enum JSONObjectKeys: String, CodingKey { case id = "transaction_id" case transactionTime = "transaction_time" case description case versionTime = "version_time" case version case globalUnitId = "global_unit_denomination" case customUnitId = "custom_unit_denomination" case authorId = "author" case active case entries } } internal struct UpdateArguments: Encodable { private let id: Int private let transactionTime: Date? private let description: Description private let globalUnitId: Int? private let customUnitId: Int? private let entries: Array<Entry>? init ( transaction: Transaction, transactionTime: Date, description: String, denomination: Denomination, entries: Array<Entry> ) throws { self.id = transaction.id self.description = try Description(description) self.transactionTime = transactionTime let globalUnitId: Int? let customUnitId: Int? if let globalUnit = denomination as? GlobalUnit { globalUnitId = globalUnit.id customUnitId = nil } else if let customUnit = denomination as? CustomUnit { globalUnitId = nil customUnitId = customUnit.id } else { fatalError("unknown denomination type") } self.globalUnitId = globalUnitId self.customUnitId = customUnitId self.entries = entries return } internal init ( transaction: Transaction, transactionTime: Date, description: String, customUnitId: Int?, globalUnitId: Int?, entries: Array<Entry> ) throws { self.id = transaction.id self.description = try Description(description) self.transactionTime = transactionTime self.globalUnitId = globalUnitId self.customUnitId = customUnitId self.entries = entries return } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: JSONObjectKeys.self) try container.encode(id, forKey: .id) try container.encode(entries, forKey: .entries) try container.encode( String(describing: description), forKey: .description ) try container.encode(globalUnitId, forKey: .globalUnit) try container.encode(customUnitId, forKey: .customUnit) try container.encode(transactionTime, forKey: .transactionTime) return } enum JSONObjectKeys: String, CodingKey { case id = "transaction_id" case transactionTime = "transaction_time" case description case globalUnit = "global_unit_denomination" case customUnit = "custom_unit_denomination" case entries } } public struct CreateArguments: Encodable { private let transactionTime: Date private let description: Description private let globalUnitId: Int? private let customUnitId: Int? private let entries: Array<Entry> init ( transactionTime: Date, description: String, denomination: Denomination, entries: Array<Entry> ) throws { let globalUnitId: Int? let customUnitId: Int? if let globalUnit = denomination as? GlobalUnit { globalUnitId = globalUnit.id customUnitId = nil } else if let customUnit = denomination as? CustomUnit { globalUnitId = nil customUnitId = customUnit.id } else { fatalError("unknown denomination type") } self.description = try Description(description) self.transactionTime = transactionTime self.globalUnitId = globalUnitId self.customUnitId = customUnitId self.entries = entries let _ = try checkEntries(entries: entries) return } init ( transactionTime: Date, description: String, customUnitId: Int, entries: Array<Entry> ) throws { self.description = try Description(description) self.transactionTime = transactionTime self.globalUnitId = nil self.customUnitId = customUnitId self.entries = entries let _ = try checkEntries(entries: entries) return } init ( transactionTime: Date, description: String, globalUnitId: Int, entries: Array<Entry> ) throws { self.description = try Description(description) self.transactionTime = transactionTime self.globalUnitId = globalUnitId self.customUnitId = nil self.entries = entries let _ = try checkEntries(entries: entries) return } private func checkEntries(entries: Array<Entry>) throws -> Void { var runningBalance: Decimal = 0 for entry in entries { switch entry.side { case .debit: runningBalance += entry.amount case .credit: runningBalance -= entry.amount } } guard runningBalance == 0 else { throw ConstraintError(.debitCreditBalance) } return } enum JSONObjectKeys: String, CodingKey { case transactionTime = "transaction_time" case description case globalUnit = "global_unit_denomination" case customUnit = "custom_unit_denomination" case entries } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: JSONObjectKeys.self) try container.encode(entries, forKey: .entries) try container.encode( String(describing: description), forKey: .description ) try container.encode(globalUnitId, forKey: .globalUnit) try container.encode(customUnitId, forKey: .customUnit) try container.encode(transactionTime, forKey: .transactionTime) return } } public struct RetrieveArguments: Encodable { let id: Int let customUnitId: Int? let globalUnitId: Int? let version: Int? public init( transactionId: Int, denomination: Denomination? = nil, version: Int? = nil ) { id = transactionId self.version = version if denomination == nil { self.globalUnitId = nil self.customUnitId = nil return } let customUnitId: Int? let globalUnitId: Int? if let customUnit = denomination as? CustomUnit { globalUnitId = nil customUnitId = customUnit.id } else if let globalUnit = denomination as? GlobalUnit { customUnitId = nil globalUnitId = globalUnit.id } else { fatalError("Unknown denominating type") } self.globalUnitId = globalUnitId self.customUnitId = customUnitId return } public init( transactionId: Int, customUnitId: Int, version: Int? = nil ) { self.version = version id = transactionId globalUnitId = nil self.customUnitId = customUnitId return } public init( transactionId: Int, globalUnitId: Int, version: Int? = nil ) { self.version = version id = transactionId self.globalUnitId = globalUnitId customUnitId = nil return } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: JSONObjectKeys.self) try container.encode(id, forKey: .id) try container.encode(customUnitId, forKey: .customUnitId) try container.encode(globalUnitId, forKey: .globalUnitId) try container.encode(version, forKey: .version) return } enum JSONObjectKeys: String, CodingKey { case id = "transaction_id" case customUnitId = "custom_unit_denomination" case globalUnitId = "global_unit_denomination" case version } } internal struct Description: CustomStringConvertible { private let rawStringValue: String private var maxLengthErrorMessage: String { let errorString = """ Transaction description is limited to \(maxDescriptionLength) characters """ return errorString } internal var description: String { get { return rawStringValue } } init (_ description: String?) throws { let storedDescription: String if (description == nil) { storedDescription = "" } else { storedDescription = description! } rawStringValue = storedDescription guard storedDescription.count < maxDescriptionLength else { throw ConstraintError.init( .descriptionLength, maxLengthErrorMessage ) } return } } public class ConstraintError: AmatinoError { public let constraint: Constraint public let constraintDescription: String internal init(_ cause: Constraint, _ description: String? = nil) { constraint = cause constraintDescription = description ?? cause.rawValue super.init(.constraintViolated) return } public enum Constraint: String { case descriptionLength = "Maximum description length exceeded" case debitCreditBalance = "Debits & credits must balance" case tooManyArguments = "Maximum number of arguments exceeded" } } }