hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
2020d5ea79d5102677c1510223d223f80dbd0b90
2,990
// // RulesViewController.swift // CriticalMaps // // Created by Leonard Thomas on 12/17/18. // import UIKit enum Rule: String, CaseIterable { case cork case contraflow case gently case brake case green case stayLoose case haveFun var title: String { NSLocalizedString("rules.title.\(rawValue)", comment: "") } var text: String { NSLocalizedString("rules.text.\(rawValue)", comment: "") } var artwork: UIImage? { UIImage(named: rawValue.prefix(1).uppercased() + rawValue.dropFirst()) } } class RulesViewController: UITableViewController { private let rules = Rule.allCases private let themeController: ThemeController init(themeController: ThemeController) { self.themeController = themeController super.init(nibName: nil, bundle: nil) } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = UITableView.automaticDimension updateThemeIfNeeded() configureNotifications() configureNavigationBar() registerCell() // remove empty cells tableView.tableFooterView = UIView() } private func configureNotifications() { NotificationCenter.default.addObserver( self, selector: #selector(updateThemeIfNeeded), name: .themeDidChange, object: nil ) } @objc private func updateThemeIfNeeded() { if #available(iOS 13.0, *) { if themeController.currentTheme == .dark { overrideUserInterfaceStyle = .dark } else { overrideUserInterfaceStyle = .light } } } private func configureNavigationBar() { title = L10n.rulesTitle if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = true } } private func registerCell() { tableView.register(cellType: RuleTableViewCell.self) } // MARK: UITableViewDataSource override func tableView(_: UITableView, estimatedHeightForRowAt _: IndexPath) -> CGFloat { 60 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { rules.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(ofType: RuleTableViewCell.self) cell.label?.text = rules[indexPath.row].title return cell } // MARK: UITableViewDataDelegate override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) { let rule = rules[indexPath.row] let detailViewController = RulesDetailViewController(rule: rule) navigationController?.pushViewController(detailViewController, animated: true) } }
26.460177
109
0.642809
222a880ff27ad5db509152933c2aac2610b083e3
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct d{ class a{class n}}if{ func b(A class A<var A
22.3
87
0.753363
332fb573fd933b9fbc0d357f565c21fa746f692c
3,522
import Foundation import XCTest import SwiftSyntax @testable import MinSwiftKit class Practice5: ParserTestCase { // 5-1 func testFunctionCalling() { load("doSomething()") // identifier, leftParen, rightParen let node = parser.parseIdentifierExpression() XCTAssertTrue(node is CallExpressionNode) let callExpressionNode = node as! CallExpressionNode XCTAssertEqual(callExpressionNode.callee, "doSomething") XCTAssertTrue(callExpressionNode.arguments.isEmpty) XCTAssertEqual(parser.currentToken.tokenKind, .eof) } // 5-2 func testFunctionCallingWithLabel() { load("doSomething(a: 10 + 20)") // identifier, leftParen, identifier, colon, <some expression> , rightParen let node = parser.parseIdentifierExpression() XCTAssertTrue(node is CallExpressionNode) let callExpressionNode = node as! CallExpressionNode XCTAssertEqual(callExpressionNode.callee, "doSomething") XCTAssertEqual(callExpressionNode.arguments.count, 1) let firstArgument = callExpressionNode.arguments.first!.value as! BinaryExpressionNode XCTAssertEqual(firstArgument.operator, .addition) XCTAssertEqual(parser.currentToken.tokenKind, .eof) } // 5-3 func testFunctionCallingWithLabels() { load("doSomething(a: 10 + 20, b: x)") // identifier, leftParen, // identifier, colon, <some expression>, comma // identifier, colon, <some expression> ... // rightParen let node = parser.parseIdentifierExpression() XCTAssertTrue(node is CallExpressionNode) let callExpressionNode = node as! CallExpressionNode XCTAssertEqual(callExpressionNode.callee, "doSomething") XCTAssertEqual(callExpressionNode.arguments.count, 2) let firstArgument = callExpressionNode.arguments.first!.value as! BinaryExpressionNode XCTAssertEqual(firstArgument.operator, .addition) let secondArgument = callExpressionNode.arguments[1].value as! VariableNode XCTAssertEqual(secondArgument.identifier, "x") XCTAssertEqual(parser.currentToken.tokenKind, .eof) } // If you have a rest time, try them. func _testFunctionCallingWithLiteralArguments() { load("doSomething(10)") // identifier, leftParen, <some expression> , rightParen let node = parser.parseIdentifierExpression() XCTAssertTrue(node is CallExpressionNode) let callExpressionNode = node as! CallExpressionNode XCTAssertEqual(callExpressionNode.callee, "doSomething") XCTAssertEqual(callExpressionNode.arguments.count, 1) let firstArgument = callExpressionNode.arguments.first!.value as! NumberNode XCTAssertEqual(firstArgument.value, 10) XCTAssertEqual(parser.currentToken.tokenKind, .eof) } func _testFunctionCallingWithVariableArguments() { load("doSomething(a)") // identifier, leftParen, <some expression> , rightParen let node = parser.parseIdentifierExpression() XCTAssertTrue(node is CallExpressionNode) let callExpressionNode = node as! CallExpressionNode XCTAssertEqual(callExpressionNode.callee, "doSomething") XCTAssertEqual(callExpressionNode.arguments.count, 1) let firstArgument = callExpressionNode.arguments.first!.value as! VariableNode XCTAssertEqual(firstArgument.identifier, "a") XCTAssertEqual(parser.currentToken.tokenKind, .eof) } }
39.133333
115
0.71096
fc85081c163fba2a18cc3f3f9b1a79ea5e0668af
5,705
public indirect enum SVGFilterNode: Equatable { public typealias ColorMatrix = Matrix.D4x5<SVG.Float> public enum ColorMatrixType: Equatable { case matrix(ColorMatrix) case saturate(SVG.Float) case hueRotate(SVG.Float) case luminanceToAlpha } case flood(color: SVG.Color, opacity: SVG.Float) case colorMatrix(in: SVGFilterNode, type: ColorMatrixType) case offset(in: SVGFilterNode, dx: SVG.Float, dy: SVG.Float) case gaussianBlur(in: SVGFilterNode, stddevX: SVG.Float, stddevY: SVG.Float) case blend(in1: SVGFilterNode, in2: SVGFilterNode, mode: SVG.BlendMode) case sourceGraphic case sourceAlpha case backgroundImage case backgroundAlpha case fillPaint case strokePaint } private enum FilterGraphCreationError: Swift.Error { case inputNotDefined case colorMatrixHasInvalidValuesCount(Int) } extension SVGFilterNode { public init(raw: SVG.Filter) throws { let result = try raw.children.reduce( into: FilterPrimitiveProcessAccumulator.initial, processFilterPrimitive(acc:next:) ) self = result.prev } } private struct FilterPrimitiveProcessAccumulator { var prev: SVGFilterNode var preceding: [String: SVGFilterNode] static let initial = FilterPrimitiveProcessAccumulator(prev: .sourceGraphic, preceding: [:]) } private func processFilterPrimitive( acc: inout FilterPrimitiveProcessAccumulator, next: SVG.FilterPrimitiveContent ) throws { let nodeFromInput = node(acc: acc) let resultNode: SVGFilterNode switch next { case let .feBlend(d): let in1 = try d.in |> nodeFromInput let in2 = try d.in2 |> nodeFromInput let mode = d.mode ?? .normal resultNode = .blend(in1: in1, in2: in2, mode: mode) case let .feColorMatrix(d): let input = try d.in |> nodeFromInput let type: SVGFilterNode.ColorMatrixType switch d.type ?? .matrix { case .matrix: let matrix = try d.values.map(colorMatrixFromValues(values:)) ?? Matrix.scalar4x5(λ: 1, zero: 0) type = .matrix(matrix) case .saturate: type = .saturate(try d.values.map(singleFromValues) ?? 1) case .hueRotate: type = .hueRotate(try d.values.map(singleFromValues) ?? 1) case .luminanceToAlpha: type = .luminanceToAlpha } resultNode = .colorMatrix(in: input, type: type) case let .feFlood(d): resultNode = .flood(color: d.floodColor ?? .black(), opacity: d.floodOpacity ?? 1) case let .feGaussianBlur(d): let stddevX = d.stdDeviation?._1 ?? 0 let stddevY = d.stdDeviation?._2 ?? stddevX resultNode = .gaussianBlur( in: try d.in |> nodeFromInput, stddevX: stddevX, stddevY: stddevY ) case let .feOffset(d): resultNode = .offset( in: try d.in |> nodeFromInput, dx: d.dx ?? 0, dy: d.dy ?? 0 ) } acc.prev = resultNode if let result = next.common.result { acc.preceding[result] = resultNode } } private func singleFromValues(values: [SVG.Float]) throws -> SVG.Float { try check(values.count == 1, .colorMatrixHasInvalidValuesCount(values.count)) return values[0] } private func colorMatrixFromValues( values: [SVG.Float] ) throws -> SVGFilterNode.ColorMatrix { try check(values.count == 20, .colorMatrixHasInvalidValuesCount(values.count)) let a = values.splitBy(subSize: 5).map(Array.init) return .init( r1: .init(c1: a[0][0], c2: a[0][1], c3: a[0][2], c4: a[0][3], c5: a[0][4]), r2: .init(c1: a[1][0], c2: a[1][1], c3: a[1][2], c4: a[1][3], c5: a[1][4]), r3: .init(c1: a[2][0], c2: a[2][1], c3: a[2][2], c4: a[2][3], c5: a[2][4]), r4: .init(c1: a[3][0], c2: a[3][1], c3: a[3][2], c4: a[3][3], c5: a[3][4]) ) } /* 15.7.2 Identifies input for the given filter primitive. The value can be either one of six keywords or can be a string which matches a previous ‘result’ attribute value within the same ‘filter’ element. If no value is provided and this is the first filter primitive, then this filter primitive will use SourceGraphic as its input. If no value is provided and this is a subsequent filter primitive, then this filter primitive will use the result from the previ- ous filter primitive as its input. If the value for ‘result’ appears multiple times within a given ‘filter’ element, then a reference to that result will use the closest preceding filter primitive with the given value for attribute ‘result’. Forward references to results are an error. */ private func node( acc: FilterPrimitiveProcessAccumulator ) -> (SVG.FilterPrimitiveIn?) throws -> SVGFilterNode { { switch $0 { case let .predefined(predefined): return node(from: predefined) case let .previous(name): return try acc.preceding[name] !! FilterGraphCreationError.inputNotDefined case .none: return acc.prev } } } private func node( from predefinedInput: SVG.FilterPrimitiveIn.Predefined ) -> SVGFilterNode { switch predefinedInput { case .backgroundalpha: return .backgroundAlpha case .sourcegraphic: return .sourceGraphic case .sourcealpha: return .sourceAlpha case .backgroundimage: return .backgroundImage case .fillpaint: return .fillPaint case .strokepaint: return .strokePaint } } private func check( _ condition: Bool, _ error: FilterGraphCreationError ) throws { if !condition { throw error } } extension SVG.FilterPrimitiveContent { public var common: SVG.FilterPrimitiveCommonAttributes { switch self { case let .feBlend(d): return d.common case let .feColorMatrix(d): return d.common case let .feFlood(d): return d.common case let .feGaussianBlur(d): return d.common case let .feOffset(d): return d.common } } }
30.345745
80
0.693252
1c802d2e8a330268dffe1b96d298f73d18d23254
3,469
// // ImageProcesser.swift // ImageProcess // // Created by 郑红 on 2020/7/2. // Copyright © 2020 com.zhenghong. All rights reserved. // import UIKit import Accelerate enum ImageResult { case success case error(String) } let ImageMakeBufferError = ImageResult.error("fail create buffer") protocol ImageOperator: CustomDebugStringConvertible { func operateImage(buffer: inout vImage_Buffer, format: inout vImage_CGImageFormat) -> ImageResult var provider: Bool {get} } extension ImageOperator { var provider: Bool { return false } } struct ChainOperator: ImageOperator { var debugDescription: String { return "ChainOperator" } var provider: Bool { let arr = operators.filter { $0.provider } return !arr.isEmpty } var operators: [ImageOperator] func operateImage(buffer: inout vImage_Buffer, format: inout vImage_CGImageFormat) -> ImageResult { guard !operators.isEmpty else { return .error("empty operator") } var resultBuffer = buffer var resultFormat = format for op in operators { let err = op.operateImage(buffer: &resultBuffer, format: &resultFormat) if case ImageResult.error(_) = err { return err } } buffer = resultBuffer format = resultFormat return .success } } let imageChangeNotification = Notification.Name.init("processer-image") struct BufferBox { var buffer: vImage_Buffer var format: vImage_CGImageFormat var image: CGImage? { let img = try? buffer.createCGImage(format: format) return img } // func copy() -> BufferBox? { // guard let buff = try? vImage_Buffer(width: Int(buffer.width), height: Int(buffer.height), bitsPerPixel: format.bitsPerPixel) else { return nil } // var form = vImage_CGImageFormat(bitsPerComponent: Int(format.bitsPerComponent), bitsPerPixel: Int(format.bitsPerPixel), colorSpace: format.colorSpace as! CGColorSpace, bitmapInfo: format.bitmapInfo) // // return BufferBox(buffer: buff, format: form) // } } class ImageProcesser { var image: CGImage? { didSet { NotificationCenter.default.post(name: imageChangeNotification, object: nil) } } var sourceBuffer: vImage_Buffer? var sourceFormat: vImage_CGImageFormat? deinit { sourceBuffer?.free() } func performOperator(imageOperator: ImageOperator) { // not good if imageOperator.provider { if sourceFormat == nil { sourceFormat = vImage_CGImageFormat(bitsPerComponent: 8, bitsPerPixel: 32, colorSpace: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.first.rawValue)) } if sourceBuffer == nil { sourceBuffer = try? vImage_Buffer(width: 10, height: 10, bitsPerPixel: 32) } } guard var buffer = sourceBuffer, var format = sourceFormat else { return } let err = imageOperator.operateImage(buffer: &buffer, format: &format) guard case ImageResult.success = err else { return } if let img = try? buffer.createCGImage(format: format) { image = img sourceFormat = format sourceBuffer = buffer } } }
27.531746
208
0.62727
29835551ae6ef061e79a0bcd3c9cfe6d6327cc8e
3,450
// // FloatingUIAlertControllerTests.swift // FrameworksTestingShell // // Created by Robert Huston on 7/17/16. // Copyright © 2016 Pinpoint Dynamics. All rights reserved. // // // NOTE: // // The FloatingUIAlertController actually resides in the PDLUIToolBox frameworks // project. However, we test FloatingUIAlertController.presentStandardAlert() // function here because the testing needs to actually use a properly set up // UIApplication and window hierarchy. // import XCTest @testable import PDLUIToolBox class FloatingUIAlertControllerTests: XCTestCase { func test_presentStandardAlert_AddsNewWindowToWindowHierarcy() { let countBefore = UIApplication.shared.windows.count FloatingUIAlertController.presentStandardAlert(title: "Alert", message: "Hi, there!") let countAfter = UIApplication.shared.windows.count XCTAssert(countAfter > countBefore) } func test_presentStandardAlert_NewWindowContainsPresentedFloatingUIAlertController() { let countBefore = UIApplication.shared.windows.count FloatingUIAlertController.presentStandardAlert(title: "Alert", message: "Hi, there!") let countAfter = UIApplication.shared.windows.count if countAfter > countBefore { let frontWindow = UIApplication.shared.windows.last let presentedViewController = frontWindow?.rootViewController?.presentedViewController XCTAssert(presentedViewController is FloatingUIAlertController) } } func test_presentStandardAlert_PresentedFloatingUIAlertControllerContainsReferenceToWindow() { let countBefore = UIApplication.shared.windows.count FloatingUIAlertController.presentStandardAlert(title: "Alert", message: "Hi, there!") let countAfter = UIApplication.shared.windows.count if countAfter > countBefore { let frontWindow = UIApplication.shared.windows.last let presentedViewController = frontWindow?.rootViewController?.presentedViewController if presentedViewController is FloatingUIAlertController { let floatingAlertController = presentedViewController as! FloatingUIAlertController XCTAssertEqual(floatingAlertController.alertWindow, frontWindow) } } } func test_presentStandardAlert_PresentedFloatingUIAlertControllerIsProperlyFormed() { let countBefore = UIApplication.shared.windows.count FloatingUIAlertController.presentStandardAlert(title: "Alert", message: "Hi, there!") let countAfter = UIApplication.shared.windows.count if countAfter > countBefore { let frontWindow = UIApplication.shared.windows.last let presentedViewController = frontWindow?.rootViewController?.presentedViewController if presentedViewController is FloatingUIAlertController { let floatingAlertController = presentedViewController as! FloatingUIAlertController XCTAssertEqual(floatingAlertController.title, "Alert") XCTAssertEqual(floatingAlertController.message, "Hi, there!") XCTAssertEqual(floatingAlertController.actions.count, 1) if floatingAlertController.actions.count == 1 { let action = floatingAlertController.actions[0] XCTAssertEqual(action.title, "OK") } } } } }
41.566265
99
0.718261
238168893933b73c53e152df92c0ccfa5c79961e
3,781
// // CollectionViewController.swift // FlixApp // // Created by Nancy Yao on 6/16/16. // Copyright © 2016 Nancy Yao. All rights reserved. // import UIKit import MBProgressHUD class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! var movies: [NSDictionary]? override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self let apiKey = "fe0bc5f627da8817426f458762d96d06" let url = NSURL(string: "http://api.themoviedb.org/3/movie/upcoming?api_key=\(apiKey)") let request = NSURLRequest( URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue() ) MBProgressHUD.showHUDAddedTo(self.view, animated: true) let task: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in MBProgressHUD.hideHUDForView(self.view, animated: true) if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { print("response: \(responseDictionary)") self.movies = responseDictionary["results"] as? [NSDictionary] self.collectionView.reloadData() } } }) task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let movies = movies { return movies.count } else {return 0} } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCollectionCell", forIndexPath: indexPath) as! MovieCollectionCell if let movie = movies?[indexPath.item] { if let posterPath = movie["poster_path"] as? String { let baseURL = "http://image.tmdb.org/t/p/w500" let imageURL = NSURL(string: baseURL + posterPath) cell.collectionImageView.setImageWithURL(imageURL!)} } return cell; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if let destinationViewController = segue.destinationViewController as? DetailViewController { let indexPath = collectionView.indexPathForCell(sender as! UICollectionViewCell) let movie = movies![indexPath!.item] if let posterPath = movie["poster_path"] as? String { destinationViewController.photoUrl = posterPath let title = movie["title"] as! String destinationViewController.detailTitle = title } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */
40.223404
144
0.650093
d678ff8e724cf940127f7dda2ba8514ad0459563
8,375
// RUN: %target-typecheck-verify-swift // REQUIRES: objc_interop import Foundation struct S0 { init!(int: Int) { } init! (uint: UInt) { } init !(float: Float) { } init?(string: String) { } init ?(double: Double) { } init ? (char: Character) { } } struct S1<T> { init?(value: T) { } } class DuplicateDecls { init!() { } // expected-note{{'init()' previously declared here}} init?() { } // expected-error{{invalid redeclaration of 'init()'}} init!(string: String) { } // expected-note{{'init(string:)' previously declared here}} init(string: String) { } // expected-error{{invalid redeclaration of 'init(string:)'}} init(double: Double) { } // expected-note{{'init(double:)' previously declared here}} init?(double: Double) { } // expected-error{{invalid redeclaration of 'init(double:)'}} } // Construct via a failable initializer. func testConstruction(_ i: Int, s: String) { let s0Opt = S0(string: s) assert(s0Opt != nil) var _: S0 = s0Opt // expected-error{{value of optional type 'S0?' must be unwrapped}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let s0IUO = S0(int: i) assert(s0IUO != nil) _ = s0IUO } // ---------------------------------------------------------------------------- // Superclass initializer chaining // ---------------------------------------------------------------------------- class Super { init?(fail: String) { } init!(failIUO: String) { } init() { } // expected-note 2{{non-failable initializer 'init()' overridden here}} } class Sub : Super { override init() { super.init() } // okay, never fails init(nonfail: Int) { // expected-note{{propagate the failure with 'init?'}}{{7-7=?}} super.init(fail: "boom") // expected-error{{a non-failable initializer cannot chain to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } convenience init(forceNonfail: Int) { self.init(nonfail: forceNonfail)! // expected-error{{cannot force unwrap value of non-optional type 'Sub'}} {{37-38=}} } init(nonfail2: Int) { // okay, traps on nil super.init(failIUO: "boom") } init(nonfail3: Int) { super.init(fail: "boom")! } override init?(fail: String) { super.init(fail: fail) // okay, propagates ? } init?(fail2: String) { // okay, propagates ! as ? super.init(failIUO: fail2) } init?(fail3: String) { // okay, can introduce its own failure super.init() } override init!(failIUO: String) { super.init(failIUO: failIUO) // okay, propagates ! } init!(failIUO2: String) { // okay, propagates ? as ! super.init(fail: failIUO2) } init!(failIUO3: String) { // okay, can introduce its own failure super.init() } } // ---------------------------------------------------------------------------- // Initializer delegation // ---------------------------------------------------------------------------- extension Super { convenience init(convenienceNonFailNonFail: String) { // okay, non-failable self.init() } convenience init(convenienceNonFailFail: String) { // expected-note{{propagate the failure with 'init?'}}{{19-19=?}} self.init(fail: convenienceNonFailFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{44-44=!}} } convenience init(convenienceNonFailFailForce: String) { self.init(fail: convenienceNonFailFailForce)! } convenience init(convenienceNonFailFailIUO: String) { // okay, trap on failure self.init(failIUO: convenienceNonFailFailIUO) } convenience init?(convenienceFailNonFail: String) { self.init() // okay, can introduce its own failure } convenience init?(convenienceFailFail: String) { self.init(fail: convenienceFailFail) // okay, propagates ? } convenience init?(convenienceFailFailIUO: String) { // okay, propagates ! as ? self.init(failIUO: convenienceFailFailIUO) } convenience init!(convenienceFailIUONonFail: String) { self.init() // okay, can introduce its own failure } convenience init!(convenienceFailIUOFail: String) { self.init(fail: convenienceFailIUOFail) // okay, propagates ? as ! } convenience init!(convenienceFailIUOFailIUO: String) { // okay, propagates ! self.init(failIUO: convenienceFailIUOFailIUO) } } struct SomeStruct { init(nonFail: Int) { // expected-note{{propagate the failure with 'init?'}}{{8-8=?}} self.init(fail: nonFail) // expected-error{{a non-failable initializer cannot delegate to failable initializer 'init(fail:)' written with 'init?'}} // expected-note@-1{{force potentially-failing result with '!'}}{{29-29=!}} } init(nonFail2: Int) { self.init(fail: nonFail2)! } init?(fail: Int) {} } // ---------------------------------------------------------------------------- // Initializer overriding // ---------------------------------------------------------------------------- class Sub2 : Super { override init!(fail: String) { // okay to change ? to ! super.init(fail: fail) } override init?(failIUO: String) { // okay to change ! to ? super.init(failIUO: failIUO) } override init() { super.init() } // no change } // Dropping optionality class Sub3 : Super { override init(fail: String) { // okay, strengthened result type super.init() } override init(failIUO: String) { // okay, strengthened result type super.init() } override init() { } // no change } // Adding optionality class Sub4 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init?() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } class Sub5 : Super { override init?(fail: String) { super.init() } override init!(failIUO: String) { super.init() } override init!() { // expected-error{{failable initializer 'init()' cannot override a non-failable initializer}} super.init() } } // ---------------------------------------------------------------------------- // Initializer conformances // ---------------------------------------------------------------------------- protocol P1 { init(string: String) } @objc protocol P1_objc { init(string: String) } protocol P2 { init?(fail: String) } protocol P3 { init!(failIUO: String) } class C1a : P1 { required init?(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} } class C1b : P1 { required init!(string: String) { } // okay } class C1b_objc : P1_objc { @objc required init!(string: String) { } // expected-error{{non-failable initializer requirement 'init(string:)' in Objective-C protocol cannot be satisfied by a failable initializer ('init!')}} } class C1c { required init?(string: String) { } // expected-note {{'init(string:)' declared here}} } extension C1c: P1 {} // expected-error{{non-failable initializer requirement 'init(string:)' cannot be satisfied by a failable initializer ('init?')}} class C2a : P2 { required init(fail: String) { } // okay to remove failability } class C2b : P2 { required init?(fail: String) { } // okay, ? matches } class C2c : P2 { required init!(fail: String) { } // okay to satisfy init? with init! } class C3a : P3 { required init(failIUO: String) { } // okay to remove failability } class C3b : P3 { required init?(failIUO: String) { } // okay to satisfy ! with ? } class C3c : P3 { required init!(failIUO: String) { } // okay, ! matches } // ---------------------------------------------------------------------------- // Initiating failure // ---------------------------------------------------------------------------- struct InitiateFailureS { init(string: String) { // expected-note{{use 'init?' to make the initializer 'init(string:)' failable}}{{7-7=?}} return (nil) // expected-error{{only a failable initializer can return 'nil'}} } init(int: Int) { return 0 // expected-error{{'nil' is the only return value permitted in an initializer}} } init?(double: Double) { return nil // ok } init!(char: Character) { return nil // ok } }
29.385965
196
0.600239
164f417db5223e54290accf7102355686c6893eb
1,660
// // Setup.swift // UberSDK // // Created by Manav Gabhawala on 25/07/15. // // import Foundation import Foundation import CoreLocation @testable import UberiOSSDK /* SET THESE VALUES AS NEEDED TO RUN TESTS. // MARK: Globals class Delegate : NSObject, UberManagerDelegate { var applicationName: String { get { return "APP NAME" } } var clientID : String { get { return "ID" } } var clientSecret: String { get { return "SECRET" } } var serverToken : String { get { return "SERVER TOKEN" } } var redirectURI : String { get { return "REDIRECT URI" } } var baseURL : UberBaseURL { get { return .SandboxAPI } } var scopes : [Int] { get { return [ UberScopes.Profile.rawValue, UberScopes.Request.rawValue, UberScopes.History.rawValue ] } } var surgeConfirmationRedirectURI : String { return redirectURI /* Change to custom if required */ } } // To test authentication and stuff. let user = "EMAIL ID OF UBER USER" let password = "PASSWORD OF UBER USER" // MARK: - Already setup globals let manager = UberManager(delegate: Delegate()) //MARK: - Locations let startLatitude = 37.7759792 let startLongitude = -122.41823 let startLocation = CLLocation(latitude: startLatitude, longitude: startLongitude) let endLatitude = 40.7439945 let endLongitude = -74.006194 let endLocation = CLLocation(latitude: endLatitude, longitude: endLongitude) let badLatitude = 0.0 let badLongitude = 0.0 let badLocation = CLLocation(latitude: badLatitude, longitude: badLongitude) let closeToStartLatitude = 37.7789792 let closeToStartLongitude = -122.31823 let closeToStartLocation = CLLocation(latitude: closeToStartLatitude, longitude: closeToStartLongitude) */
29.122807
128
0.746386
e931562807b1191424f78e26e23cb87f1893d293
1,284
// // AppDelegate.swift // music-mood // // Created by Eugene Oskin on 08.10.16. // Copyright © 2016 Eugene Oskin. All rights reserved. // import Cocoa import AppKit; @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var eventGenerator: EventGenerator! var sampler: Sampler! var statusItem: NSStatusItem! func applicationDidFinishLaunching(_ aNotification: Notification) { statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) updateFrequency(0) loadSampler() eventGenerator = EventGenerator( block: { frequency in self.sampler.change(frequency: frequency) self.updateFrequency(frequency) }, reset: { self.sampler.reset() self.updateFrequency(0) } ) eventGenerator.start() } func loadSampler() { sampler = Sampler(); } func updateFrequency(_ frequency: Double) { statusItem.button?.title = String(format: "M %.0f", frequency) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
24.692308
92
0.607477
08c4dfef8c5071cdab3a358eb76885d6823c08b9
1,351
// // AppDelegate.swift // Project6b // // Created by Hümeyra Şahin on 7.10.2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.513514
179
0.746114
5d9c98bd94a9e54c34eb01c7c66435a8fb194efb
2,177
// // AppDelegate.swift // TabBarInteraction // // Created by potato04 on 2019/3/27. // Copyright © 2019 potato04. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } 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:. } }
46.319149
285
0.756086
20125cc030ab977df8a5fc7b01031c51a41dcd07
286
/** * Publish * Copyright (c) John Behnke 2020 * MIT license, see LICENSE file for details */ import Plot import Publish import Foundation extension Theme where Site == BehnkeDotDev{ static var behnkeDotDev: Self { Theme(htmlFactory: BehnkeDotDevHTMLFactory()) } }
14.3
49
0.70979
ebbece0b45b624269acf96d511aaae3ab1f97a17
2,817
// Copyright 2017-present the Material Components for iOS 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 Foundation import MaterialComponents.MaterialBottomNavigation_ColorThemer import MaterialComponents.MaterialColorScheme class BottomNavigationTypicalUseSwiftExample: UIViewController { var colorScheme = MDCSemanticColorScheme() // Create a bottom navigation bar to add to a view. let bottomNavBar = MDCBottomNavigationBar() override func viewDidLoad() { super.viewDidLoad() bottomNavBar.sizeThatFitsIncludesSafeArea = false view.backgroundColor = colorScheme.backgroundColor view.addSubview(bottomNavBar) // Always show bottom navigation bar item titles. bottomNavBar.titleVisibility = .always // Cluster and center the bottom navigation bar items. bottomNavBar.alignment = .centered // Add items to the bottom navigation bar. let tabBarItem1 = UITabBarItem(title: "Home", image: UIImage(named: "Home"), tag: 0) let tabBarItem2 = UITabBarItem(title: "Messages", image: UIImage(named: "Email"), tag: 1) let tabBarItem3 = UITabBarItem(title: "Favorites", image: UIImage(named: "Favorite"), tag: 2) bottomNavBar.items = [ tabBarItem1, tabBarItem2, tabBarItem3 ] // Select a bottom navigation bar item. bottomNavBar.selectedItem = tabBarItem2; } func layoutBottomNavBar() { let size = bottomNavBar.sizeThatFits(view.bounds.size) var bottomNavBarFrame = CGRect(x: 0, y: view.bounds.height - size.height, width: size.width, height: size.height) if #available(iOS 11.0, *) { bottomNavBarFrame.size.height += view.safeAreaInsets.bottom bottomNavBarFrame.origin.y -= view.safeAreaInsets.bottom } bottomNavBar.frame = bottomNavBarFrame } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layoutBottomNavBar() } } // MARK: Catalog by convention extension BottomNavigationTypicalUseSwiftExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Bottom Navigation", "Bottom Navigation (Swift)"], "primaryDemo": false, "presentable": false, ] } }
34.777778
88
0.706425
33469727f3bf4e66c4e53785e7b768f5c167cf71
1,752
// // NSAppearance.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-09-09. // // --------------------------------------------------------------------------- // // © 2018 1024jp // // 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 // // https://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 AppKit.NSAppearance extension NSAppearance { var isDark: Bool { if self.name == .vibrantDark { return true } guard #available(macOS 10.14, *) else { return false } switch self.name { case .darkAqua, .accessibilityHighContrastDarkAqua, .accessibilityHighContrastVibrantDark: return true default: return false } } var isHighContrast: Bool { guard #available(macOS 10.14, *) else { return NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast } switch self.name { case .accessibilityHighContrastAqua, .accessibilityHighContrastDarkAqua, .accessibilityHighContrastVibrantLight, .accessibilityHighContrastVibrantDark: return true default: return false } } }
26.953846
80
0.593037
645be1c5f29946cd91d4f51af74ee3f7adcf7c83
3,928
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the ProxyServerAddEditController class, which controls a view used to create or edit a proxy server configuration. */ import UIKit import NetworkExtension /// A view controller object for a view that contains input fields used to define HTTP proxy server settings. class ProxyServerAddEditController: ConfigurationParametersViewController { // MARK: Properties /// A table view cell containing a text input field where the user enters the proxy server address. @IBOutlet weak var addressCell: TextFieldCell! /// A table view cell containing a text input field where the user enters the proxy server port number. @IBOutlet weak var portCell: TextFieldCell! /// A table view cell containing a text input field where the user enters the username portion of the proxy credential. @IBOutlet weak var usernameCell: TextFieldCell! /// A table view cell containing a text input field where the user enters the password portion of the proxy credential. @IBOutlet weak var passwordCell: TextFieldCell! /// A table view cell containing a switch that toggles authentication for the proxy server. @IBOutlet weak var authenticationSwitchCell: SwitchCell! /// The NEProxyServer object containing the proxy server settings. var targetServer = NEProxyServer(address: "", port: 0) /// The block to call when the user taps on the "Done" button. var saveChangesCallback: (NEProxyServer) -> Void = { server in return } // MARK: UIViewController /// Handle the event where the view is loaded into memory. override func viewDidLoad() { super.viewDidLoad() cells = [ addressCell, portCell, authenticationSwitchCell ].compactMap { $0 } authenticationSwitchCell.dependentCells = [ usernameCell, passwordCell ] authenticationSwitchCell.getIndexPath = { return self.getIndexPathOfCell(self.authenticationSwitchCell) } as (() -> IndexPath?) authenticationSwitchCell.valueChanged = { self.updateCellsWithDependentsOfCell(self.authenticationSwitchCell) self.targetServer.authenticationRequired = self.authenticationSwitchCell.isOn } as (() -> Void) } /// Handle the event when the view is being displayed. override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() addressCell.textField.text = !targetServer.address.isEmpty ? targetServer.address : nil portCell.textField.text = targetServer.port > 0 ? String(targetServer.port) : nil passwordCell.textField.text = targetServer.password usernameCell.textField.text = targetServer.username authenticationSwitchCell.isOn = targetServer.authenticationRequired } // MARK: Interface /// Set the NEProxyServer object to modify, the title of the view, and a block to call when the user is done modify the proxy server settings. func setTargetServer(_ server: NEProxyServer?, title: String, saveHandler: @escaping (NEProxyServer) -> Void) { targetServer = server ?? NEProxyServer(address: "", port: 0) navigationItem.title = title saveChangesCallback = saveHandler } /// Gather all of the inputs from the user and call saveChangesCallback. This function is called when the user taps on the "Done" button. @IBAction func saveProxyServer(_ sender: AnyObject) { guard let address = addressCell.textField.text, let portString = portCell.textField.text, let port = Int(portString) , !address.isEmpty && !portString.isEmpty else { return } let result = NEProxyServer(address: address, port: port) result.username = usernameCell.textField.text result.password = passwordCell.textField.text result.authenticationRequired = authenticationSwitchCell.isOn saveChangesCallback(result) // Go back to the main proxy settings view. performSegue(withIdentifier: "save-proxy-server-settings", sender: sender) } }
39.676768
143
0.77113
91be97d9eb0bfeeec0275c417bd4a46ad2e6219d
2,315
// // EditProfilePresenter.swift // Blogs // // Created by Vyacheslav Pronin on 13.08.2021. // // import Foundation final class EditProfilePresenter { weak var view: EditProfileViewInput? weak var moduleOutput: EditProfileModuleOutput? private let router: EditProfileRouterInput private let interactor: EditProfileInteractorInput init(router: EditProfileRouterInput, interactor: EditProfileInteractorInput) { self.router = router self.interactor = interactor } } extension EditProfilePresenter: EditProfileModuleInput { } extension EditProfilePresenter: EditProfileViewOutput { func getAvatar(image: String) { interactor.giveAvatar(image: image) } func didTapAvatarButton() { interactor.editAvatar() } func didFinishNameText(text: String) { interactor.newNameText(text: text) } func didFinishSurnameText(text: String) { interactor.newSurnameText(text: text) } func didFinishTagNameText(text: String) { interactor.newTagNameText(text: text) } func didFinishAboutMeText(text: String) { interactor.newAboutMeText(text: text) } func setupTextInViews() { interactor.giveMyProfile() } func didTapBackButton() { router.popViewController() } func didTapEditAvatarButton() { interactor.editAvatar() } func didTapSaveButton() { interactor.verificationOfEnteredData() } } extension EditProfilePresenter: EditProfileInteractorOutput { func transferAvatar(image: String) { view?.newAvatar(image: image) } func callAlertAvatar() { view?.showAlertAvatar() } func transferErrorName(text: String) { view?.showErrorName(text: text) } func transferErrorSurname(text: String) { view?.showErrorSurname(text: text) } func transferErrorTagName(text: String) { view?.showErrorTagName(text: text) } func transferErrorAboutMe(text: String) { view?.showErrorAboutMe(text: text) } func openBackViewController() { router.popViewController() } func giveAwayMyProfile(profile: User) { view?.updateViews(profile: profile) } }
22.259615
82
0.65486
8750773729e82b86d3c2648c7e94fbe11ce48cbb
254
// class_15 internal class class_15{ var foo = [String]() var bar = [String:[String]]() internal init(){ foo.append("hello world") bar["foo"] = foo } internal func helloWorld() -> String { return bar["foo"]![0] } }
15.875
41
0.551181
69fab2acbc7987c27031e3da5ed56e6a18f3b727
1,009
// // ProtocolObj.swift // SwiftDump // // Created by neilwu on 2020/6/26. // Copyright © 2020 nw. All rights reserved. // import Foundation final class SDProtocolObj { var flags: UInt32 = 0; var name: String = ""; var numRequirementsInSignature: UInt32 = 0; var numRequirements: UInt32 = 0; var associatedTypeNames: String = ""; // joined by " " var superProtocols:[String] = []; var dumpDefine: String { let intent: String = " " var str: String = "protocol \(name)"; if (superProtocols.count > 0) { let superStr: String = superProtocols.joined(separator: ",") str += " : " + superStr; } str += " {\n"; str += intent + "//flags \(flags.hex), numRequirements \(numRequirements)" + "\n" for astype in associatedTypeNames.split(separator: " ") { str += intent + "associatedtype " + String(astype) + "\n" } str += "}\n" return str; } }
27.27027
89
0.55005
1cc9ed009ad7ac9d9449d64d995e2d62684fb6df
5,008
// // MIT License // // Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com ) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // swiftlint:disable colon opening_brace /// A way of sending, receiving and storing data from a verified source via a Message Particle type. Message Particle instances may contain arbitrary byte data with arbitrary string-based key-value metadata. /// /// Sending, storing and fetching data in some form is required for virtually every application - from everyday instant messaging to complex supply chain management. /// A decentralised ledger needs to support simple and safe mechanisms for data management to be a viable platforms for decentralised applications (or DApps). /// For a formal definition read [RIP - Messages][1]. /// /// [1]: https://radixdlt.atlassian.net/wiki/spaces/AM/pages/412844083/RIP-3+Messages /// public struct MessageParticle: ParticleConvertible, RadixModelTypeStaticSpecifying, Accountable, RadixCodable, Equatable { // swiftlint:enable colon opening_brace public static let serializer = RadixModelType.messageParticle public let from: Address public let to: Address public let metaData: MetaData public let payload: Data public let nonce: Nonce public init( from: Address, to: Address, payload: Data, nonce: Nonce = Nonce(), metaData: MetaData = [:] ) { self.from = from self.to = to self.metaData = metaData self.payload = payload self.nonce = nonce } } // MARK: - Convenience init public extension MessageParticle { init(from: Address, to: Address, message: String, nonce: Nonce = Nonce(), includeTimeNow: Bool = true) { let messageData = message.toData() let metaData: MetaData = includeTimeNow ? .timeNow : [:] self.init( from: from, to: to, payload: messageData, nonce: nonce, metaData: metaData ) } } // MARK: - Accountable public extension MessageParticle { func addresses() throws -> Addresses { return try Addresses(addresses: [from, to]) } } // MARK: Codable public extension MessageParticle { enum CodingKeys: String, CodingKey { case serializer, version, destinations case from case to case payload = "bytes" case nonce case metaData } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let from = try container.decode(Address.self, forKey: .from) let to = try container.decode(Address.self, forKey: .to) let payloadBase64 = try container.decodeIfPresent(Base64String.self, forKey: .payload) let metaData = try container.decodeIfPresent(MetaData.self, forKey: .metaData) ?? [:] let nonce = try container.decode(Nonce.self, forKey: .nonce) self.init( from: from, to: to, payload: payloadBase64?.asData ?? Data(), nonce: nonce, metaData: metaData ) } func encodableKeyValues() throws -> [EncodableKeyValue<CodingKeys>] { let payloadOrEmpty = payload.isEmpty ? "" : payload.toBase64String() return [ EncodableKeyValue(key: .from, value: from), EncodableKeyValue(key: .to, value: to), EncodableKeyValue(key: .payload, value: payloadOrEmpty), EncodableKeyValue(key: .nonce, value: nonce), EncodableKeyValue(key: .metaData, nonEmpty: metaData) ].compactMap { $0 } } } public extension MessageParticle { var textMessage: String { return String(data: payload) } } public extension MessageParticle { var debugPayloadDescription: String { return "'\(textMessage)' [\(from) ➡️ \(to)]" } }
33.837838
207
0.661142
18449ff601c6426787921b6312580fc1a8ce7416
14,479
// // ShiftImport.swift // masamon // // Created by 岩見建汰 on 2015/11/04. // Copyright © 2015年 Kenta. All rights reserved. // import UIKit import Eureka class ShiftImport: FormViewController, UIWebViewDelegate{ let filemanager:FileManager = FileManager() let documentspath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let Libralypath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as String let filename = DBmethod().FilePathTmpGet().lastPathComponent //ファイル名の抽出 let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate var myWebView = UIWebView() var myIndiator = UIActivityIndicatorView() var filename_new = "" var staff_count_new = 0 override func viewDidLoad() { super.viewDidLoad() // ナビゲーションバーの設定 let cancel_button = UIBarButtonItem(image: UIImage(named: "icon_cancel"), style: .plain, target: self, action: #selector(self.TapCancelButton(sender:))) let do_import_button = UIBarButtonItem(image: UIImage(named: "icon_import"), style: .plain, target: self, action: #selector(self.TapDoImportButton(sender:))) self.navigationItem.title = "シフトの取り込み" self.navigationController?.navigationBar.barTintColor = UIColor.black self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white] self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationItem.setLeftBarButton(cancel_button, animated: true) self.navigationItem.setRightBarButton(do_import_button, animated: true) if DBmethod().FilePathTmpGet() != "" { filename_new = DBmethod().FilePathTmpGet().lastPathComponent } if DBmethod().DBRecordCount(StaffNumberDB.self) != 0 { staff_count_new = DBmethod().StaffNumberGet() } CreateForm() // PDFを開くためのWebViewを生成. myWebView = UIWebView(frame: CGRect(x: 0, y: self.view.frame.height/2, width: self.view.frame.width, height: 400)) myWebView.delegate = self myWebView.scalesPageToFit = true // URLReqestを生成. let documentspath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String let Inboxpath = documentspath + "/Inbox/" let filePath = Inboxpath + filename_new let myPDFurl = URL(fileURLWithPath: filePath) let myRequest = URLRequest(url: myPDFurl) // ページ読み込み中に表示させるインジケータを生成. myIndiator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) myIndiator.center = self.view.center myIndiator.hidesWhenStopped = true myIndiator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray // WebViewのLoad開始. myWebView.loadRequest(myRequest) // viewにWebViewを追加. self.view.addSubview(myWebView) } func CreateForm() { let RuleRequired_M = "必須項目です" LabelRow.defaultCellUpdate = { cell, row in cell.contentView.backgroundColor = .red cell.textLabel?.textColor = .white cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13) cell.textLabel?.textAlignment = .right } form +++ Section() <<< TextRow() { $0.title = "ファイル名" $0.value = filename_new $0.add(rule: RuleRequired()) $0.validationOptions = .validatesOnChange $0.tag = "name" } .onRowValidationChanged { cell, row in let rowIndex = row.indexPath!.row while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow { row.section?.remove(at: rowIndex + 1) } if !row.isValid { for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() { let labelRow = LabelRow() { $0.title = RuleRequired_M $0.cell.height = { 30 } } row.section?.insert(labelRow, at: row.indexPath!.row + index + 1) } } } <<< IntRow(){ $0.title = "従業員の人数" $0.value = staff_count_new $0.tag = "count" $0.add(rule: RuleRequired()) $0.validationOptions = .validatesOnChange } .onRowValidationChanged { cell, row in let rowIndex = row.indexPath!.row while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow { row.section?.remove(at: rowIndex + 1) } if !row.isValid { for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() { let labelRow = LabelRow() { $0.title = RuleRequired_M $0.cell.height = { 30 } } row.section?.insert(labelRow, at: row.indexPath!.row + index + 1) } } } } @objc func TapCancelButton(sender: UIButton) { let inboxpath = documentspath + "/Inbox/" //Inboxまでのパス //コピーしたファイルの削除 do{ try filemanager.removeItem(atPath: inboxpath + filename) DBmethod().InitRecordInboxFileCountDB() }catch{ print(error) } self.dismiss(animated: true, completion: nil) } @objc func TapDoImportButton(sender: UIButton) { var err_count = 0 for row in form.allRows { err_count = row.validate().count } if err_count == 0 { if DBmethod().DBRecordCount(UserNameDB.self) == 0 || DBmethod().DBRecordCount(HourlyPayDB.self) == 0 { self.present(Utility().GetStandardAlert(title: "エラー", message: "先に設定画面で情報の登録をして下さい", b_title: "OK"),animated: true, completion: nil) }else { DoImport() } }else { self.present(Utility().GetStandardAlert(title: "エラー", message: "必須項目を入力してください", b_title: "OK"),animated: true, completion: nil) } } func DoImport() { //DBにスタッフの人数を保存 let staff_count = form.values()["count"] as! Int let staffnumberrecord = StaffNumberDB() staffnumberrecord.id = 0 staffnumberrecord.number = staff_count DBmethod().AddandUpdate(staffnumberrecord, update: true) //ファイル名を更新 filename_new = form.values()["name"] as! String //ファイル形式がpdfの場合 if filename.contains(".pdf") || filename.contains(".PDF") { if filename_new != "" { let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス let filemanager = FileManager() if filemanager.fileExists(atPath: Libralypath+"/"+filename_new) { //入力したファイル名が既に存在する場合 //アラートを表示して上書きかキャンセルかを選択させる let alert:UIAlertController = UIAlertController(title:"取り込みエラー", message: "既に同じファイル名が存在します", preferredStyle: UIAlertControllerStyle.alert) let cancelAction:UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.cancel, handler:{ (action:UIAlertAction!) -> Void in }) let updateAction:UIAlertAction = UIAlertAction(title: "上書き", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in do{ try filemanager.removeItem(atPath: self.Libralypath+"/"+self.filename_new) self.FileSaveAndMove(Inboxpath, update: true) }catch{ print(error) } self.dismiss(animated: true, completion: nil) }) alert.addAction(cancelAction) alert.addAction(updateAction) present(alert, animated: true, completion: nil) }else{ //入力したファイル名が被ってない場合 self.FileSaveAndMove(Inboxpath, update: false) self.dismiss(animated: true, completion: nil) } } }else{ if filename_new != "" { let Inboxpath = documentspath + "/Inbox/" //Inboxまでのパス let filemanager = FileManager() if filemanager.fileExists(atPath: Libralypath+"/"+filename_new) { //入力したファイル名が既に存在する場合 //アラートを表示して上書きかキャンセルかを選択させる let alert:UIAlertController = UIAlertController(title:"取り込みエラー", message: "既に同じファイル名が存在します", preferredStyle: UIAlertControllerStyle.alert) let cancelAction:UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertActionStyle.cancel, handler:{ (action:UIAlertAction!) -> Void in }) let updateAction:UIAlertAction = UIAlertAction(title: "上書き", style: UIAlertActionStyle.default, handler:{ (action:UIAlertAction!) -> Void in do{ try filemanager.removeItem(atPath: self.Libralypath+"/"+self.filename_new) self.FileSaveAndMove(Inboxpath, update: true) }catch{ print(error) } self.dismiss(animated: true, completion: nil) }) alert.addAction(cancelAction) alert.addAction(updateAction) present(alert, animated: true, completion: nil) }else{ //入力したファイル名が被ってない場合 self.FileSaveAndMove(Inboxpath, update: false) self.dismiss(animated: true, completion: nil) } }else{ //テキストフィールドが空の場合 let alertController = UIAlertController(title: "取り込みエラー", message: "ファイル名を入力して下さい", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func startAnimation() { // NetworkActivityIndicatorを表示. UIApplication.shared.isNetworkActivityIndicatorVisible = true // UIACtivityIndicatorを表示. if !myIndiator.isAnimating { myIndiator.startAnimating() } // viewにインジケータを追加. self.view.addSubview(myIndiator) } func stopAnimation() { // NetworkActivityIndicatorを非表示. UIApplication.shared.isNetworkActivityIndicatorVisible = false // UIACtivityIndicatorを非表示. if myIndiator.isAnimating { myIndiator.stopAnimating() } } func webViewDidStartLoad(_ webView: UIWebView) { startAnimation() } func webViewDidFinishLoad(_ webView: UIWebView) { stopAnimation() } func FileSaveAndMove(_ Inboxpath: String, update: Bool){ do{ try filemanager.moveItem(atPath: Inboxpath+self.filename, toPath: self.Libralypath+"/"+filename_new) }catch{ print(error) } self.appDelegate.filesavealert = true self.appDelegate.filename = filename_new self.appDelegate.update = update DBmethod().InitRecordInboxFileCountDB() //DBへパスを記録 let filepathrecord = FilePathTmpDB() filepathrecord.id = 0 filepathrecord.path = self.Libralypath+"/"+filename_new as NSString DBmethod().AddandUpdate(filepathrecord,update: true) } }
44.965839
165
0.481594
d610e2ebfb11484d950c820611f58ae7350bc84e
487
import UIKit import ComponentKit class PasteboardManager { var value: String? { UIPasteboard.general.string } func set(value: String) { UIPasteboard.general.setValue(value, forPasteboardType: "public.plain-text") } } class CopyHelper { static func copyAndNotify(value: String) { UIPasteboard.general.setValue(value, forPasteboardType: "public.plain-text") HudHelper.instance.showSuccess(title: "alert.copied".localized) } }
20.291667
84
0.694045
399d5a0f90097910353f655b435a1be84120033f
1,007
import UIKit import Mapbox class SimpleMapViewController: UIViewController, MGLMapViewDelegate{ // Update the token here if you want to customize the token for this controller in your own project. // Otherwise update the value at the top of the main controller: ViewController.swift. // let accessToken = "YOUR_ACCESS_TOKEN" override func viewDidLoad() { super.viewDidLoad() // Initialize title title = "Simple street map" let url = URL(string: "https://api.jawg.io/styles/jawg-streets.json?access-token="+accessToken) let mapView = MGLMapView(frame: view.bounds, styleURL: url) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.delegate = self mapView.logoView.isHidden = true // Set the map’s center coordinate and zoom level. mapView.setCenter(CLLocationCoordinate2D(latitude: -33.865143, longitude: 151.209900), zoomLevel: 12, animated: false) view.addSubview(mapView) } }
41.958333
126
0.702085
1d83e3eb170c52c135b9140dd697803c3772d95f
1,180
// // ViewController.swift // TwitterClient // // Created by Prasanthi Relangi on 2/19/16. // Copyright © 2016 prasanthi. All rights reserved. // import UIKit import BDBOAuth1Manager //TwitterBlue color: rgb(29,161,242) 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 onLogin(sender: AnyObject) { TwitterClient.sharedInstance.loginWithCompletion() { (user:User?, error: NSError?) in if user != nil { //perform segue //self.performSegueWithIdentifier("loginSegue", sender: self) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.setupHamburgerVC() } else { //handle login error } } } }
23.137255
92
0.576271
4af8a1824d9e18af22943fd9f9764038b2fe9d6d
262
//: [Previous](@previous) // https://leetcode-cn.com/problems/container-with-most-water/ import Foundation let heights = [1,8,6,2,5,4,8,3,7] print("暴力解法:\(MaxArea1.violentSolution(heights))") print("最优解法:\(MaxArea1.bestSolution(heights))") //: [Next](@next)
21.833333
62
0.694656
036615e191b49505822787cc3ca2e20dd5c2d11d
1,237
// // Express.swift // Baboon // // Created by Amir Daliri on 4/15/17. // Copyright © 2017 Baboon. All rights reserved. // import UIKit class Express: UIViewController { @IBOutlet weak var webview: UIWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. webview.loadRequest(URLRequest(url: URL(string: Strings.express)!)) self.navigationController?.navigationBar.barTintColor = UIColor.navbar } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func menuTapped(_ sender: Any) { let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.drawerController?.toggle(.left, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
28.113636
106
0.691997
e4fdfb6ba45a3834843aebb8f3888d0bd5864462
234
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var:{class B<T where B:C{let a{struct T:e}}struct T{protocol A:P
39
87
0.75641
3a6ff4305f6de75d4e5f47de2431829101793304
4,022
// // FormViewController.swift // LBTATools // // Created by Brian Voong on 5/16/19. // import UIKit @available(iOS 9.0, *) open class LBTAFormController: UIViewController { var lowestElement: UIView! public lazy var scrollView: UIScrollView = { let sv = UIScrollView() if #available(iOS 11.0, *) { sv.contentInsetAdjustmentBehavior = .never } sv.contentSize = view.frame.size sv.keyboardDismissMode = .interactive return sv }() public let formContainerStackView: UIStackView = { let sv = UIStackView() sv.isLayoutMarginsRelativeArrangement = true sv.axis = .vertical return sv }() fileprivate let alignment: FormAlignment public init(alignment: FormAlignment = .top) { self.alignment = alignment super.init(nibName: nil, bundle: nil) } public required init?(coder aDecoder: NSCoder) { fatalError("You most likely have a Storyboard controller that uses this class, please remove any instance of LBTAFormController or sublasses of this component from your Storyboard files.") } override open func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(scrollView) scrollView.fillSuperview() scrollView.addSubview(formContainerStackView) if alignment == .top { formContainerStackView.anchor(top: scrollView.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor) } else { formContainerStackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true formContainerStackView.centerInSuperview() } setupKeyboardNotifications() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if formContainerStackView.frame.height > view.frame.height { scrollView.contentSize.height = formContainerStackView.frame.size.height } _ = distanceToBottom } lazy fileprivate var distanceToBottom = self.distanceFromLowestElementToBottom() fileprivate func distanceFromLowestElementToBottom() -> CGFloat { if lowestElement != nil { guard let frame = lowestElement.superview?.convert(lowestElement.frame, to: view) else { return 0 } let distance = view.frame.height - frame.origin.y - frame.height return distance } return view.frame.height - formContainerStackView.frame.maxY } fileprivate func setupKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc fileprivate func handleKeyboardShow(notification: Notification) { guard let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } let keyboardFrame = value.cgRectValue scrollView.contentInset.bottom = keyboardFrame.height // when stackView is center aligned, we need some extra bottom padding, not sure why yet... if alignment == .center { scrollView.contentInset.bottom += UIApplication.shared.statusBarFrame.height } if distanceToBottom > 0 { scrollView.contentInset.bottom -= distanceToBottom } self.scrollView.scrollIndicatorInsets.bottom = keyboardFrame.height } @objc fileprivate func handleKeyboardHide() { self.scrollView.contentInset.bottom = 0 self.scrollView.scrollIndicatorInsets.bottom = 0 } public enum FormAlignment { case top, center } }
35.59292
196
0.6636
e04e1b2cd494fa956d35d93b39347167977a655c
1,696
// // ViewController.swift // demo // // Created by Feng on 2020/4/17. // Copyright © 2020 Zhuhao Wang. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var switchBtn: UISwitch! var status: VPNStatus { didSet(o) { updateConnectButton() } } required init?(coder aDecoder: NSCoder) { self.status = .off super.init(coder: aDecoder) NotificationCenter.default.addObserver(self, selector: #selector(onVPNStatusChanged), name: kProxyServiceVPNStatusNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: kProxyServiceVPNStatusNotification, object: nil) } @objc func onVPNStatusChanged(){ self.status = VpnManager.shared.vpnStatus } func updateConnectButton(){ switch status { case .connecting: break case .disconnecting: break case .on: switchBtn.isOn = true break case .off: switchBtn.isOn = false break } } @IBAction func clickSwitch(_ sender: UISwitch) { if sender.isOn { VpnManager.shared.host = "202.60.250.190" VpnManager.shared.port = 9286 VpnManager.shared.name = "900182:MT163AAFE857FC76B4F678B6CA95B69E611E7" VpnManager.shared.dns = "114.114.114.114" VpnManager.shared.password = "4BPiTF0isY33MVJe" VpnManager.shared.endtime = 1687090004 VpnManager.shared.connect() }else{ VpnManager.shared.disconnect() } } }
25.69697
148
0.596108
715a81c2f8270892afa9738fe5496ae569fce937
1,094
// // MainViewController.swift // AMXFontAutoScale // // Created by Alexandru Maimescu on 4/1/17. // Copyright © 2017 Alex Maimescu. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet var helloLabels: [UILabel]! @IBOutlet var sizeLabels: [UILabel]! override func viewDidLoad() { super.viewDidLoad() for helloLabel in helloLabels { helloLabel.amx_fontSizeUpdateHandler = { originalSize, preferredSize, multiplier in print("For original size: \(originalSize) set preferred size: \(preferredSize), multiplier: \(multiplier)") } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if helloLabels.count == sizeLabels.count { for (index, helloLabel) in helloLabels.enumerated() { sizeLabels[index].text = String(format: "%.2f", helloLabel.font.pointSize) } } else { fatalError("Please connect all the outlets.") } } }
28.789474
123
0.61426
4bda112c344e659afac76a9020fc5e7924bfa3c2
267
// // Address.swift // Charlie // // Created by Halil Gursoy on 11.12.19. // Copyright © 2019 Halil. All rights reserved. // import Foundation struct Address: Codable { let street: String init(street: String) { self.street = street } }
14.833333
48
0.617978
e4806c245206407fa92f957e74d3f80b767f4717
6,989
import Foundation /// The sequence behavior when the number of invocations exceeds the number of values provided. enum SequenceType { /// Use the last value. case lastValue /// Return to the first value in the sequence. case looping /// Stop returning values. case finite func nextIndex(_ index: Int, count: Int) -> Int { guard index+1 >= count else { return index + 1 } switch self { case .lastValue: return count-1 case .looping: return 0 case .finite: return count } } } /// Stub a sequence of values. /// /// Provide one or more values which will be returned sequentially for each invocation. The last /// value will be used if the number of invocations is greater than the number of values provided. /// /// ```swift /// given(bird.name) /// .willReturn(sequence(of: "Ryan", "Sterling")) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Prints "Sterling" /// ``` /// /// - Parameter values: A sequence of values to stub. public func sequence<DeclarationType: Declaration, InvocationType, ReturnType>( of values: ReturnType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: values, type: .lastValue) } /// Stub a sequence of implementations. /// /// Provide one or more implementations which will be returned sequentially for each invocation. The /// last implementation will be used if the number of invocations is greater than the number of /// implementations provided. /// /// ```swift /// given(bird.name).willReturn(sequence(of: { /// return Bool.random() ? "Ryan" : "Meisters" /// }, { /// return Bool.random() ? "Sterling" : "Hackley" /// })) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Prints "Hackley" /// ``` /// /// - Parameter implementations: A sequence of implementations to stub. public func sequence<DeclarationType: Declaration, InvocationType, ReturnType>( of implementations: InvocationType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: implementations, type: .lastValue) } /// Stub a looping sequence of values. /// /// Provide one or more values which will be returned sequentially for each invocation. The sequence /// will loop from the beginning if the number of invocations is greater than the number of values /// provided. /// /// ```swift /// given(bird.name) /// .willReturn(loopingSequence(of: "Ryan", "Sterling")) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// ``` /// /// - Parameter values: A sequence of values to stub. public func loopingSequence<DeclarationType: Declaration, InvocationType, ReturnType>( of values: ReturnType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: values, type: .looping) } /// Stub a looping sequence of implementations. /// /// Provide one or more implementations which will be returned sequentially for each invocation. The /// sequence will loop from the beginning if the number of invocations is greater than the number of /// implementations provided. /// /// ```swift /// given(bird.name).willReturn(loopingSequence(of: { /// return Bool.random() ? "Ryan" : "Meisters" /// }, { /// return Bool.random() ? "Sterling" : "Hackley" /// })) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Prints "Meisters" /// print(bird.name) // Prints "Hackley" /// ``` /// /// - Parameter implementations: A sequence of implementations to stub. public func loopingSequence<DeclarationType: Declaration, InvocationType, ReturnType>( of implementations: InvocationType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: implementations, type: .looping) } /// Stub a finite sequence of values. /// /// Provide one or more values which will be returned sequentially for each invocation. The stub /// will be invalidated if the number of invocations is greater than the number of values provided. /// /// ```swift /// given(bird.name) /// .willReturn(finiteSequence(of: "Ryan", "Sterling")) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Error: Missing stubbed implementation /// ``` /// /// - Parameter values: A sequence of values to stub. public func finiteSequence<DeclarationType: Declaration, InvocationType, ReturnType>( of values: ReturnType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: values, type: .finite) } /// Stub a finite sequence of implementations. /// /// Provide one or more implementations which will be returned sequentially for each invocation. The /// stub will be invalidated if the number of invocations is greater than the number of /// implementations provided. /// /// ```swift /// given(bird.name).willReturn(finiteSequence(of: { /// return Bool.random() ? "Ryan" : "Meisters" /// }, { /// return Bool.random() ? "Sterling" : "Hackley" /// })) /// /// print(bird.name) // Prints "Ryan" /// print(bird.name) // Prints "Sterling" /// print(bird.name) // Error: Missing stubbed implementation /// ``` /// /// - Parameter implementations: A sequence of implementations to stub. public func finiteSequence<DeclarationType: Declaration, InvocationType, ReturnType>( of implementations: InvocationType... ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { return sequence(of: implementations, type: .finite) } /// Stub a sequence of values. /// /// - Parameter values: A list of values to stub. func sequence<DeclarationType: Declaration, InvocationType, ReturnType>( of values: [ReturnType], type: SequenceType ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { var index = 0 let implementation: () -> ReturnType = { let value = values[index] index = type.nextIndex(index, count: values.count) return value } let availability: () -> Bool = { return values.get(index) != nil } return ImplementationProvider(implementation: implementation, availability: availability) } /// Stub a sequence of implementations. /// /// - Parameter implementations: A list of implementations to stub. func sequence<DeclarationType: Declaration, InvocationType, ReturnType>( of implementations: [InvocationType], type: SequenceType ) -> ImplementationProvider<DeclarationType, InvocationType, ReturnType> { var index = 0 let implementationCreator: () -> InvocationType? = { let implementation = implementations.get(index) index = type.nextIndex(index, count: implementations.count) return implementation } return ImplementationProvider(implementationCreator: implementationCreator) }
34.945
100
0.705823
ccc6afc12f20a77d8eec59d392f6819f71cd5ab7
540
// // HitsRoutingLogicSpy.swift // HackerNewsReader // // Created on 28-11-20. // Copyright © 2020 @dequin_cl All rights reserved. // @testable import HackerNewsReader import UIKit class HitsRoutingLogicSpy: NSObject, HitsRoutingLogic, HitsDataPassing { var dataStore: HitsDataStore? var routeToStoryDetailGotCalled = false var routeToStoryDetailSegue: UIStoryboardSegue? func routeToStoryDetail(segue: UIStoryboardSegue?) { routeToStoryDetailGotCalled = true routeToStoryDetailSegue = segue } }
23.478261
72
0.748148
ddfb3e4efdcd6c0497911ab9457c5283ba5eed1e
3,105
// // AppInfoItemsViewController.swift // DemoApp // // Created by Konstantin Koval on 07/03/15. // Copyright (c) 2015 Kostiantyn Koval. All rights reserved. // import UIKit import AppInfo struct AppInfoItem { let name: String let value: String? } class AppInfoItemsViewController: UITableViewController { var items: Array<AppInfoItem> = [] override func viewDidLoad() { super.viewDidLoad() loadItems() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AppInfoItemCell", forIndexPath: indexPath) as! UITableViewCell let item = items[indexPath.row] cell.textLabel?.text = item.name cell.detailTextLabel?.text = item.value return cell } private func loadItems() { items.append(AppInfoItem(name: "CFBundleIdentifier", value:AppInfo.CFBundleIdentifier)) items.append(AppInfoItem(name: "DTPlatformName", value: AppInfo.DTPlatformName)) items.append(AppInfoItem(name: "UIMainStoryboardFile", value:AppInfo.UIMainStoryboardFile)) items.append(AppInfoItem(name: "CFBundleVersion", value:"\(AppInfo.CFBundleVersion!)")) items.append(AppInfoItem(name: "CFBundleSignature", value:AppInfo.CFBundleSignature)) items.append(AppInfoItem(name: "CFBundleExecutable", value:AppInfo.CFBundleExecutable)) items.append(AppInfoItem(name: "LSRequiresIPhoneOS", value:AppInfo.LSRequiresIPhoneOS!>||)) items.append(AppInfoItem(name: "CFBundleName", value:AppInfo.CFBundleName)) items.append(AppInfoItem(name: "UILaunchStoryboardName", value:AppInfo.UILaunchStoryboardName!>||)) items.append(AppInfoItem(name: "CFBundleSupportedPlatforms", value:AppInfo.CFBundleSupportedPlatforms!>||)) items.append(AppInfoItem(name: "CFBundlePackageType", value:AppInfo.CFBundlePackageType)) items.append(AppInfoItem(name: "CFBundleNumericVersion", value:AppInfo.CFBundleNumericVersion!>||)) items.append(AppInfoItem(name: "CFBundleInfoDictionaryVersion", value:AppInfo.CFBundleInfoDictionaryVersion)) items.append(AppInfoItem(name: "UIRequiredDeviceCapabilities", value:AppInfo.UIRequiredDeviceCapabilities!>||)) items.append(AppInfoItem(name: "UISupportedInterfaceOrientations", value:AppInfo.UISupportedInterfaceOrientations!>||)) items.append(AppInfoItem(name: "CFBundleInfoPlistURL", value:AppInfo.CFBundleInfoPlistURL)) items.append(AppInfoItem(name: "CFBundleDevelopmentRegion", value:AppInfo.CFBundleDevelopmentRegion)) items.append(AppInfoItem(name: "DTSDKName", value:AppInfo.DTSDKName)) items.append(AppInfoItem(name: "UIDeviceFamily", value:AppInfo.UIDeviceFamily!>||)) items.append(AppInfoItem(name: "CFBundleShortVersionString", value:AppInfo.CFBundleShortVersionString)) } } postfix operator >|| {} postfix func >|| <T>(x: T ) -> String { return "\(x)" } private func string(object: AnyObject?) -> String? { return object as? String }
41.4
123
0.765539
230f4f44d06d501121d6eb2124a90e742b323273
5,493
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-RAW // RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s -check-prefix=CHECK-CANONICAL // REQUIRES: objc_interop import Newtype // CHECK-CANONICAL-LABEL: sil hidden @_T07newtype17createErrorDomain{{[_0-9a-zA-Z]*}}F // CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String) func createErrorDomain(str: String) -> ErrorDomain { // CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]]) // CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString) return ErrorDomain(rawValue: str) } // CHECK-RAW-LABEL: sil shared [transparent] [serializable] @_T0SC11ErrorDomainVABSS8rawValue_tcfC // CHECK-RAW: bb0([[STR:%[0-9]+]] : $String, // CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var ErrorDomain }, var, name "self" // CHECK-RAW: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]] // CHECK-RAW: [[PB_BOX:%[0-9]+]] = project_box [[MARKED_SELF_BOX]] // CHECK-RAW: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-RAW: [[COPIED_STR:%.*]] = copy_value [[BORROWED_STR]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC // CHECK-RAW: [[BORROWED_COPIED_STR:%.*]] = begin_borrow [[COPIED_STR]] // CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[BORROWED_COPIED_STR]]) // CHECK-RAW: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]] // CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[WRITE]] // CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]] // CHECK-RAW: end_borrow [[BORROWED_COPIED_STR]] from [[COPIED_STR]] // CHECK-RAW: end_borrow [[BORROWED_STR]] from [[STR]] func getRawValue(ed: ErrorDomain) -> String { return ed.rawValue } // CHECK-RAW-LABEL: sil shared [serializable] @_T0SC11ErrorDomainV8rawValueSSvg // CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain): // CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue // CHECK-RAW: [[STORED_VALUE_COPY:%.*]] = copy_value [[STORED_VALUE]] // CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK-RAW: [[OPT_STORED_VALUE_COPY:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[STORED_VALUE_COPY]] // CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thin String.Type // CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OPT_STORED_VALUE_COPY]], [[STRING_META]]) // CHECK-RAW: return [[STRING_RESULT]] class ObjCTest { // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGF : $@convention(method) (@owned Optional<ErrorDomain>, @guaranteed ObjCTest) -> @owned Optional<ErrorDomain> { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC19optionalPassThroughSC11ErrorDomainVSgAGFTo : $@convention(objc_method) (Optional<ErrorDomain>, ObjCTest) -> Optional<ErrorDomain> { @objc func optionalPassThrough(_ ed: ErrorDomain?) -> ErrorDomain? { return ed } // CHECK-RAW-LABEL: sil hidden @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFF : $@convention(method) (MyInt, @guaranteed ObjCTest) -> MyInt { // CHECK-RAW: sil hidden [thunk] @_T07newtype8ObjCTestC18integerPassThroughSC5MyIntVAFFTo : $@convention(objc_method) (MyInt, ObjCTest) -> MyInt { @objc func integerPassThrough(_ ed: MyInt) -> MyInt { return ed } } // These use a bridging conversion with a specialization of a generic witness. // CHECK-RAW-LABEL: sil hidden @_T07newtype15bridgeToNewtypeSC8MyStringVyF func bridgeToNewtype() -> MyString { // CHECK-RAW: [[STRING:%.*]] = apply // CHECK-RAW: [[TO_NS:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-RAW: [[BORROW:%.*]] = begin_borrow [[STRING]] // CHECK-RAW: [[NS:%.*]] = apply [[TO_NS]]([[BORROW]]) // CHECK-RAW: [[TO_MY:%.*]] = function_ref @_T0s20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE026_unconditionallyBridgeFromD1CxAD_01_D5CTypeQZSgFZ : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@owned Optional<τ_0_0.RawValue._ObjectiveCType>, @thick τ_0_0.Type) // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NS]] // CHECK-RAW: [[META:%.*]] = metatype $@thick MyString.Type // CHECK-RAW: apply [[TO_MY]]<MyString, String>({{.*}}, [[OPTNS]], [[META]]) return "foo" as NSString as MyString } // CHECK-RAW-LABEL: sil hidden @_T07newtype17bridgeFromNewtypeSSSC8MyStringV6string_tF func bridgeFromNewtype(string: MyString) -> String { // CHECK-RAW: [[FROM_MY:%.*]] = function_ref @_T0s20_SwiftNewtypeWrapperPss21_ObjectiveCBridgeable8RawValueRpzrlE09_bridgeToD1CAD_01_D5CTypeQZyF : $@convention(method) <τ_0_0 where τ_0_0 : _SwiftNewtypeWrapper, τ_0_0.RawValue : _ObjectiveCBridgeable> (@in_guaranteed τ_0_0) -> @owned τ_0_0.RawValue._ObjectiveCType // CHECK-RAW: [[NS:%.*]] = apply [[FROM_MY]]<MyString, String>( // CHECK-RAW: [[FROM_NS:%.*]] = function_ref @_T0SS10FoundationE36_unconditionallyBridgeFromObjectiveCSSSo8NSStringCSgFZ // CHECK-RAW: [[OPTNS:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NS]] // CHECK-RAW: [[META:%.*]] = metatype $@thin String.Type // CHECK-RAW: apply [[FROM_NS]]([[OPTNS]], [[META]]) return string as NSString as String }
63.872093
338
0.714182
91e9983fb83c0c8db9e6a14c25ea4673dba46ca8
5,459
// // Transactions.swift // Budget // // Created by Mike Kari Anderson on 6/23/18. // Copyright © 2018 Mike Kari Anderson. All rights reserved. // import Firebase class Transactions : Records<Transaction> { private var records: [String:Transaction] = [:] private var recordList: [Transaction] = [] private var periodStart: String? private var periodEnd: String? override init(reference: DatabaseReference) { super.init(reference: reference) } private func inPeriod(_ date: String) -> Bool { guard self.periodStart != nil, self.periodEnd != nil else { return false } return (self.periodStart! <= date) && (date <= self.periodEnd!) } // don't need to sort since the view does that for us private func populateTransactionList() { self.recordList = Array(self.records.values) } override func onChildAdded(_ record: Transaction) { guard self.periodStart != nil, self.periodEnd != nil else { return } if self.inPeriod(record.date) { self.records[record.id!] = record self.populateTransactionList() self.emit(.childAddedInPeriod, Historical(record)) } else if record.date < self.periodStart! { self.emit(.childAddedBeforePeriod, Historical(record)) } super.onChildAdded(record) } override func onChildChanged(_ record: Transaction) { guard self.periodStart != nil, self.periodEnd != nil else { return } if self.inPeriod(record.date) { self.records[record.id!] = record self.populateTransactionList() self.emit(.childChangedInPeriod, Historical(record)) } else { if self.records.removeValue(forKey: record.id!) != nil { self.populateTransactionList() } } self.emit(.childChanged, Historical(record)) } override func onChildRemoved(_ record: Transaction) { guard self.periodStart != nil, self.periodEnd != nil else { return } if self.records.removeValue(forKey: record.id!) != nil { self.populateTransactionList(); } if self.inPeriod(record.date) { self.emit(.childRemovedInPeriod, Historical(record)) } else if record.date < self.periodStart! { self.emit(.childRemovedBeforePeriod, Historical(record)) } self.emit(.childRemoved, Historical(record)) } override func onChildSaved(_ current: Transaction, _ original: Transaction?) { guard self.periodStart != nil, self.periodEnd != nil else { return } if self.inPeriod(current.id!) { self.records[current.id!] = current } else { self.records.removeValue(forKey: current.id!) } } public var Records: [String:Transaction] { get { return self.records } } public var List: [Transaction] { get { return self.recordList } } public var Start: String? { get { return self.periodStart } } public var End: String? { get { return self.periodEnd } } public var Cash: Budget.Cash { get { var result = Budget.Cash() for record in (self.recordList.filter { $0.cash && !$0.paid && !$0.deposit }) { result = result + Budget.Cash(record.amount) } return result } } public var Transfer: Double { get { var result = 0.0 for record in (self.recordList.filter { $0.transfer && !$0.paid }) { result += record.amount } return result } } public func getSame(record: Transaction, completion:@escaping ([Transaction]) -> Void) { self.loadRecordsByChild(child: "name", startAt: record.name, endAt: record.name) { records in let result = records.values.filter { $0.category == record.category } completion(result) } } public func loadPeriod(start: String, end: String, completion:@escaping ([String:Transaction]) -> Void) { self.loadRecordsByChild(child: "date", startAt: start, endAt: end) { records in self.records = records self.populateTransactionList() self.periodStart = start self.periodEnd = end completion(self.records) self.emit(.periodLoaded) } } public func getRecurring(id: String, completion:@escaping ([String:Transaction]) -> Void) { self.loadRecordsByChild(child: "recurring", startAt: id, endAt: id, completion: completion) } public func getTotal(completion:@escaping (Double) -> Void) { guard self.periodStart != nil, self.periodEnd != nil else { completion(0.0) return } self.loadRecordsByChild(child: "date", startAt: nil, endAt: self.periodEnd) { records in let total = records.values.map({ $0.amount }).reduce(0, +) completion(total) } } // TODO SEARCH }
29.994505
109
0.555047
87732b7aa7343867032dbb5961f8f78cbcc88887
1,978
// // ACKeychainSwiftConstants.swift // AutoCommons // // Created by Dhiya Ulhaq Zulha Alamsyah on 08/08/20. // Copyright © 2020 Idolobi. All rights reserved. // import Security /// Constants used by the library public struct ACKeychainSwiftConstants { /// Specifies a Keychain access group. Used for sharing Keychain items between apps. public static var accessGroup: String { return toString(kSecAttrAccessGroup) } /** A value that indicates when your app needs access to the data in a keychain item. The default value is AccessibleWhenUnlocked. For a list of possible values, see KeychainSwiftAccessOptions. */ public static var accessible: String { return toString(kSecAttrAccessible) } /// Used for specifying a String key when setting/getting a Keychain value. public static var attrAccount: String { return toString(kSecAttrAccount) } /// Used for specifying synchronization of keychain items between devices. public static var attrSynchronizable: String { return toString(kSecAttrSynchronizable) } /// An item class key used to construct a Keychain search dictionary. public static var klass: String { return toString(kSecClass) } /// Specifies the number of values returned from the keychain. The library only supports single values. public static var matchLimit: String { return toString(kSecMatchLimit) } /// A return data type used to get the data from the Keychain. public static var returnData: String { return toString(kSecReturnData) } /// Used for specifying a value when setting a Keychain value. public static var valueData: String { return toString(kSecValueData) } /// Used for returning a reference to the data from the keychain public static var returnReference: String { return toString(kSecReturnPersistentRef) } static func toString(_ value: CFString) -> String { return value as String } }
41.208333
194
0.72548
0e0fa8a95ffb32488770c9ec6a87cd70de0f018c
3,561
// // ViewController.swift // CycleScrollViewDemo // // Created by 朱文杰 on 16/2/27. // Copyright © 2016年 朱文杰. All rights reserved. // import UIKit class ViewController: UIViewController, CycleScrollViewDelegate { override func viewDidLoad() { super.viewDidLoad() edgesForExtendedLayout = .None view.backgroundColor = UIColor(red: 0.98, green: 0.98, blue: 0.98, alpha: 0.99) let backgroundView = UIImageView(image: UIImage(named: "005.jpg")) backgroundView.frame = view.bounds view.addSubview(backgroundView) let containerView = UIScrollView(frame: view.frame) containerView.contentSize = CGSize(width: view.frame.width, height: 700) view.addSubview(containerView) title = "Demo" let imageNames = ["h1.jpg", "h2.jpg", "h3.jpg", "h4.jpg"] let imageURLStrings = ["https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg", "https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg", "http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"] let titles = ["First title", "Second title", "Third title", "Fourth title"] let w = view.frame.width let cycleScrollView = CycleScrollView(frame: CGRect(x: 0.0, y: 0.0, width: w, height: 180.0), shouldInfiniteLoop: true, imagesPaths: imageNames) cycleScrollView.delegate = self cycleScrollView.pageControlStyle = .Animated containerView.addSubview(cycleScrollView) cycleScrollView.autoScrollTimeInterval = 4.0 let cycleScrollView2 = CycleScrollView(frame: CGRect(x: 0.0, y: 200.0, width: w, height: 180.0), delegate: self, placeholderImage: UIImage(named: "placeholder")) cycleScrollView2.pageControlAliment = .Right cycleScrollView2.titles = titles cycleScrollView2.currentPageDotColor = UIColor.whiteColor() cycleScrollView2.trustedHosts = ["venj.me"] containerView.addSubview(cycleScrollView2) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { cycleScrollView2.imagePaths = imageURLStrings } cycleScrollView2.clickItemOperation = { print("------ callback at \($0)") } let cycleScrollView3 = CycleScrollView(frame: CGRect(x: 0.0, y: 400.0, width: w, height: 180.0), delegate: self, placeholderImage: UIImage(named: "placeholder")) cycleScrollView3.currentPageDotImage = UIImage(named: "pageControlCurrentDot") cycleScrollView3.pageDotImage = UIImage(named: "pageControlDot") cycleScrollView3.imagePaths = imageURLStrings cycleScrollView3.trustedHosts = ["venj.me"] containerView.addSubview(cycleScrollView3) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func cycleScrollView(cycleScrollView: CycleScrollView, didSelectItemAtIndex index: Int) { print("------ You selected picture \(index)") let demoVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("DemoXibViewController") navigationController?.pushViewController(demoVC, animated: true) } }
43.962963
195
0.704577
7a35bf8af3f74f5013e887a8b15317902e539ae5
3,277
// // View1.swift // dial3 // // Created by [email protected] on 2021/05/01. // import Cocoa class View1: NSView { @IBOutlet weak var label1: NSTextField! @IBOutlet weak var label2: NSTextField! public let unitDeg: Float = 45.0 public var currentFunc: Int = 0 { didSet { if (0 > currentFunc) { currentFunc = 0 } else if (7 < currentFunc) { currentFunc = 7 } if oldValue != currentFunc { setNeedsDisplay(bounds) } } } public var value: String = "" { didSet { if oldValue != value { setNeedsDisplay(bounds) } } } public let funcNames = [ "スクロール縦", "スクロール横", "拡大 / 縮小", "3", "ボリューム", "5", "明るさ", "7" ] override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. let halfWidth = frame.width / 2 let halfHeight = frame.height / 2 let centerX = frame.width / 2 let centerY = frame.height / 2 let fillColor: NSColor = NSColor(red: 0, green: 0, blue: 0.01, alpha: 0.9) let lightColor: NSColor = NSColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 1) let arcColor: NSColor = NSColor(red: 0.3, green: 0.3, blue: 0.3, alpha: 0.5) let outsideCircle = NSBezierPath(roundedRect: self.frame, xRadius: 360, yRadius: 360) fillColor.setFill() outsideCircle.fill() let innerRect: NSRect = NSRect(x: centerX / 2, y: centerY / 2, width: halfWidth, height: halfHeight) let centerCircle = NSBezierPath(roundedRect: innerRect, xRadius: 360, yRadius: 360) lightColor.setFill() centerCircle.fill() let start: Float = Float(currentFunc) * unitDeg - (unitDeg / 2) let end: Float = (Float(currentFunc) + 1) * unitDeg - (unitDeg / 2) let context = NSGraphicsContext.current let circleCenter = NSPoint(x: centerX, y: centerY) let circleRadius = halfWidth - 3 let circleStartAngle = CGFloat(degreeToRadian(angle: start)) let circleEndAngle = CGFloat(degreeToRadian(angle: end)) context?.cgContext.setLineWidth(5.0) context?.cgContext.move(to: circleCenter) context?.cgContext.addArc(center: circleCenter, radius: circleRadius, startAngle: circleStartAngle, endAngle: circleEndAngle, clockwise: true) arcColor.setFill() context?.cgContext.fillPath() context?.cgContext.setLineWidth(5.0) context?.cgContext.addArc(center: circleCenter, radius: circleRadius, startAngle: circleStartAngle, endAngle: circleEndAngle, clockwise: true) NSColor.systemBlue.set() context?.cgContext.strokePath() label1.stringValue = funcNames[currentFunc] if ((4 == currentFunc) || (6 == currentFunc)) { label2.stringValue = value } else { label2.stringValue = "" } } func degreeToRadian(angle: Float) -> Double { let radian = Double(-angle + 90) * Double.pi / 180 return radian } }
30.342593
150
0.568508
71ccfaa705eed1118380831cfc1536c128ff3c18
849
// // RankViewController.swift // TZBTV // // Created by mac on 2018/2/22. // Copyright © 2018年 mac . All rights reserved. // import UIKit class RankViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 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. } */ }
23.583333
106
0.664311
61b6f5b4aae2b9320ebf3e0701053f6a39cebe43
1,527
// // MatcherPathComponent.swift // RxRouting // // Created by Bas van Kuijck on 05/06/2019. // Copyright © 2019 E-sites. All rights reserved. // import Foundation enum MatcherPathComponent { case plain(String) case placeholder(type: String, key: String) } extension MatcherPathComponent { init(_ value: String) { if value.hasPrefix("<") && value.hasSuffix(">") { let start = value.index(after: value.startIndex) let end = value.index(before: value.endIndex) let placeholder = value[start..<end] // e.g. "<id:int>" -> "id:int" let typeAndKey = placeholder.components(separatedBy: ":") if typeAndKey.count == 1 { // no type, default = string self = .placeholder(type: String.typeName, key: typeAndKey[0]) return } else if typeAndKey.count == 2 { self = .placeholder(type: typeAndKey[1], key: typeAndKey[0]) return } } self = .plain(value) } } extension MatcherPathComponent: Equatable { static func == (lhs: MatcherPathComponent, rhs: MatcherPathComponent) -> Bool { switch (lhs, rhs) { case let (.plain(leftValue), .plain(rightValue)): return leftValue == rightValue case let (.placeholder(leftType, leftKey), .placeholder(rightType, key: rightKey)): return (leftType == rightType) && (leftKey == rightKey) default: return false } } }
29.941176
91
0.582187
234fade3171960f9b5e2ccfa6a6a94d834ba47ba
3,442
// // DBCloud.swift // Harvest // // Created by Letanyan Arumugam on 2018/06/24. // Copyright © 2018 University of Pretoria. All rights reserved. // import FirebaseDatabase enum HarvestCloud { static let baseURL = "https://us-central1-harvest-ios-1522082524457.cloudfunctions.net/" static func component(onBase base: String, withArgs args: [(String, String)]) -> String { guard let first = args.first else { return base } let format: ((String, String)) -> String = { kv in return kv.0 + "=" + kv.1 } var result = base + "?" + format(first) for kv in args.dropFirst() { result += "&" + format(kv) } return result } static func makeBody(withArgs args: [(String, String)]) -> String { guard let first = args.first else { return "" } let format: ((String, String)) -> String = { kv in return kv.0 + "=" + kv.1 } var result = format(first) for kv in args.dropFirst() { result += "&" + format(kv) } return result } static func runTask(withQuery query: String, completion: @escaping (Any) -> Void) { let furl = URL(string: baseURL + query)! let task = URLSession.shared.dataTask(with: furl) { data, _, error in if let error = error { print(error) return } guard let data = data else { completion(Void()) return } guard let jsonSerilization = try? JSONSerialization.jsonObject(with: data, options: []) else { completion(Void()) return } completion(jsonSerilization) } task.resume() } static func runTask(_ task: String, withBody body: String, completion: @escaping (Any) -> Void) { let furl = URL(string: baseURL + task)! var request = URLRequest(url: furl) // request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = body.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, _, error in if let error = error { print(error) return } guard let data = data else { completion(Void()) return } guard let jsonSerilization = try? JSONSerialization.jsonObject(with: data, options: []) else { completion(Void()) return } completion(jsonSerilization) } task.resume() } // swiftlint:disable function_parameter_count static func timeGraphSessions( grouping: StatKind, ids: [String], period: TimeStep, startDate: Date, endDate: Date, mode: TimedGraphMode, completion: @escaping (Any) -> Void ) { var args = [ ("groupBy", grouping.identifier), ("period", period.identifier), ("startDate", DateFormatter.rfc2822String(from: startDate)), ("endDate", DateFormatter.rfc2822String(from: endDate)), ("mode", mode.identifier), ("uid", HarvestDB.Path.parent) ] for (i, id) in ids.enumerated() { args.append(("id\(i)", id)) } let body = makeBody(withArgs: args) runTask(Identifiers.timeGraphSessions, withBody: body) { (data) in completion(data) } } } extension HarvestCloud { enum Identifiers { static let timeGraphSessions = "timedGraphSessions" } }
24.411348
100
0.590064
895cf050cbf27e9d40d088d056e85a300a2cf77f
527
// // MovieModel.swift // MVVMSample // // Created by Kay Zin Thaw on 24/06/2020. // Copyright © 2020 cbbank. All rights reserved. // import UIKit class MovieModel: Decodable { var artistName: String? var trackName: String? init(artistName:String, trackName: String){ self.artistName = artistName self.trackName = trackName } } class ResultsModel: Decodable { var results = [MovieModel]() init(results: [MovieModel]) { self.results = results } }
17
49
0.622391
4ba80613e183cb1d20c1293b306ca2db200dc666
4,426
// // MainScreen.swift // AnyRing // // Created by Dmitriy Loktev on 19.12.2020. // import SwiftUI struct MainScreen: View { var rings: RingWrapper<RingViewModel> @EnvironmentObject var vm: AnyRingViewModel @State var days: Int @State var selection = 1 var onPeriodChange: ((Int) -> Void)? var body: some View { Form { Section { RingDashboard(size: 150, ring1: rings.first, ring2: rings.second, ring3: rings.third, days: days, shape: .rectangular).padding() TemplatesView { newConfig in rings.first.updateFromSnapshot(snapshot: newConfig.first) rings.second.updateFromSnapshot(snapshot: newConfig.second) rings.third.updateFromSnapshot(snapshot: newConfig.third) onPeriodChange?(vm.globalConfig.days) } } Section { HStack { Text("Days") Picker(selection: $days, label: Text("Days"), content: { Text("1").tag(1) Text("2").tag(2) Text("3").tag(3) Text("5").tag(5) Text("7").tag(7) }) .pickerStyle(SegmentedPickerStyle()) .onChange(of: days, perform: { value in onPeriodChange?(days) }) } Text("Specify how often the progress starts from the beginning. For example you can aggregate number of steps over 3 days") .font(.footnote) .foregroundColor(.secondary) } Section(header: Text("Configuration")) { Picker(selection: $selection, label: Text(""), content: { Text("Ring 1").tag(1) Text("Ring 2").tag(2) Text("Ring 3").tag(3) }).pickerStyle(SegmentedPickerStyle()) } switch(selection) { case 2: RingConfigurationView(ring: rings.second).environmentObject(vm) case 3: RingConfigurationView(ring: rings.third).environmentObject(vm) default: RingConfigurationView(ring: rings.first).environmentObject(vm) } } } } struct MainScreen_Preview: PreviewProvider { static var previews: some View { MainScreen(rings: RingWrapper([ DemoProvider( initValue: 50, config: DemoProvider.Configuration( name: "FirstRing", ring: .first, minValue: 0, maxValue: 100, appearance: RingAppearance( mainColor: CodableColor(.red)), units: "M")) .viewModel(globalConfig: GlobalConfiguration.Default), DemoProvider(initValue: 50, config: DemoProvider.Configuration( name: "SecondRing", ring: .second, minValue: 0, maxValue: 100, appearance: RingAppearance( mainColor: CodableColor(.blue)), units: "M") ).viewModel(globalConfig: GlobalConfiguration.Default), DemoProvider().viewModel(globalConfig: GlobalConfiguration.Default)]), days: 3) .environmentObject(AnyRingViewModel()) } }
42.557692
139
0.402395
dbb6425d262c6b3d46d5fb360473d9bfd08a65ef
5,784
import Cocoa import RepoConfig import Mustache import XCEProjectGenerator // MARK: - Global parameters let swiftVersion = "4.0" let tstSuffix = "Tst" let company = ( name: "XCEssentials", identifier: "io.XCEssentials", prefix: "XCE" ) let product = ( name: "TypedKey", summary: "Generic key for type safe access to values in any key-value storage.", type: Template.XCE.InfoPlist.Options.TargetType.framework ) let moduleName = company.prefix + product.name let podspecPath = moduleName + ".podspec" let projectName = product.name let licenseType = "MIT" // open-source let author = ( name: "Maxim Khatskevich", email: "[email protected]" ) let depTarget = Template.XCE .CocoaPods .Podfile .Options .DeploymentTarget .with( name: .iOS, minimumVersion: "8.0" ) let targetName = ( main: product.name, tst: product.name + tstSuffix ) let targetType = ( main: product.type, tst: Template.XCE.InfoPlist.Options.TargetType.tests ) let targetInfo = ( main: "Info/" + targetName.main + ".plist", tst: "Info/" + targetName.tst + ".plist" ) let bundleId = ( main: company.identifier + "." + product.name, tst: company.identifier + "." + product.name + ".Tst" ) let sourcesPath = ( main: "Sources/" + targetName.main, tst: "Sources/" + targetName.tst ) let structConfigPath = "project.yml" let repo = ( name: product.name, location: PathPrefix .iCloudDrive .appendingPathComponent("Dev/XCEssentials") .appendingPathComponent(product.name) ) // MARK: - Actually write repo configuration files try! Template.XCE.Gitignore .prepare() .render(.cocoaFramework) .write(at: repo.location) try! Template.XCE.SwiftLint .prepare() .render(.recommended) .write(at: repo.location) try! Template.XCE.Fastlane.Fastfile .prepare() .render(.framework(projectName: projectName)) .write(at: repo.location) try! Template.XCE.InfoPlist .prepare() .render(.with(targetType: targetType.main)) .write(to: targetInfo.main, at: repo.location) try! Template.XCE.InfoPlist .prepare() .render(.with(targetType: targetType.tst)) .write(to: targetInfo.tst, at: repo.location) try! Template.XCE.License.MIT .prepare() .render(.with(copyrightEntity: author.name)) .write(at: repo.location) try! Template.XCE.CocoaPods.Podspec .prepare() .render(.with( company: .with( name: company.name, prefix: company.prefix ), product: .with( name: product.name, summary: product.summary ), license: .with( type: licenseType ), author: .with( name: author.name, email: author.email ), deploymentTargets: [depTarget.name], subspecs: false ) ) .write(to: podspecPath, at: repo.location) try! Template.XCE.CocoaPods.Podfile .prepare() .render(.with( workspaceName: product.name, globalEntries: [ "use_frameworks!" ], sharedEntries: [ "podspec" ], targets: [ .target( named: targetName.main, projectName: projectName, deploymentTarget: depTarget, entries: [] ), .target( named: targetName.tst, projectName: projectName, deploymentTarget: depTarget, entries: [] ) ] ) ) .write(at: repo.location) //=== let specFormat = Spec.Format.v2_1_0 let project = Project(projectName) { project in project.configurations.all.override( "IPHONEOS_DEPLOYMENT_TARGET" <<< depTarget.minimumVersion, "SWIFT_VERSION" <<< swiftVersion, "VERSIONING_SYSTEM" <<< "apple-generic" ) project.configurations.debug.override( "SWIFT_OPTIMIZATION_LEVEL" <<< "-Onone" ) //--- project.target(targetName.main, .iOS, .framework) { fwk in fwk.include(sourcesPath.main) //--- fwk.configurations.all.override( "IPHONEOS_DEPLOYMENT_TARGET" <<< depTarget.minimumVersion, "PRODUCT_BUNDLE_IDENTIFIER" <<< bundleId.main, "INFOPLIST_FILE" <<< targetInfo.main, //--- iOS related: "SDKROOT" <<< "iphoneos", "TARGETED_DEVICE_FAMILY" <<< DeviceFamily.iOS.universal, //--- Framework related: "PRODUCT_NAME" <<< moduleName, "DEFINES_MODULE" <<< "NO", "SKIP_INSTALL" <<< "YES" ) fwk.configurations.debug.override( "MTL_ENABLE_DEBUG_INFO" <<< true ) //--- fwk.unitTests(targetName.tst) { fwkTests in fwkTests.include(sourcesPath.tst) //--- fwkTests.configurations.all.override( // very important for unit tests, // prevents the error when unit test do not start at all "LD_RUNPATH_SEARCH_PATHS" <<< "$(inherited) @executable_path/Frameworks @loader_path/Frameworks", "IPHONEOS_DEPLOYMENT_TARGET" <<< depTarget.minimumVersion, "PRODUCT_BUNDLE_IDENTIFIER" <<< bundleId.tst, "INFOPLIST_FILE" <<< targetInfo.tst, "FRAMEWORK_SEARCH_PATHS" <<< "$(inherited) $(BUILT_PRODUCTS_DIR)" ) fwkTests.configurations.debug.override( "MTL_ENABLE_DEBUG_INFO" <<< true ) } } } //=== try! Manager .prepareSpec(specFormat, for: project) .write(to: structConfigPath, at: repo.location)
22.952381
84
0.585927
337bb9578c5b9f8fdeb7c770300551a3b5254722
8,791
// // AlertView.swift // NativeUI // // Created by Anton Poltoratskyi on 05.04.2020. // Copyright © 2020 Anton Poltoratskyi. All rights reserved. // import UIKit protocol AlertViewDelegate: AnyObject { func alertView(_ alertView: AlertView, buttonTappedAtIndex index: Int) } final class AlertView: UIView { private var viewModel: Alert? weak var delegate: AlertViewDelegate? // MARK: - Subviews // MARK: Blur private lazy var blurView: UIVisualEffectView = { let blurStyle: UIBlurEffect.Style if #available(iOS 13, *) { blurStyle = .systemMaterial } else { blurStyle = .extraLight } let blurEffect = UIBlurEffect(style: blurStyle) let effectView = UIVisualEffectView(effect: blurEffect) effectView.translatesAutoresizingMaskIntoConstraints = false addSubview(effectView) return effectView }() // MARK: Content private lazy var contentContainerView: UIView = { let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false blurView.contentView.addSubview(containerView) return containerView }() private lazy var contentStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false contentContainerView.addSubview(stackView) return stackView }() private lazy var titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 return label }() private lazy var messageLabel: UITextView = { let label = UITextView() label.isScrollEnabled = false label.backgroundColor = .clear label.textAlignment = .center label.isEditable = false label.dataDetectorTypes = .link label.linkTextAttributes = [ .foregroundColor: UIColor.systemGray, .underlineStyle: NSUnderlineStyle.single.rawValue ] label.translatesAutoresizingMaskIntoConstraints = false return label }() private lazy var customContentView: UIView = { let contentView = UIView() contentView.translatesAutoresizingMaskIntoConstraints = false return contentView }() // MARK: Actions private lazy var actionsStackView: UIStackView = { let stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false blurView.contentView.addSubview(stackView) return stackView }() private lazy var contentSeparatorView: UIView = { let separatorView = SeparatorView() separatorView.translatesAutoresizingMaskIntoConstraints = false separatorView.axis = .horizontal return separatorView }() private lazy var actionSequenceView: AlertActionSequenceView = { let sequenceView = AlertActionSequenceView() sequenceView.translatesAutoresizingMaskIntoConstraints = false return sequenceView }() // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder: NSCoder) { super.init(coder: coder) initialize() } // MARK: - Base Setup private func initialize() { setupLayout() setupAppearance() } private func setupLayout() { NSLayoutConstraint.activate([ blurView.topAnchor.constraint(equalTo: topAnchor), blurView.leadingAnchor.constraint(equalTo: leadingAnchor), blurView.trailingAnchor.constraint(equalTo: trailingAnchor), blurView.bottomAnchor.constraint(equalTo: bottomAnchor), contentContainerView.topAnchor.constraint(equalTo: blurView.contentView.topAnchor), contentContainerView.leadingAnchor.constraint(equalTo: blurView.contentView.leadingAnchor), contentContainerView.trailingAnchor.constraint(equalTo: blurView.contentView.trailingAnchor), contentStackView.topAnchor.constraint(equalTo: contentContainerView.topAnchor, constant: Layout.Content.top), contentStackView.leadingAnchor.constraint(equalTo: contentContainerView.leadingAnchor, constant: Layout.Content.horizontal), contentStackView.trailingAnchor.constraint(equalTo: contentContainerView.trailingAnchor, constant: -Layout.Content.horizontal), contentStackView.bottomAnchor.constraint(equalTo: contentContainerView.bottomAnchor, constant: -Layout.Content.bottom), actionsStackView.topAnchor.constraint(equalTo: contentContainerView.bottomAnchor), actionsStackView.leadingAnchor.constraint(equalTo: blurView.contentView.leadingAnchor), actionsStackView.trailingAnchor.constraint(equalTo: blurView.contentView.trailingAnchor), actionsStackView.bottomAnchor.constraint(equalTo: blurView.contentView.bottomAnchor) ]) contentStackView.axis = .vertical contentStackView.spacing = Layout.Content.verticalSpacing contentStackView.addArrangedSubview(titleLabel) contentStackView.addArrangedSubview(messageLabel) contentStackView.addArrangedSubview(customContentView) actionsStackView.axis = .vertical actionsStackView.spacing = 0 actionsStackView.addArrangedSubview(contentSeparatorView) actionsStackView.addArrangedSubview(actionSequenceView) [titleLabel, messageLabel].forEach { $0.setContentHuggingPriority(.required, for: .vertical) $0.setContentCompressionResistancePriority(.required, for: .vertical) } actionSequenceView.delegate = self } private func setupAppearance() { backgroundColor = .clear layer.cornerRadius = 12 layer.masksToBounds = true titleLabel.textAlignment = .center messageLabel.textAlignment = .center } // MARK: - Setup func setup(viewModel: Alert) { self.viewModel = viewModel switch viewModel.title { case let .string(text, font): titleLabel.text = text titleLabel.font = font case let .attributedString(attributedText): titleLabel.attributedText = attributedText case nil: titleLabel.text = nil } titleLabel.isHidden = viewModel.title == nil switch viewModel.message { case let .string(text, font): messageLabel.text = text messageLabel.font = font case let .attributedString(attributedText): messageLabel.attributedText = attributedText case nil: messageLabel.text = nil } messageLabel.isHidden = viewModel.message == nil if let contentView = viewModel.contentView { contentView.translatesAutoresizingMaskIntoConstraints = false customContentView.addSubview(contentView) NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: customContentView.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: customContentView.trailingAnchor), contentView.topAnchor.constraint(equalTo: customContentView.topAnchor), contentView.bottomAnchor.constraint(equalTo: customContentView.bottomAnchor) ]) } customContentView.isHidden = viewModel.contentView == nil if !viewModel.actions.isEmpty { let actionsViewModel = AlertActionSequenceViewModel( actions: viewModel.actions, disabledTintColor: viewModel.disabledTintColor ) actionSequenceView.setup(viewModel: actionsViewModel) } contentSeparatorView.isHidden = viewModel.actions.isEmpty actionSequenceView.isHidden = viewModel.actions.isEmpty } // MARK: - Layout private enum Layout { enum Content { static let top: CGFloat = 20 static let bottom: CGFloat = 20 static let horizontal: CGFloat = 16 static let verticalSpacing: CGFloat = 4 } } } // MARK: - AlertActionSequenceViewDelegate extension AlertView: AlertActionSequenceViewDelegate { func alertActionSequenceView(_ actionView: AlertActionSequenceView, tappedAtIndex index: Int) { delegate?.alertView(self, buttonTappedAtIndex: index) } }
35.447581
139
0.658514
cc8e0d7bfacb4e6b776abbe67bd651985d3de1be
438
// // See LICENSE folder for this template’s licensing information. // // Abstract: // Instantiates a live view and passes it to the PlaygroundSupport framework. // import UIKit import PlaygroundSupport // Instantiate a new instance of the live view from the book's auxiliary sources and pass it to PlaygroundSupport. PlaygroundPage.current.liveView = instantiateLiveView(chapter: 2, page: 1) //var sample = UIImage(named: "first")
29.2
114
0.767123
485672312d6ed2ab8b9e435c3781c6898ec041ac
3,224
// GraphTest.swift // UniMaps // // Created by Benni on 14.05.17. // Copyright © 2017 Ben Boecker. All rights reserved. // import XCTest @testable import CoreGraph class GraphTests: XCTestCase { func testBuildingGraphWithInts() { let graph = Graph<Int>() let nodeA = graph.addNode(with: 1).data! let nodeB = graph.addNode(with: 2).data! let nodeC = graph.addNode(with: 3).data! let nodeD = graph.addNode(with: 4).data! let nodeE = graph.addNode(with: 5).data! let nodeF = graph.addNode(with: 3).error as? GraphError graph.addEdge(from: 1, to: 2, weight: 1) graph.addEdge(from: 1, to: 4, weight: 4) graph.addEdge(from: 2, to: 4, weight: 5) graph.addEdge(from: 2, to: 3, weight: 2) graph.addEdge(from: 4, to: 5, weight: 8) graph.addEdge(from: 4, to: 5, weight: 18) // Does not work and simply silently returns XCTAssertEqual(nodeF, GraphError.nodeAlreadyExists) XCTAssertEqual(graph.nodes.count, 5) XCTAssertTrue(graph.node(nodeA, hasEdgeTo: nodeD)) XCTAssertFalse(graph.node(nodeB, hasEdgeTo: nodeE)) XCTAssertFalse(graph.node(nodeC, hasEdgeTo: nodeE)) XCTAssertTrue(graph.node(nodeD, hasEdgeTo: nodeA)) XCTAssertTrue(graph.node(nodeD, hasEdgeTo: nodeE)) } func testGraphSubscript() { let graph = Graph<Int>() let nodeA = graph.addNode(with: 1).data! let nodeB = graph.addNode(with: 2).data! let nodeC = graph.addNode(with: 3).data! graph.addEdge(from: 1, to: 2, weight: 10) graph.addEdge(from: 1, to: 3, weight: 10) let testA = graph[nodeA] let testB = graph[nodeB] let testC = graph[nodeC] let testD = graph[4] XCTAssertEqual(testA?.count, 2) XCTAssertEqual(testB?.count, 1) XCTAssertEqual(testC?.count, 1) XCTAssertEqual(testA?.first?.weight, 10) XCTAssertNil(testD) } func testEmptyGraph() { let graph = Graph<String>() let shortestPathResult = graph.shortestPath(from: "A", to: "B") XCTAssertTrue(shortestPathResult.isUnexpected) XCTAssertEqual(shortestPathResult.error as? GraphError, GraphError.startingPOINotFound) } func testClearGraph() { let graph = Graph<String>() graph.addNode(with: "A") graph.addNode(with: "B") graph.addEdge(from: "A", to: "B", weight: 1) let shortestPathResult = graph.shortestPath(from: "A", to: "B") XCTAssertTrue(shortestPathResult.isExpected) graph.clear() let shortestPathResult2 = graph.shortestPath(from: "A", to: "B") XCTAssertTrue(shortestPathResult2.isUnexpected) } func testHasEdge() { let graph = Graph<String>() graph.addNode(with: "A") graph.addNode(with: "B") graph.addEdge(from: "A", to: "B", weight: 1) XCTAssertTrue(graph.node("A", hasEdgeTo: "B")) XCTAssertTrue(graph.node("B", hasEdgeTo: "A")) XCTAssertFalse(graph.node("A", hasEdgeTo: "A")) XCTAssertFalse(graph.node("A", hasEdgeTo: "C")) XCTAssertFalse(graph.node("C", hasEdgeTo: "C")) } func testGetSuccessorPaths() { let graph = Graph<String>() graph.addNode(with: "A") // A graph.addNode(with: "B") // B let path = Path(with: "A", weight: 10) let pathC = Path(with: "C", weight: 10) XCTAssertEqual(path.totalWeight, 10) XCTAssertEqual(graph.successorsPaths(for: path), []) XCTAssertEqual(graph.successorsPaths(for: pathC), []) } }
28.280702
89
0.690136
6a7329f4ced251e0329d642713f99b6ebaba4da8
1,818
/** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class Solution { // Solution @ Sergey Leschev, Belarusian State University // 530. Minimum Absolute Difference in BST // Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree. // Example 1: // Input: root = [4,2,6,1,3] // Output: 1 // Example 2: // Input: root = [1,0,48,null,null,12,49] // Output: 1 // Constraints: // The number of nodes in the tree is in the range [2, 10^4]. // 0 <= Node.val <= 10^5 // - Complexity: // - Time: O(n), n is the number of nodes in the tree. It takes O(n) to complete inorder, Then, takes O(n) to computer minimum differences. // - Space: O(n), n is the number of nodes in the tree. It stores values in every node. func getMinimumDifference(_ root: TreeNode?) -> Int { var list = [Int]() var minDiff = Int.max func inorder(_ root: TreeNode?) { guard let root = root else { return } inorder(root.left) list.append(root.val) inorder(root.right) } inorder(root) for index in stride(from: 1, to: list.count, by: 1) { minDiff = min(minDiff, list[index] - list[index - 1]) } return minDiff } }
30.813559
150
0.573707
692b347926edb7eb8978fd446db668b7ebf8249b
1,992
// // PopTransition.swift // Transition // // Created by Xie Fan on 16/2/7. // Copyright © 2016年 PrettyX.org. All rights reserved. // import UIKit import UIKit class PopTransion: NSObject, UIViewControllerAnimatedTransitioning { //MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! DetailViewController let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! ViewController let container = transitionContext.containerView() let snapshotView = fromVC.avatarImageView.snapshotViewAfterScreenUpdates(false) snapshotView.frame = container!.convertRect(fromVC.avatarImageView.frame, fromView: fromVC.view) fromVC.avatarImageView.hidden = true toVC.view.frame = transitionContext.finalFrameForViewController(toVC) toVC.selectedCell!.imageView.hidden = true container!.insertSubview(toVC.view, belowSubview: fromVC.view) container!.addSubview(snapshotView) UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in snapshotView.frame = container!.convertRect(toVC.selectedCell!.imageView.frame, fromView: toVC.selectedCell) fromVC.view.alpha = 0 }) { (finish: Bool) -> Void in toVC.selectedCell!.imageView.hidden = false snapshotView.removeFromSuperview() fromVC.avatarImageView.hidden = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) } } }
41.5
159
0.710843
206591f5597902316a0aa1891122521926b05649
1,847
// // Defaults.swift // Bot // // Created by Akram Hussein on 04/09/2017. // Copyright © 2017 Ross Atkin Associates. All rights reserved. // import Foundation public struct Key { public static let ScanningSpeed = "ScanningSpeed" public static let RobotSpeed = "RobotSpeed" public static let Trim = "Trim" public static let ServoOn = "ServoOn" public static let ServoOff = "ServoOff" } public struct Defaults { // Set user defaults key - Bool public static func setUserDefaultsKey(_ key: String, value: Bool) { UserDefaults.standard.set(value, forKey: key) } // Set user defaults key - Int public static func setUserDefaultsKey(_ key: String, value: Int) { UserDefaults.standard.set(value, forKey: key) } // Set user defaults key - Double public static func setUserDefaultsKey(_ key: String, value: Double) { UserDefaults.standard.set(value, forKey: key) } // Set user defaults key - String public static func setUserDefaultsKey(_ key: String, value: String) { UserDefaults.standard.set(value, forKey: key) } // Get user defaults key public static func getUserDefaultsKey(_ key: String) -> Bool { return UserDefaults.standard.bool(forKey: key) } public static func getUserDefaultsValueForKeyAsInt(_ key: String) -> Int { return UserDefaults.standard.integer(forKey: key) } public static func getUserDefaultsValueForKeyAsDouble(_ key: String) -> Double { return UserDefaults.standard.double(forKey: key) } public static func resetUserDefaultsValueForKey(_ key: String) { return UserDefaults.standard.set(nil, forKey: key) } public static func removeUserDefaultsValueForKey(_ key: String) { return UserDefaults.standard.removeObject(forKey: key) } }
29.790323
84
0.688143
1e9dfe411dc7add16c25c463464021bc1584ed2f
612
// // ViewController.swift // SwiftQRCodeScan // // Created by wenyou on 2018/5/6. // Copyright © 2018年 wenyou. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 坐标让过 navigationBar edgesForExtendedLayout = [] } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // override var prefersStatusBarHidden: Bool { // false // } }
19.741935
55
0.650327
e6137fdb293538a8d7307ebade74fb1185881c81
6,804
// // InsertCannulaSetupViewController.swift // OmniKitUI // // Created by Pete Schwamb on 9/18/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import UIKit import LoopKit import LoopKitUI import RileyLinkKit import OmniKit class InsertCannulaSetupViewController: SetupTableViewController { var pumpManager: OmnipodPumpManager! // MARK: - @IBOutlet weak var activityIndicator: SetupIndicatorView! @IBOutlet weak var loadingLabel: UILabel! private var loadingText: String? { didSet { tableView.beginUpdates() loadingLabel.text = loadingText let isHidden = (loadingText == nil) loadingLabel.isHidden = isHidden tableView.endUpdates() } } private var cancelErrorCount = 0 override func viewDidLoad() { super.viewDidLoad() continueState = .initial } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if case .startingInsertion = continueState { return } tableView.deselectRow(at: indexPath, animated: true) } // MARK: - Navigation private enum State { case initial case startingInsertion case inserting(finishTime: CFTimeInterval) case fault case ready } private var continueState: State = .initial { didSet { switch continueState { case .initial: activityIndicator.state = .hidden footerView.primaryButton.isEnabled = true footerView.primaryButton.setConnectTitle() case .startingInsertion: activityIndicator.state = .indeterminantProgress footerView.primaryButton.isEnabled = false lastError = nil case .inserting(let finishTime): activityIndicator.state = .timedProgress(finishTime: CACurrentMediaTime() + finishTime) footerView.primaryButton.isEnabled = false lastError = nil case .fault: activityIndicator.state = .hidden footerView.primaryButton.isEnabled = true footerView.primaryButton.setDeactivateTitle() case .ready: activityIndicator.state = .completed footerView.primaryButton.isEnabled = true footerView.primaryButton.resetTitle() lastError = nil } } } private var lastError: Error? { didSet { guard oldValue != nil || lastError != nil else { return } var errorText = lastError?.localizedDescription if let error = lastError as? LocalizedError { let localizedText = [error.errorDescription, error.failureReason, error.recoverySuggestion].compactMap({ $0 }).joined(separator: ". ") if !localizedText.isEmpty { errorText = localizedText + "." } } // If we have an error but no error text, generate a string to describe the error if let error = lastError, (errorText == nil || errorText!.isEmpty) { errorText = String(describing: error) } loadingText = errorText // If we have an error, update the continue state if let podCommsError = lastError as? PodCommsError { switch podCommsError { case .podFault, .activationTimeExceeded: continueState = .fault default: continueState = .initial } } else if lastError != nil { continueState = .initial } } } private func navigateToReplacePod() { performSegue(withIdentifier: "ReplacePod", sender: nil) } override func continueButtonPressed(_ sender: Any) { switch continueState { case .initial: continueState = .startingInsertion insertCannula() case .ready: super.continueButtonPressed(sender) case .fault: navigateToReplacePod() case .startingInsertion, .inserting: break } } override func cancelButtonPressed(_ sender: Any) { let confirmVC = UIAlertController(pumpDeletionHandler: { self.navigateToReplacePod() }) present(confirmVC, animated: true) {} } private func insertCannula() { pumpManager.insertCannula() { (result) in DispatchQueue.main.async { switch(result) { case .success(let finishTime): self.continueState = .inserting(finishTime: finishTime) let delay = finishTime if delay > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.continueState = .ready } } else { self.continueState = .ready } case .failure(let error): self.lastError = error } } } } } private extension SetupButton { func setConnectTitle() { setTitle(LocalizedString("Insert Cannula", comment: "Button title to insert cannula during setup"), for: .normal) } func setDeactivateTitle() { setTitle(LocalizedString("Deactivate", comment: "Button title to deactivate pod because of fault during setup"), for: .normal) } } private extension UIAlertController { convenience init(pumpDeletionHandler handler: @escaping () -> Void) { self.init( title: nil, message: LocalizedString("Are you sure you want to shutdown this pod?", comment: "Confirmation message for shutting down a pod"), preferredStyle: .actionSheet ) addAction(UIAlertAction( title: LocalizedString("Deactivate Pod", comment: "Button title to deactivate pod"), style: .destructive, handler: { (_) in handler() } )) let exit = LocalizedString("Continue", comment: "The title of the continue action in an action sheet") addAction(UIAlertAction(title: exit, style: .default, handler: nil)) } }
32.246445
150
0.560259
ebc0d48f0cba9c192b8aa73a91b03aa8014b4513
1,426
// // AppDelegate.swift // Cathay // // Created by Steve on 11/9/19. // Copyright © 2019 Steve. All rights reserved. // //swiftlint:disable line_length import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
43.212121
179
0.751052
11834f98060ec043fe611cf710dd138733c382d4
6,685
// // TJPageCollectionView.swift // TJPageView // // Created by zcm_iOS on 2017/5/31. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit //MARK: 代理 protocol TJPageCollectionViewDateSource : class { func numberOfSections(in pageCollectionView : TJPageCollectionView) -> Int func pageCollectionView(_ collectionView : TJPageCollectionView, numberOfItemsInSection section : Int) -> Int func pageCollectionView(_ pageCollectionView : TJPageCollectionView, _ collectionView : UICollectionView, cellForItemAt indexPath : IndexPath) -> UICollectionViewCell } protocol TJPageCollectionViewDelegate : class { func pageCollectionView(_ pageCollectionView : TJPageCollectionView, didSelectorItemAt indexPath : IndexPath) } //MARK: 常量 private let kCollectionViewCell = "kCollectionViewCell" class TJPageCollectionView: UIView { // MARK: 代理 weak var dataSource : TJPageCollectionViewDateSource? weak var delegate : TJPageCollectionViewDelegate? // MARK: 页面属性 fileprivate var style : TJTitleStyle fileprivate var titles : [String] fileprivate var isTitleInTop : Bool fileprivate var layout : TJPageCollectionLayout fileprivate var collectionView : UICollectionView! fileprivate var pageControl : UIPageControl! fileprivate var titleView : TJTitleView! fileprivate var sourceIndexPath : IndexPath = IndexPath(item: 0, section: 0) init(frame: CGRect, style : TJTitleStyle, titles : [String], isTitleInTop : Bool, layout : TJPageCollectionLayout) { self.style = style self.titles = titles self.isTitleInTop = isTitleInTop self.layout = layout super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: 界面搭建 extension TJPageCollectionView{ fileprivate func setupUI(){ //1.创建titleView let titleViewY = isTitleInTop ? 0 : bounds.height - style.titleHeight titleView = TJTitleView(frame: CGRect(x: 0, y: titleViewY, width: bounds.width, height: style.titleHeight), titles: titles, style: style) titleView.delegate = self addSubview(titleView) //2.创建pageControl let pageControllHeight : CGFloat = 20 let pageControlY = isTitleInTop ? bounds.height - pageControllHeight : bounds.height - pageControllHeight - style.titleHeight pageControl = UIPageControl(frame: CGRect(x: 0, y: pageControlY , width: bounds.width, height: pageControllHeight)) pageControl.pageIndicatorTintColor = UIColor.lightGray pageControl.currentPageIndicatorTintColor = UIColor.orange addSubview(pageControl) //3.创建collectionView let collectionViewY = isTitleInTop ? style.titleHeight : 0 collectionView = UICollectionView(frame: CGRect(x: 0, y: collectionViewY, width: bounds.width, height: bounds.height - style.titleHeight - pageControllHeight), collectionViewLayout: layout) // collectionView.backgroundColor = UIColor.white collectionView.isPagingEnabled = true collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kCollectionViewCell) addSubview(collectionView) pageControl.backgroundColor = collectionView.backgroundColor } } // MARK: 对外暴露的方法 extension TJPageCollectionView{ func register(cell : AnyClass?, identifier : String) { collectionView.register(cell, forCellWithReuseIdentifier: identifier) } func register(nib : UINib, identifier : String) { collectionView.register(nib, forCellWithReuseIdentifier: identifier) } func reloadData() { collectionView.reloadData() } } // MARK: UICollectionViewDataSource extension TJPageCollectionView : UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource?.numberOfSections(in: self) ?? 0 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let itemCount = dataSource?.pageCollectionView(self, numberOfItemsInSection: section) ?? 0 if section == 0 { pageControl.numberOfPages = (itemCount - 1) / (layout.cols * layout.rows) + 1 } return itemCount } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return dataSource!.pageCollectionView(self, collectionView, cellForItemAt: indexPath) } } // MARK: UICollectionVIewDelegate extension TJPageCollectionView : UICollectionViewDelegate{ //结束减速 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewEndScroll() } //结束滑动 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { scrollViewEndScroll() } fileprivate func scrollViewEndScroll(){ //取出在屏幕中显示的cell let point = CGPoint(x: layout.sectionInset.left + collectionView.contentOffset.x + 1, y: layout.sectionInset.top + 1) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } //判断分组是否发生改变 if sourceIndexPath.section != indexPath.section { //修改pageController的个数 let itemCOunt = dataSource?.pageCollectionView(self, numberOfItemsInSection: indexPath.section) ?? 0 pageControl.numberOfPages = (itemCOunt - 1) / (layout.cols * layout.rows) + 1 //设置titleView的位置 titleView.setTitleWithProgress(1.0, sourceIndex: sourceIndexPath.section, targetIndex: indexPath.section) //记录 sourceIndexPath = indexPath } // 3.根据indexPath设置pageControl pageControl.currentPage = indexPath.item / (layout.cols * layout.rows) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.pageCollectionView(self, didSelectorItemAt: indexPath) } } // MARK: TJTitleViewDelegate extension TJPageCollectionView : TJTitleViewDelegate{ func titleView(_ titleView: TJTitleView, selectedIndex index: Int) { let indexPath = IndexPath(item: 0, section: index) //此处若为true,则会重新调用EndDecelerating和EndDragging方法 collectionView.scrollToItem(at: indexPath, at: .left, animated: false) collectionView.contentOffset.x -= layout.sectionInset.left scrollViewEndScroll() } }
41.01227
197
0.711743
fbbd1af1d7d0cc67ae89ff0289019590ccbce0ff
52,805
/* 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 TSCBasic import PackageModel import TSCUtility /// An error in the structure or layout of a package. public enum ModuleError: Swift.Error { /// Describes a way in which a package layout is invalid. public enum InvalidLayoutType { case multipleSourceRoots([AbsolutePath]) case modulemapInSources(AbsolutePath) case modulemapMissing(AbsolutePath) } /// Indicates two targets with the same name and their corresponding packages. case duplicateModule(String, [String]) /// The referenced target could not be found. case moduleNotFound(String, TargetDescription.TargetType) /// The artifact for the binary target could not be found. case artifactNotFound(String) /// Invalid custom path. case invalidCustomPath(target: String, path: String) /// Package layout is invalid. case invalidLayout(InvalidLayoutType) /// The manifest has invalid configuration wrt type of the target. case invalidManifestConfig(String, String) /// The target dependency declaration has cycle in it. case cycleDetected((path: [String], cycle: [String])) /// The public headers directory is at an invalid path. case invalidPublicHeadersDirectory(String) /// The sources of a target are overlapping with another target. case overlappingSources(target: String, sources: [AbsolutePath]) /// We found multiple LinuxMain.swift files. case multipleLinuxMainFound(package: String, linuxMainFiles: [AbsolutePath]) /// The tools version in use is not compatible with target's sources. case incompatibleToolsVersions(package: String, required: [SwiftLanguageVersion], current: ToolsVersion) /// The target path is outside the package. case targetOutsidePackage(package: String, target: String) /// Unsupported target path case unsupportedTargetPath(String) /// Invalid header search path. case invalidHeaderSearchPath(String) /// Default localization not set in the presence of localized resources. case defaultLocalizationNotSet } extension ModuleError: CustomStringConvertible { public var description: String { switch self { case .duplicateModule(let name, let packages): let packages = packages.joined(separator: ", ") return "multiple targets named '\(name)' in: \(packages)" case .moduleNotFound(let target, let type): let folderName = type == .test ? "Tests" : "Sources" return "Source files for target \(target) should be located under '\(folderName)/\(target)', or a custom sources path can be set with the 'path' property in Package.swift" case .artifactNotFound(let target): return "artifact not found for target '\(target)'" case .invalidLayout(let type): return "package has unsupported layout; \(type)" case .invalidManifestConfig(let package, let message): return "configuration of package '\(package)' is invalid; \(message)" case .cycleDetected(let cycle): return "cyclic dependency declaration found: " + (cycle.path + cycle.cycle).joined(separator: " -> ") + " -> " + cycle.cycle[0] case .invalidPublicHeadersDirectory(let name): return "public headers directory path for '\(name)' is invalid or not contained in the target" case .overlappingSources(let target, let sources): return "target '\(target)' has sources overlapping sources: " + sources.map({ $0.description }).joined(separator: ", ") case .multipleLinuxMainFound(let package, let linuxMainFiles): return "package '\(package)' has multiple linux main files: " + linuxMainFiles.map({ $0.description }).sorted().joined(separator: ", ") case .incompatibleToolsVersions(let package, let required, let current): if required.isEmpty { return "package '\(package)' supported Swift language versions is empty" } return "package '\(package)' requires minimum Swift language version \(required[0]) which is not supported by the current tools version (\(current))" case .targetOutsidePackage(let package, let target): return "target '\(target)' in package '\(package)' is outside the package root" case .unsupportedTargetPath(let targetPath): return "target path '\(targetPath)' is not supported; it should be relative to package root" case .invalidCustomPath(let target, let path): return "invalid custom path '\(path)' for target '\(target)'" case .invalidHeaderSearchPath(let path): return "invalid header search path '\(path)'; header search path should not be outside the package root" case .defaultLocalizationNotSet: return "manifest property 'defaultLocalization' not set; it is required in the presence of localized resources" } } } extension ModuleError.InvalidLayoutType: CustomStringConvertible { public var description: String { switch self { case .multipleSourceRoots(let paths): return "multiple source roots found: " + paths.map({ $0.description }).sorted().joined(separator: ", ") case .modulemapInSources(let path): return "modulemap '\(path)' should be inside the 'include' directory" case .modulemapMissing(let path): return "missing system target module map at '\(path)'" } } } extension Target { /// An error in the organization or configuration of an individual target. enum Error: Swift.Error { /// The target's name is invalid. case invalidName(path: RelativePath, problem: ModuleNameProblem) enum ModuleNameProblem { /// Empty target name. case emptyName } /// The target contains an invalid mix of languages (e.g. both Swift and C). case mixedSources(AbsolutePath) } } extension Target.Error: CustomStringConvertible { var description: String { switch self { case .invalidName(let path, let problem): return "invalid target name at '\(path)'; \(problem)" case .mixedSources(let path): return "target at '\(path)' contains mixed language source files; feature not supported" } } } extension Target.Error.ModuleNameProblem: CustomStringConvertible { var description: String { switch self { case .emptyName: return "target names can not be empty" } } } extension Product { /// An error in a product definition. enum Error: Swift.Error { case moduleEmpty(product: String, target: String) } } extension Product.Error: CustomStringConvertible { var description: String { switch self { case .moduleEmpty(let product, let target): return "target '\(target)' referenced in product '\(product)' is empty" } } } /// A structure representing the remote artifact information necessary to construct the package. public struct RemoteArtifact { /// The URl the artifact was downloaded from. public let url: String /// The path to the downloaded artifact. public let path: AbsolutePath public init(url: String, path: AbsolutePath) { self.url = url self.path = path } } /// Helper for constructing a package following the convention system. /// /// The 'builder' here refers to the builder pattern and not any build system /// related function. public final class PackageBuilder { /// The manifest for the package being constructed. private let manifest: Manifest /// The product filter to apply to the package. private let productFilter: ProductFilter /// The path of the package. private let packagePath: AbsolutePath /// Information concerning the different downloaded binary target artifacts. private let remoteArtifacts: [RemoteArtifact] /// The filesystem package builder will run on. private let fileSystem: FileSystem /// The diagnostics engine. private let diagnostics: DiagnosticsEngine /// Create multiple test products. /// /// If set to true, one test product will be created for each test target. private let shouldCreateMultipleTestProducts: Bool /// Create the special REPL product for this package. private let createREPLProduct: Bool /// The additionla file detection rules. private let additionalFileRules: [FileRuleDescription] /// Minimum deployment target of XCTest per platform. private let xcTestMinimumDeploymentTargets: [PackageModel.Platform:PlatformVersion] /// Create a builder for the given manifest and package `path`. /// /// - Parameters: /// - manifest: The manifest of this package. /// - path: The root path of the package. /// - artifactPaths: Paths to the downloaded binary target artifacts. /// - fileSystem: The file system on which the builder should be run. /// - diagnostics: The diagnostics engine. /// - createMultipleTestProducts: If enabled, create one test product for /// each test target. public init( manifest: Manifest, productFilter: ProductFilter, path: AbsolutePath, additionalFileRules: [FileRuleDescription] = [], remoteArtifacts: [RemoteArtifact] = [], xcTestMinimumDeploymentTargets: [PackageModel.Platform:PlatformVersion], fileSystem: FileSystem = localFileSystem, diagnostics: DiagnosticsEngine, shouldCreateMultipleTestProducts: Bool = false, createREPLProduct: Bool = false ) { self.manifest = manifest self.productFilter = productFilter self.packagePath = path self.additionalFileRules = additionalFileRules self.remoteArtifacts = remoteArtifacts self.xcTestMinimumDeploymentTargets = xcTestMinimumDeploymentTargets self.fileSystem = fileSystem self.diagnostics = diagnostics self.shouldCreateMultipleTestProducts = shouldCreateMultipleTestProducts self.createREPLProduct = createREPLProduct } /// Loads a package from a package repository using the resources associated with a particular `swiftc` executable. /// /// - Parameters: /// - packagePath: The absolute path of the package root. /// - swiftCompiler: The absolute path of a `swiftc` executable. /// Its associated resources will be used by the loader. /// - kind: The kind of package. public static func loadPackage( packagePath: AbsolutePath, swiftCompiler: AbsolutePath, xcTestMinimumDeploymentTargets: [PackageModel.Platform:PlatformVersion] = MinimumDeploymentTarget.default.xcTestMinimumDeploymentTargets, diagnostics: DiagnosticsEngine, kind: PackageReference.Kind = .root ) throws -> Package { let manifest = try ManifestLoader.loadManifest( packagePath: packagePath, swiftCompiler: swiftCompiler, packageKind: kind) let builder = PackageBuilder( manifest: manifest, productFilter: .everything, path: packagePath, xcTestMinimumDeploymentTargets: xcTestMinimumDeploymentTargets, diagnostics: diagnostics) return try builder.construct() } /// Build a new package following the conventions. public func construct() throws -> Package { let targets = try constructTargets() let products = try constructProducts(targets) // Find the special directory for targets. let targetSpecialDirs = findTargetSpecialDirs(targets) return Package( manifest: manifest, path: packagePath, targets: targets, products: products, targetSearchPath: packagePath.appending(component: targetSpecialDirs.targetDir), testTargetSearchPath: packagePath.appending(component: targetSpecialDirs.testTargetDir) ) } private func diagnosticLocation() -> DiagnosticLocation { return PackageLocation.Local(name: manifest.name, packagePath: packagePath) } /// Computes the special directory where targets are present or should be placed in future. private func findTargetSpecialDirs(_ targets: [Target]) -> (targetDir: String, testTargetDir: String) { let predefinedDirs = findPredefinedTargetDirectory() // Select the preferred tests directory. var testTargetDir = PackageBuilder.predefinedTestDirectories[0] // If found predefined test directory is not same as preferred test directory, // check if any of the test target is actually inside the predefined test directory. if predefinedDirs.testTargetDir != testTargetDir { let expectedTestsDir = packagePath.appending(component: predefinedDirs.testTargetDir) for target in targets where target.type == .test { // If yes, use the predefined test directory as preferred test directory. if expectedTestsDir == target.sources.root.parentDirectory { testTargetDir = predefinedDirs.testTargetDir break } } } return (predefinedDirs.targetDir, testTargetDir) } // MARK: Utility Predicates private func isValidSource(_ path: AbsolutePath) -> Bool { // Ignore files which don't match the expected extensions. guard let ext = path.extension, SupportedLanguageExtension.validExtensions(toolsVersion: self.manifest.toolsVersion).contains(ext) else { return false } let basename = path.basename // Ignore dotfiles. if basename.hasPrefix(".") { return false } // Ignore linux main. if basename == SwiftTarget.linuxMainBasename { return false } // Ignore paths which are not valid files. if !fileSystem.isFile(path) { // Diagnose broken symlinks. if fileSystem.isSymlink(path) { diagnostics.emit(.brokenSymlink(path), location: diagnosticLocation()) } return false } // Ignore manifest files. if path.parentDirectory == packagePath { if basename == Manifest.filename { return false } // Ignore version-specific manifest files. if basename.hasPrefix(Manifest.basename + "@") && basename.hasSuffix(".swift") { return false } } // Otherwise, we have a valid source file. return true } private func shouldConsiderDirectory(_ path: AbsolutePath) -> Bool { let base = path.basename.lowercased() if base == "tests" { return false } if base == "include" { return false } if base.hasSuffix(".xcodeproj") { return false } if base.hasSuffix(".playground") { return false } if base.hasPrefix(".") { return false } // eg .git if path == packagesDirectory { return false } if !fileSystem.isDirectory(path) { return false } return true } private var packagesDirectory: AbsolutePath { return packagePath.appending(component: "Packages") } /// Returns path to all the items in a directory. // FIXME: This is generic functionality, and should move to FileSystem. func directoryContents(_ path: AbsolutePath) throws -> [AbsolutePath] { return try fileSystem.getDirectoryContents(path).map({ path.appending(component: $0) }) } /// Private function that creates and returns a list of targets defined by a package. private func constructTargets() throws -> [Target] { // Check for a modulemap file, which indicates a system target. let moduleMapPath = packagePath.appending(component: moduleMapFilename) if fileSystem.isFile(moduleMapPath) { // Warn about any declared targets. if !manifest.targets.isEmpty { diagnostics.emit( .systemPackageDeclaresTargets(targets: Array(manifest.targets.map({ $0.name }))), location: diagnosticLocation() ) } // Emit deprecation notice. if manifest.toolsVersion >= .v4_2 { diagnostics.emit(.systemPackageDeprecation, location: diagnosticLocation()) } // Package contains a modulemap at the top level, so we assuming // it's a system library target. return [ SystemLibraryTarget( name: manifest.name, platforms: self.platforms(), path: packagePath, isImplicit: true, pkgConfig: manifest.pkgConfig, providers: manifest.providers) ] } // At this point the target can't be a system target, make sure manifest doesn't contain // system target specific configuration. guard manifest.pkgConfig == nil else { throw ModuleError.invalidManifestConfig( manifest.name, "the 'pkgConfig' property can only be used with a System Module Package") } guard manifest.providers == nil else { throw ModuleError.invalidManifestConfig( manifest.name, "the 'providers' property can only be used with a System Module Package") } return try constructV4Targets() } /// Predefined source directories, in order of preference. public static let predefinedSourceDirectories = ["Sources", "Source", "src", "srcs"] /// Predefined test directories, in order of preference. public static let predefinedTestDirectories = ["Tests", "Sources", "Source", "src", "srcs"] /// Finds the predefined directories for regular and test targets. private func findPredefinedTargetDirectory() -> (targetDir: String, testTargetDir: String) { let targetDir = PackageBuilder.predefinedSourceDirectories.first(where: { fileSystem.isDirectory(packagePath.appending(component: $0)) }) ?? PackageBuilder.predefinedSourceDirectories[0] let testTargetDir = PackageBuilder.predefinedTestDirectories.first(where: { fileSystem.isDirectory(packagePath.appending(component: $0)) }) ?? PackageBuilder.predefinedTestDirectories[0] return (targetDir, testTargetDir) } struct PredefinedTargetDirectory { let path: AbsolutePath let contents: [String] init(fs: FileSystem, path: AbsolutePath) { self.path = path self.contents = (try? fs.getDirectoryContents(path)) ?? [] } } /// Construct targets according to PackageDescription 4 conventions. fileprivate func constructV4Targets() throws -> [Target] { // Select the correct predefined directory list. let predefinedDirs = findPredefinedTargetDirectory() let predefinedTargetDirectory = PredefinedTargetDirectory(fs: fileSystem, path: packagePath.appending(component: predefinedDirs.targetDir)) let predefinedTestTargetDirectory = PredefinedTargetDirectory(fs: fileSystem, path: packagePath.appending(component: predefinedDirs.testTargetDir)) /// Returns the path of the given target. func findPath(for target: TargetDescription) throws -> AbsolutePath { // If there is a custom path defined, use that. if let subpath = target.path { if subpath == "" || subpath == "." { return packagePath } // Make sure target is not refenced by absolute path guard let relativeSubPath = try? RelativePath(validating: subpath) else { throw ModuleError.unsupportedTargetPath(subpath) } let path = packagePath.appending(relativeSubPath) // Make sure the target is inside the package root. guard path.contains(packagePath) else { throw ModuleError.targetOutsidePackage(package: manifest.name, target: target.name) } if fileSystem.isDirectory(path) { return path } throw ModuleError.invalidCustomPath(target: target.name, path: subpath) } else if target.type == .binary { if let artifact = remoteArtifacts.first(where: { $0.path.basenameWithoutExt == target.name }) { return artifact.path } else { throw ModuleError.artifactNotFound(target.name) } } // Check if target is present in the predefined directory. let predefinedDir = target.isTest ? predefinedTestTargetDirectory : predefinedTargetDirectory let path = predefinedDir.path.appending(component: target.name) // Return the path if the predefined directory contains it. if predefinedDir.contents.contains(target.name) { return path } // Otherwise, if the path "exists" then the case in manifest differs from the case on the file system. if fileSystem.isDirectory(path) { diagnostics.emit(.targetNameHasIncorrectCase(target: target.name), location: diagnosticLocation()) return path } throw ModuleError.moduleNotFound(target.name, target.type) } // Create potential targets. let potentialTargets: [PotentialModule] potentialTargets = try manifest.targetsRequired(for: productFilter).map({ target in let path = try findPath(for: target) return PotentialModule(name: target.name, path: path, type: target.type) }) return try createModules(potentialTargets) } // Create targets from the provided potential targets. private func createModules(_ potentialModules: [PotentialModule]) throws -> [Target] { // Find if manifest references a target which isn't present on disk. let allVisibleModuleNames = manifest.visibleModuleNames(for: productFilter) let potentialModulesName = Set(potentialModules.map({ $0.name })) let missingModuleNames = allVisibleModuleNames.subtracting(potentialModulesName) if let missingModuleName = missingModuleNames.first { let type = potentialModules.first(where: { $0.name == missingModuleName })?.type ?? .regular throw ModuleError.moduleNotFound(missingModuleName, type) } let potentialModuleMap = Dictionary(potentialModules.map({ ($0.name, $0) }), uniquingKeysWith: { $1 }) let successors: (PotentialModule) -> [PotentialModule] = { // No reference of this target in manifest, i.e. it has no dependencies. guard let target = self.manifest.targetMap[$0.name] else { return [] } return target.dependencies.compactMap({ switch $0 { case .target(let name, _): // Since we already checked above that all referenced targets // has to present, we always expect this target to be present in // potentialModules dictionary. return potentialModuleMap[name]! case .product: return nil case .byName(let name, _): // By name dependency may or may not be a target dependency. return potentialModuleMap[name] } }) } // Look for any cycle in the dependencies. if let cycle = findCycle(potentialModules.sorted(by: { $0.name < $1.name }), successors: successors) { throw ModuleError.cycleDetected((cycle.path.map({ $0.name }), cycle.cycle.map({ $0.name }))) } // There was no cycle so we sort the targets topologically. let potentialModules = try! topologicalSort(potentialModules, successors: successors) // The created targets mapped to their name. var targets = [String: Target]() // If a direcotry is empty, we don't create a target object for them. var emptyModules = Set<String>() // Start iterating the potential targets. for potentialModule in potentialModules.lazy.reversed() { // Validate the target name. This function will throw an error if it detects a problem. try validateModuleName(potentialModule.path, potentialModule.name, isTest: potentialModule.isTest) // Get the target from the manifest. let manifestTarget = manifest.targetMap[potentialModule.name] // Get the dependencies of this target. let dependencies: [Target.Dependency] = manifestTarget.map { $0.dependencies.compactMap { dependency in switch dependency { case .target(let name, let condition): // We don't create an object for targets which have no sources. if emptyModules.contains(name) { return nil } guard let target = targets[name] else { return nil } return .target(target, conditions: buildConditions(from: condition)) case .product(let name, let package, let condition): return .product( .init(name: name, package: package), conditions: buildConditions(from: condition) ) case .byName(let name, let condition): // We don't create an object for targets which have no sources. if emptyModules.contains(name) { return nil } if let target = targets[name] { return .target(target, conditions: buildConditions(from: condition)) } else if potentialModuleMap[name] == nil { return .product( .init(name: name, package: nil), conditions: buildConditions(from: condition) ) } else { return nil } } } } ?? [] // Create the target. let target = try createTarget( potentialModule: potentialModule, manifestTarget: manifestTarget, dependencies: dependencies ) // Add the created target to the map or print no sources warning. if let createdTarget = target { targets[createdTarget.name] = createdTarget } else { emptyModules.insert(potentialModule.name) diagnostics.emit(.targetHasNoSources(targetPath: potentialModule.path.pathString, target: potentialModule.name)) } } return targets.values.map{ $0 }.sorted{ $0.name > $1.name } } /// Private function that checks whether a target name is valid. This method doesn't return anything, but rather, /// if there's a problem, it throws an error describing what the problem is. private func validateModuleName(_ path: AbsolutePath, _ name: String, isTest: Bool) throws { if name.isEmpty { throw Target.Error.invalidName( path: path.relative(to: packagePath), problem: .emptyName) } } /// Private function that constructs a single Target object for the potential target. private func createTarget( potentialModule: PotentialModule, manifestTarget: TargetDescription?, dependencies: [Target.Dependency] ) throws -> Target? { guard let manifestTarget = manifestTarget else { return nil } // Create system library target. if potentialModule.type == .system { let moduleMapPath = potentialModule.path.appending(component: moduleMapFilename) guard fileSystem.isFile(moduleMapPath) else { throw ModuleError.invalidLayout(.modulemapMissing(moduleMapPath)) } return SystemLibraryTarget( name: potentialModule.name, platforms: self.platforms(), path: potentialModule.path, isImplicit: false, pkgConfig: manifestTarget.pkgConfig, providers: manifestTarget.providers ) } else if potentialModule.type == .binary { let remoteURL = remoteArtifacts.first(where: { $0.path == potentialModule.path }) let artifactSource: BinaryTarget.ArtifactSource = remoteURL.map({ .remote(url: $0.url) }) ?? .local return BinaryTarget( name: potentialModule.name, platforms: self.platforms(), path: potentialModule.path, artifactSource: artifactSource ) } // Check for duplicate target dependencies by name let combinedDependencyNames = dependencies.map { $0.target?.name ?? $0.product!.name } combinedDependencyNames.spm_findDuplicates().forEach { diagnostics.emit(.duplicateTargetDependency(dependency: $0, target: potentialModule.name)) } // Create the build setting assignment table for this target. let buildSettings = try self.buildSettings(for: manifestTarget, targetRoot: potentialModule.path) // Compute the path to public headers directory. let publicHeaderComponent = manifestTarget.publicHeadersPath ?? ClangTarget.defaultPublicHeadersComponent let publicHeadersPath = potentialModule.path.appending(try RelativePath(validating: publicHeaderComponent)) guard publicHeadersPath.contains(potentialModule.path) else { throw ModuleError.invalidPublicHeadersDirectory(potentialModule.name) } let sourcesBuilder = TargetSourcesBuilder( packageName: manifest.name, packagePath: packagePath, target: manifestTarget, path: potentialModule.path, defaultLocalization: manifest.defaultLocalization, additionalFileRules: additionalFileRules, toolsVersion: manifest.toolsVersion, fs: fileSystem, diags: diagnostics ) let (sources, resources, headers) = try sourcesBuilder.run() // Make sure defaultLocalization is set if the target has localized resources. let hasLocalizedResources = resources.contains(where: { $0.localization != nil }) if hasLocalizedResources && manifest.defaultLocalization == nil { throw ModuleError.defaultLocalizationNotSet } // The name of the bundle, if one is being generated. let bundleName = resources.isEmpty ? nil : manifest.name + "_" + potentialModule.name if sources.relativePaths.isEmpty && resources.isEmpty { return nil } try validateSourcesOverlapping(forTarget: potentialModule.name, sources: sources.paths) // Create and return the right kind of target depending on what kind of sources we found. if sources.hasSwiftSources { return SwiftTarget( name: potentialModule.name, bundleName: bundleName, defaultLocalization: manifest.defaultLocalization, platforms: self.platforms(isTest: potentialModule.isTest), isTest: potentialModule.isTest, sources: sources, resources: resources, dependencies: dependencies, swiftVersion: try swiftVersion(), buildSettings: buildSettings ) } else { // It's not a Swift target, so it's a Clang target (those are the only two types of source target currently supported). // First determine the type of module map that will be appropriate for the target based on its header layout. // FIXME: We should really be checking the target type to see whether it is one that can vend headers, not just check for the existence of the public headers path. But right now we have now way of distinguishing between, for example, a library and an executable. The semantics here should be to only try to detect the header layout of targets that can vend public headers. let moduleMapType: ModuleMapType if fileSystem.exists(publicHeadersPath) { let moduleMapGenerator = ModuleMapGenerator(targetName: potentialModule.name, moduleName: potentialModule.name.spm_mangledToC99ExtendedIdentifier(), publicHeadersDir: publicHeadersPath, fileSystem: fileSystem) moduleMapType = moduleMapGenerator.determineModuleMapType(diagnostics: diagnostics) } else { moduleMapType = .none } return ClangTarget( name: potentialModule.name, bundleName: bundleName, defaultLocalization: manifest.defaultLocalization, platforms: self.platforms(isTest: potentialModule.isTest), cLanguageStandard: manifest.cLanguageStandard, cxxLanguageStandard: manifest.cxxLanguageStandard, includeDir: publicHeadersPath, moduleMapType: moduleMapType, headers: headers, isTest: potentialModule.isTest, sources: sources, resources: resources, dependencies: dependencies, buildSettings: buildSettings ) } } /// Creates build setting assignment table for the given target. func buildSettings(for target: TargetDescription?, targetRoot: AbsolutePath) throws -> BuildSettings.AssignmentTable { var table = BuildSettings.AssignmentTable() guard let target = target else { return table } // Process each setting. for setting in target.settings { let decl: BuildSettings.Declaration // Compute appropriate declaration for the setting. switch setting.name { case .headerSearchPath: switch setting.tool { case .c, .cxx: decl = .HEADER_SEARCH_PATHS case .swift, .linker: fatalError("unexpected tool for setting type \(setting)") } // Ensure that the search path is contained within the package. let subpath = try RelativePath(validating: setting.value[0]) guard targetRoot.appending(subpath).contains(packagePath) else { throw ModuleError.invalidHeaderSearchPath(subpath.pathString) } case .define: switch setting.tool { case .c, .cxx: decl = .GCC_PREPROCESSOR_DEFINITIONS case .swift: decl = .SWIFT_ACTIVE_COMPILATION_CONDITIONS case .linker: fatalError("unexpected tool for setting type \(setting)") } case .linkedLibrary: switch setting.tool { case .c, .cxx, .swift: fatalError("unexpected tool for setting type \(setting)") case .linker: decl = .LINK_LIBRARIES } case .linkedFramework: switch setting.tool { case .c, .cxx, .swift: fatalError("unexpected tool for setting type \(setting)") case .linker: decl = .LINK_FRAMEWORKS } case .unsafeFlags: switch setting.tool { case .c: decl = .OTHER_CFLAGS case .cxx: decl = .OTHER_CPLUSPLUSFLAGS case .swift: decl = .OTHER_SWIFT_FLAGS case .linker: decl = .OTHER_LDFLAGS } } // Create an assignment for this setting. var assignment = BuildSettings.Assignment() assignment.value = setting.value assignment.conditions = buildConditions(from: setting.condition) // Finally, add the assignment to the assignment table. table.add(assignment, for: decl) } return table } func buildConditions(from condition: PackageConditionDescription?) -> [PackageConditionProtocol] { var conditions: [PackageConditionProtocol] = [] if let config = condition?.config.flatMap({ BuildConfiguration(rawValue: $0) }) { let condition = ConfigurationCondition(configuration: config) conditions.append(condition) } if let platforms = condition?.platformNames.compactMap({ platformRegistry.platformByName[$0] }), !platforms.isEmpty { let condition = PlatformsCondition(platforms: platforms) conditions.append(condition) } return conditions } /// Returns the list of platforms supported by the manifest. func platforms(isTest: Bool = false) -> [SupportedPlatform] { if let platforms = _platforms[isTest] { return platforms } var supportedPlatforms: [SupportedPlatform] = [] /// Add each declared platform to the supported platforms list. for platform in manifest.platforms { let declaredPlatform = platformRegistry.platformByName[platform.platformName]! var version = PlatformVersion(platform.version) if let xcTestMinimumDeploymentTarget = xcTestMinimumDeploymentTargets[declaredPlatform], isTest, version < xcTestMinimumDeploymentTarget { version = xcTestMinimumDeploymentTarget } let supportedPlatform = SupportedPlatform( platform: declaredPlatform, version: version, options: platform.options ) supportedPlatforms.append(supportedPlatform) } // Find the undeclared platforms. let remainingPlatforms = Set(platformRegistry.platformByName.keys).subtracting(supportedPlatforms.map({ $0.platform.name })) /// Start synthesizing for each undeclared platform. for platformName in remainingPlatforms.sorted() { let platform = platformRegistry.platformByName[platformName]! let oldestSupportedVersion: PlatformVersion if let xcTestMinimumDeploymentTarget = xcTestMinimumDeploymentTargets[platform], isTest { oldestSupportedVersion = xcTestMinimumDeploymentTarget } else { oldestSupportedVersion = platform.oldestSupportedVersion } let supportedPlatform = SupportedPlatform( platform: platform, version: oldestSupportedVersion, options: [] ) supportedPlatforms.append(supportedPlatform) } _platforms[isTest] = supportedPlatforms return supportedPlatforms } // Keep two sets of supported platforms, based on the `isTest` parameter. private var _platforms = [Bool:[SupportedPlatform]]() /// The platform registry instance. private var platformRegistry: PlatformRegistry { return PlatformRegistry.default } /// Computes the swift version to use for this manifest. private func swiftVersion() throws -> SwiftLanguageVersion { if let swiftVersion = _swiftVersion { return swiftVersion } let computedSwiftVersion: SwiftLanguageVersion // Figure out the swift version from declared list in the manifest. if let swiftLanguageVersions = manifest.swiftLanguageVersions { guard let swiftVersion = swiftLanguageVersions.sorted(by: >).first(where: { $0 <= ToolsVersion.currentToolsVersion }) else { throw ModuleError.incompatibleToolsVersions( package: manifest.name, required: swiftLanguageVersions, current: .currentToolsVersion) } computedSwiftVersion = swiftVersion } else { // Otherwise, use the version depending on the manifest version. computedSwiftVersion = manifest.toolsVersion.swiftLanguageVersion } _swiftVersion = computedSwiftVersion return computedSwiftVersion } private var _swiftVersion: SwiftLanguageVersion? = nil /// The set of the sources computed so far. private var allSources = Set<AbsolutePath>() /// Validates that the sources of a target are not already present in another target. private func validateSourcesOverlapping(forTarget target: String, sources: [AbsolutePath]) throws { // Compute the sources which overlap with already computed targets. var overlappingSources: Set<AbsolutePath> = [] for source in sources { if !allSources.insert(source).inserted { overlappingSources.insert(source) } } // Throw if we found any overlapping sources. if !overlappingSources.isEmpty { throw ModuleError.overlappingSources(target: target, sources: Array(overlappingSources)) } } /// Find the linux main file for the package. private func findLinuxMain(in testTargets: [Target]) throws -> AbsolutePath? { var linuxMainFiles = Set<AbsolutePath>() var pathsSearched = Set<AbsolutePath>() // Look for linux main file adjacent to each test target root, iterating upto package root. for target in testTargets { // Form the initial search path. // // If the target root's parent directory is inside the package, start // search there. Otherwise, we start search from the target root. var searchPath = target.sources.root.parentDirectory if !searchPath.contains(packagePath) { searchPath = target.sources.root } while true { assert(searchPath.contains(packagePath), "search path \(searchPath) is outside the package \(packagePath)") // If we have already searched this path, skip. if !pathsSearched.contains(searchPath) { let linuxMain = searchPath.appending(component: SwiftTarget.linuxMainBasename) if fileSystem.isFile(linuxMain) { linuxMainFiles.insert(linuxMain) } pathsSearched.insert(searchPath) } // Break if we reached all the way to package root. if searchPath == packagePath { break } // Go one level up. searchPath = searchPath.parentDirectory } } // It is an error if there are multiple linux main files. if linuxMainFiles.count > 1 { throw ModuleError.multipleLinuxMainFound( package: manifest.name, linuxMainFiles: linuxMainFiles.map({ $0 })) } return linuxMainFiles.first } /// Collects the products defined by a package. private func constructProducts(_ targets: [Target]) throws -> [Product] { var products = OrderedSet<KeyedPair<Product, String>>() /// Helper method to append to products array. func append(_ product: Product) { let inserted = products.append(KeyedPair(product, key: product.name)) if !inserted { diagnostics.emit( .duplicateProduct(product: product), location: diagnosticLocation() ) } } // Collect all test targets. let testModules = targets.filter({ target in guard target.type == .test else { return false } #if os(Linux) // FIXME: Ignore C language test targets on linux for now. if target is ClangTarget { diagnostics.emit(.unsupportedCTestTarget( package: manifest.name, target: target.name)) return false } #endif return true }) // If enabled, create one test product for each test target. if shouldCreateMultipleTestProducts { for testTarget in testModules { let product = Product(name: testTarget.name, type: .test, targets: [testTarget]) append(product) } } else if !testModules.isEmpty { // Otherwise we only need to create one test product for all of the // test targets. // // Add suffix 'PackageTests' to test product name so the target name // of linux executable don't collide with main package, if present. let productName = manifest.name + "PackageTests" let linuxMain = try findLinuxMain(in: testModules) let product = Product( name: productName, type: .test, targets: testModules, linuxMain: linuxMain) append(product) } // Map containing targets mapped to their names. let modulesMap = Dictionary(targets.map({ ($0.name, $0) }), uniquingKeysWith: { $1 }) /// Helper method to get targets from target names. func modulesFrom(targetNames names: [String], product: String) throws -> [Target] { // Get targets from target names. return try names.map({ targetName in // Ensure we have this target. guard let target = modulesMap[targetName] else { throw Product.Error.moduleEmpty(product: product, target: targetName) } return target }) } // Only create implicit executables for root packages. if manifest.packageKind == .root { // Compute the list of targets which are being used in an // executable product so we don't create implicit executables // for them. let executableProductTargets = manifest.products.flatMap({ product -> [String] in switch product.type { case .library, .test: return [] case .executable: return product.targets } }) let declaredProductsTargets = Set(executableProductTargets) for target in targets where target.type == .executable { // If this target already has an executable product, skip // generating a product for it. if declaredProductsTargets.contains(target.name) { continue } let product = Product(name: target.name, type: .executable, targets: [target]) append(product) } } let filteredProducts: [ProductDescription] switch productFilter { case .everything: filteredProducts = manifest.products case .specific(let set): filteredProducts = manifest.products.filter { set.contains($0.name) } } for product in filteredProducts { let targets = try modulesFrom(targetNames: product.targets, product: product.name) // Peform special validations if this product is exporting // a system library target. if targets.contains(where: { $0 is SystemLibraryTarget }) { if product.type != .library(.automatic) || targets.count != 1 { diagnostics.emit( .systemPackageProductValidation(product: product.name), location: diagnosticLocation() ) continue } } // Do some validation for executable products. switch product.type { case .library, .test: break case .executable: guard validateExecutableProduct(product, with: targets) else { continue } } append(Product(name: product.name, type: product.type, targets: targets)) } // Create a special REPL product that contains all the library targets. if createREPLProduct { let libraryTargets = targets.filter({ $0.type == .library }) if libraryTargets.isEmpty { diagnostics.emit( .noLibraryTargetsForREPL, location: diagnosticLocation() ) } else { let replProduct = Product( name: manifest.name + Product.replProductSuffix, type: .library(.dynamic), targets: libraryTargets ) append(replProduct) } } return products.map({ $0.item }) } private func validateExecutableProduct(_ product: ProductDescription, with targets: [Target]) -> Bool { let executableTargetCount = targets.filter { $0.type == .executable }.count guard executableTargetCount == 1 else { if executableTargetCount == 0 { if let target = targets.spm_only { diagnostics.emit( .executableProductTargetNotExecutable(product: product.name, target: target.name), location: diagnosticLocation() ) } else { diagnostics.emit( .executableProductWithoutExecutableTarget(product: product.name), location: diagnosticLocation() ) } } else { diagnostics.emit( .executableProductWithMoreThanOneExecutableTarget(product: product.name), location: diagnosticLocation() ) } return false } return true } } /// We create this structure after scanning the filesystem for potential targets. private struct PotentialModule: Hashable { /// Name of the target. let name: String /// The path of the target. let path: AbsolutePath /// If this should be a test target. var isTest: Bool { return type == .test } /// The target type. let type: TargetDescription.TargetType /// The base prefix for the test target, used to associate with the target it tests. public var basename: String { guard isTest else { fatalError("\(Swift.type(of: self)) should be a test target to access basename.") } precondition(name.hasSuffix(Target.testModuleNameSuffix)) let endIndex = name.index(name.endIndex, offsetBy: -Target.testModuleNameSuffix.count) return String(name[name.startIndex..<endIndex]) } } private extension Manifest { /// Returns the names of all the visible targets in the manifest. func visibleModuleNames(for productFilter: ProductFilter) -> Set<String> { let names = targetsRequired(for: productFilter).flatMap({ target in [target.name] + target.dependencies.compactMap({ switch $0 { case .target(let name, _): return name case .byName, .product: return nil } }) }) return Set(names) } } extension Sources { var hasSwiftSources: Bool { paths.first?.extension == "swift" } var containsMixedLanguage: Bool { let swiftSources = relativePaths.filter{ $0.extension == "swift" } if swiftSources.isEmpty { return false } return swiftSources.count != relativePaths.count } }
42.413655
386
0.616817
ac4c763b7e3d54ee1646f1c0ab4f80abaeca489f
1,788
// // MIT License // // Copyright (c) 2021 Tamerlan Satualdypov // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation protocol ErrorPresenterProtocol { func viewDidLoad() -> () init(view : ErrorViewControllerProtocol, error : NetworkError) } final class ErrorPresenter : ErrorPresenterProtocol { private weak var view: ErrorViewControllerProtocol? private var error: NetworkError public func viewDidLoad() -> () { self.view?.set(image: self.error.image) self.view?.set(title: self.error.title) self.view?.set(message: self.error.message) } init(view: ErrorViewControllerProtocol, error: NetworkError) { self.view = view self.error = error } }
38.869565
82
0.723154
1e3558f05fce54b17c079a2f1e6e99f96f5477c9
1,580
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. import Foundation import azureSwiftRuntime internal struct ActivityLogAlertAllOfConditionData : ActivityLogAlertAllOfConditionProtocol { public var allOf: [ActivityLogAlertLeafConditionProtocol] enum CodingKeys: String, CodingKey {case allOf = "allOf" } public init(allOf: [ActivityLogAlertLeafConditionProtocol]) { self.allOf = allOf } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.allOf = try container.decode([ActivityLogAlertLeafConditionData].self, forKey: .allOf) if var pageDecoder = decoder as? PageDecoder { if pageDecoder.isPagedData, let nextLinkName = pageDecoder.nextLinkName { pageDecoder.nextLink = try UnknownCodingKey.decodeStringForKey(decoder: decoder, keyForDecode: nextLinkName) } } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.allOf as! [ActivityLogAlertLeafConditionData], forKey: .allOf) } } extension DataFactory { public static func createActivityLogAlertAllOfConditionProtocol(allOf: [ActivityLogAlertLeafConditionProtocol]) -> ActivityLogAlertAllOfConditionProtocol { return ActivityLogAlertAllOfConditionData(allOf: allOf) } }
40.512821
158
0.744937
2f7060331d7d1675f34ee89b3683230fb58e71b6
1,475
// // TestCell.swift // Twittient // // Created by TriNgo on 3/29/16. // Copyright © 2016 TriNgo. All rights reserved. // import UIKit @objc protocol TweetCellDelegate:class{ optional func tweetCell(onReplyClicked tweetCell: TweetCell) optional func tweetCell(onRetweetClicked tweetCell: TweetCell) optional func tweetCell(onLikeClicked tweetCell: TweetCell) } class TweetCell: UITableViewCell { @IBOutlet weak var avatar: UIImageView! @IBOutlet weak var name: UILabel! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var screenNameLabel: UILabel! @IBOutlet weak var timeagoLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var retweetButton: UIButton! weak var delegate: TweetCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code avatar.layer.cornerRadius = 3.0 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } @IBAction func onReplyClicked(sender: UIButton) { delegate?.tweetCell!(onReplyClicked: self) } @IBAction func onRetweetClicked(sender: UIButton) { delegate?.tweetCell!(onRetweetClicked: self) } @IBAction func onLikeClicked(sender: UIButton) { delegate?.tweetCell!(onLikeClicked: self) } }
27.830189
66
0.686102
266c35258113a50ff4085eb435540dacb95c7c0c
1,398
#if arch(x86_64) || arch(arm64) import Combine import SwiftUI // sourcery: AutoMockable @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) protocol RadiusInteractable: AnyObject { var presenter: RadiusPresenter { get } var animation: CurrentValueSubject<Animation?, Never> { get } var value: CurrentValueSubject<CGFloat, Never> { get } var range: CurrentValueSubject<ClosedRange<CGFloat>, Never> { get } } @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) final class RadiusInteractor: RadiusInteractable { let presenter = RadiusPresenter() let animation: CurrentValueSubject<Animation?, Never> let value: CurrentValueSubject<CGFloat, Never> let range: CurrentValueSubject<ClosedRange<CGFloat>, Never> private var cancellables = Set<AnyCancellable>() init() { value = CurrentValueSubject<CGFloat, Never>(presenter.value) animation = CurrentValueSubject<Animation?, Never>(presenter.animation) range = CurrentValueSubject<ClosedRange<CGFloat>, Never>(presenter.range) range.assign(to: \.range, on: presenter).store(in: &cancellables) value.assign(to: \.value, on: presenter).store(in: &cancellables) animation.assign(to: \.animation, on: presenter).store(in: &cancellables) range.map { $0.lowerBound }.assign(to: \.value, on: presenter).store(in: &cancellables) } } #endif
39.942857
95
0.7103
4807064760f430f1fa8c8f7c8ba11fbc33a86bec
6,443
// // RightButtonField.swift // PullDownListSwiftDemo // // Created by iMAC on 2020/8/7. // Copyright © 2020 xwj. All rights reserved. // import UIKit private let screenHeight = UIScreen.main.bounds.height public typealias TextFieldButtonClick = (Bool) -> Void public typealias TextItemBlock = (Bool,Int,String) -> Void/*Bool值为是否删除行事件*/ public class RightButtonField: UITextField,UITextFieldDelegate { //右边按钮相关 public var rightBtnClick:TextFieldButtonClick? public var imageName:String = ""{ didSet{ imageView?.setImage(UIImage(named: imageName), for: .normal) } } public var rightViewW:CGFloat = 45 public var rightViewH:CGFloat = 40 /*列表相关*/ //点击选项回调 public var itemBlock:TextItemBlock? //是否显示删除小按钮 public var showDelete:Bool = true //选项高度 public var itemHeight:CGFloat = 40.0 //固定视图高度,不设置根据itemHeight计算高度 public var selectViewHeight:CGFloat = 0 //选项的文字大小 public var iTextFont:UIFont? //选项的文字颜色 public var iTextColor:UIColor? //选项的背景色 public var itemBgColor:UIColor? //视图的边框颜色 public var iBorderColor:UIColor? //视图的边框大小 public var iBorderWidth:CGFloat = 0 //视图的圆角大小 public var iCornerRadius:CGFloat = 0 private var imageView:UIButton? private var deleteBtn:UIButton! private var tableView:UITableView? private static let listCellId:String = "listCellId" private var lists:[String]? /// 创建右侧按钮 /// - Parameter imageName: 右侧按钮图片名 public func createRightView(imageName:String) { createRightView(image: UIImage(named: imageName)) } /// 创建右侧按钮 /// - Parameter image: 右侧按钮图片 public func createRightView(image:UIImage?) { self.addTarget(self, action: #selector(beginEdit), for: .editingDidBegin) self.addTarget(self, action: #selector(endEdit), for: .editingDidEnd) rightViewMode = .always font = .systemFont(ofSize: 15) let rightViews = UIView(frame: CGRect(x: 0, y: 0, width: rightViewW, height: rightViewH)) deleteBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: rightViewH))//UIImage(named: "pullDownListSwift.bundle/textDelete_btn") deleteBtn.setImage(getBundleImage(name: "textDelete_btn"), for: .normal) deleteBtn.addTarget(self, action: #selector(deleteClick), for: .touchUpInside) deleteBtn.isHidden = true imageView = UIButton(frame: CGRect(x: 20, y: 0, width: rightViewW - 20 , height: rightViewH)) imageView?.addTarget(self, action: #selector(click(button:)), for: .touchUpInside) imageView?.setImage(image, for: .normal) rightViews.addSubview(deleteBtn) rightViews.addSubview(imageView!) rightView = rightViews let line = UIView() line.backgroundColor = .black self.addSubview(line) line.frame = CGRect(x: 0, y: frame.size.height, width: frame.size.width, height: 0.5) } @objc public func deleteClick(){ self.text = "" } @objc func click(button:UIButton) { button.isSelected = !button.isSelected if let btnClick = rightBtnClick { btnClick(button.isSelected) } } @objc func beginEdit() { deleteBtn.isHidden = false } @objc func endEdit() { deleteBtn.isHidden = true } /// 创建下拉列表 /// - Parameter data: 下拉列表数据 public func createTableView(data:[String]) { lists = data tableView = UITableView() tableView?.delegate = self tableView?.dataSource = self tableView?.backgroundColor = .white tableView?.layer.cornerRadius = iCornerRadius tableView?.layer.masksToBounds = true tableView?.layer.borderWidth = iBorderWidth tableView?.layer.borderColor = iBorderColor?.cgColor tableView?.register(TextFieldSelectCell.classForCoder(), forCellReuseIdentifier: RightButtonField.listCellId) if let window = UIApplication.shared.keyWindow{ let fra = self.convert(bounds, to: window) tableView?.frame = CGRect(x: fra.origin.x, y: fra.origin.y + fra.size.height + 1, width: fra.size.width, height:0) window.addSubview(tableView!) var tableViewH:CGFloat = (selectViewHeight > 0) ? selectViewHeight : CGFloat(self.lists?.count ?? 0) * itemHeight if tableViewH > screenHeight - frame.origin.y - frame.size.height { tableViewH = screenHeight - frame.origin.y - frame.size.height } UIView.animate(withDuration: 0.25) { self.tableView?.frame.size.height = tableViewH } } } //移除列表视图 public func removeTableView() { UIView.animate(withDuration: 0.25, animations: { self.tableView?.frame.size.height = 0 }) { (compet) in self.tableView?.removeFromSuperview() self.tableView = nil } } } extension RightButtonField: UITableViewDelegate,UITableViewDataSource{ public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lists?.count ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: RightButtonField.listCellId) as? TextFieldSelectCell if cell == nil { cell = TextFieldSelectCell() } cell?.title = lists?[indexPath.row] ?? "" cell?.showDelete = showDelete cell?.iTextFont = iTextFont cell?.iTextColor = iTextColor cell?.backgroundColor = itemBgColor cell?.cellDeleteClick = { [unowned self]() in let txt = self.lists?.remove(at: indexPath.row) self.tableView?.reloadData() if let sel = self.itemBlock { sel(true,indexPath.row,txt ?? "") } } return cell! } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return itemHeight } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { text = lists?[indexPath.row] click(button: imageView!) if let sel = itemBlock { sel(false,indexPath.row,text ?? "") } } }
35.994413
145
0.635884
23d7e8c4f7a213e59c94ac4423aeb615cb3fb4c9
12,279
// // MultipleExtensions.swift // ZingDriverBeta // // Created by Bhavneet Singh on 26/03/18. // Copyright © 2018 Bhavneet Singh. All rights reserved. // import Foundation import UIKit import Kingfisher import Photos extension PHAsset { func requestAVAsset() -> AVAsset? { // We only want videos here guard self.mediaType == .video else { return nil } // Create your semaphore and allow only one thread to access it let semaphore = DispatchSemaphore.init(value: 1) let imageManager = PHImageManager() var avAsset: AVAsset? // Lock the thread with the wait() command semaphore.wait() // Now go fetch the AVAsset for the given PHAsset imageManager.requestAVAsset(forVideo: self, options: nil) { (asset, _, _) in // Save your asset to the earlier place holder avAsset = asset // We're done, let the semaphore know it can unlock now semaphore.signal() } return avAsset } } extension UILabel { func calculateMaxLines() -> Int { let maxSize = CGSize(width: frame.size.width, height: CGFloat(Float.infinity)) let charSize = font.lineHeight let text = (self.text ?? "") as NSString let textSize = text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) let lines = Int(textSize.height/charSize) return lines } } extension Data { var html2AttributedString: NSAttributedString? { do { return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { print("error:", error) return nil } } var html2String: String { return html2AttributedString?.string ?? "" } } extension CGPoint { /// Return false if x or y is negative var isValid: Bool { if self.x < 0 || self.y < 0 { return false } return true } } extension UITextView { ///Returns Number of Lines public var numberOfLines: Int { let layoutManager = self.layoutManager let numberOfGlyphs = layoutManager.numberOfGlyphs var lineRange: NSRange = NSMakeRange(0, 1) var index = 0 var numberOfLines = 0 while index < numberOfGlyphs { layoutManager.lineFragmentRect( forGlyphAt: index, effectiveRange: &lineRange ) index = NSMaxRange(lineRange) numberOfLines += 1 } return numberOfLines } } struct GradientPoint { var location: NSNumber var color: UIColor } extension UINavigationController { /// Set gradient background color on the navigation bar. func setBarBackground(gradientColors: [GradientPoint], isHorizontal: Bool) { let img = UIImage(size: CGSize(width: UIScreen.main.bounds.width, height: self.navigationBar.frame.height), gradientPoints: gradientColors, isHorizontal: isHorizontal) self.navigationBar.setBackgroundImage(img, for: UIBarMetrics.default) self.navigationBar.barTintColor = .clear self.navigationBar.backgroundColor = .clear } /// Set background color on the navigation bar. func setBarBackground(color: UIColor) { if color.cgColor.alpha < 1 { self.navigationBar.setBackgroundImage(UIImage(color: color), for: UIBarMetrics.default) self.navigationBar.barTintColor = .clear self.navigationBar.backgroundColor = .clear } else { self.navigationBar.barTintColor = color self.navigationBar.backgroundColor = color self.navigationBar.setBackgroundImage(nil, for: .default) } } /// Set background image on the navigation bar. func setBarBackground(image: UIImage) { self.navigationBar.setBackgroundImage(image, for: UIBarMetrics.default) } /// Set shadow color for the navigation bar. func setBarShadow(color: UIColor) { self.navigationBar.shadowImage = UIImage(color: color) } /// Set shadow image for the navigation bar. func setBarShadow(image: UIImage) { self.navigationBar.shadowImage = image } } extension UIViewController { /// Set attributed title for the navigation bar. func setAttributedTitle(with alignment: NSTextAlignment = .natural, title: NSAttributedString) { let titleLabel = UILabel() titleLabel.sizeToFit() titleLabel.numberOfLines = 0 titleLabel.attributedText = title titleLabel.textAlignment = alignment if alignment != .justified && alignment != .natural { titleLabel.frame.size.width = UIScreen.main.bounds.width } else { titleLabel.frame.size = titleLabel.intrinsicContentSize titleLabel.frame.size.height = 44 } self.title = nil self.navigationItem.titleView = titleLabel } } extension UIImage { convenience init(color: UIColor) { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() if let cgimg = img?.cgImage { self.init(cgImage: cgimg) } else { self.init() } } convenience init?(size: CGSize, gradientPoints: [GradientPoint], isHorizontal: Bool = true) { UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } // If the size is zero, the context will be nil. guard let gradient = CGGradient(colorSpace: CGColorSpaceCreateDeviceRGB(), colorComponents: gradientPoints.compactMap { $0.color.cgColor.components }.flatMap { $0 }, locations: gradientPoints.map { CGFloat(truncating: $0.location) }, count: gradientPoints.count) else { return nil } var transformedStartPoint = CGPoint() var transformedEndPoint = CGPoint() if isHorizontal { transformedStartPoint = CGPoint.zero transformedEndPoint = CGPoint(x: size.width, y: 0) } else { transformedStartPoint = CGPoint.zero transformedEndPoint = CGPoint(x: 0, y: size.height) } context.drawLinearGradient(gradient, start: transformedStartPoint, end: transformedEndPoint, options: CGGradientDrawingOptions()) guard let image = UIGraphicsGetImageFromCurrentImageContext()?.cgImage else { return nil } self.init(cgImage: image) defer { UIGraphicsEndImageContext() } } } extension UIImageView { func gradated(gradientPoints: [GradientPoint]) { let gradientMaskLayer = CAGradientLayer() gradientMaskLayer.frame = frame gradientMaskLayer.colors = gradientPoints.map { $0.color.cgColor } gradientMaskLayer.locations = gradientPoints.map { $0.location as NSNumber } self.layer.insertSublayer(gradientMaskLayer, at: 0) } } extension UIImage { func scaleImage(toSize newSize: CGSize?, scale : CGFloat = 0) -> UIImage? { let newSize = newSize ?? self.size let rect: CGRect = CGRect(x: 0.0, y: 0.0, width: newSize.width, height: newSize.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, scale) self.draw(in: rect) if let image = UIGraphicsGetImageFromCurrentImageContext(), let imageData = UIImagePNGRepresentation(image) { return UIImage(data: imageData) } UIGraphicsEndImageContext() return nil } var circleMasked: UIImage? { let newImage = self.copy() as! UIImage let cornerRadius = self.size.height/2 UIGraphicsBeginImageContextWithOptions(self.size, false, 0) let bounds = CGRect(origin: CGPoint.zero, size: self.size) UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).addClip() newImage.draw(in: bounds) let finalImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return finalImage } var squareImage : UIImage? { var imageHeight = self.size.height var imageWidth = self.size.width if imageHeight > imageWidth { imageHeight = imageWidth } else { imageWidth = imageHeight } let size = CGSize(width: imageWidth, height: imageHeight) let refWidth : CGFloat = CGFloat(self.cgImage!.width) let refHeight : CGFloat = CGFloat(self.cgImage!.height) let x = (refWidth - size.width) / 2 let y = (refHeight - size.height) / 2 let cropRect = CGRect(x: x, y: y, width: size.height, height: size.width) if let imageRef = self.cgImage!.cropping(to: cropRect) { return UIImage(cgImage: imageRef, scale: 0, orientation: self.imageOrientation) } return nil } /** Resize and make circular image to fit into annotation image */ var createAnnoatationImage : UIImage { guard let sqaureImage = self.squareImage else {return #imageLiteral(resourceName: "icDriverRequestComingLocation")} guard let circleImage = sqaureImage.circleMasked else {return #imageLiteral(resourceName: "icDriverRequestComingLocation")} let imageSize = CGSize(width: 33, height: 50) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) let pinImage = #imageLiteral(resourceName: "icDriverRequestComingLocation") pinImage.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize)) let imageRect = CGRect(x: 4.5, y: 4, width: 23.7, height: 25) circleImage.draw(in: imageRect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result ?? pinImage } func createAnnotationImage(url: String, imageCompletion: @escaping (_ img: UIImage) -> ()) { if let urlString = URL(string: url) { KingfisherManager.shared.retrieveImage(with: urlString, options: nil, progressBlock: { (start, end) in }) { (imageFile, error, cacheType, url) in guard let img = imageFile, error == nil else { imageCompletion(#imageLiteral(resourceName: "icDriverRequestComingLocation")) return } guard let sqaureImage = img.squareImage else { imageCompletion(#imageLiteral(resourceName: "icDriverRequestComingLocation")) return } guard let circleImage = sqaureImage.circleMasked else { imageCompletion(#imageLiteral(resourceName: "icDriverRequestComingLocation")) return } let imageSize = CGSize(width: 33, height: 50) UIGraphicsBeginImageContextWithOptions(imageSize, false, 0) let pinImage = #imageLiteral(resourceName: "icDriverRequestComingLocation") pinImage.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize)) let imageRect = CGRect(x: 4.5, y: 4, width: 23.7, height: 25) circleImage.draw(in: imageRect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() imageCompletion(result ?? pinImage) } } else { imageCompletion(#imageLiteral(resourceName: "icDriverRequestComingLocation")) return } } }
37.322188
277
0.622038
757c938b40505d7c2c455144955df9659ca63694
6,135
// // NetworkServiceImpl.swift // HasbroTransformers // // Created by Dhawal on 06/12/20. // Copyright © 2020 Dhawal. All rights reserved. // import Foundation class NetworkServiceImpl: NetworkService { enum HearderConstants { enum Keys { static let authorization = "Authorization" static let contentType = "Content-Type" } enum Values { static let contentType = "application/json" static func authorization(token: String) -> String { "Bearer \(token)" } } } private let urlSession: URLSession init(urlSession: URLSession) { self.urlSession = urlSession } func execute( url: URL, method: HTTPMethod, completion: @escaping (Result<Void, NetworkError>) -> Void ) { retrieveToken { [weak self] result in switch result { case .success(let token): self?.callAPI( url: url, method: method, httpHeaderFields: self?.prepareHeaderFields(token: token) ) { result in let result = result.map { _ -> Void in } completion(result) } case .failure(let error): completion(.failure(error)) } } } func execute<ResponseObject: Decodable>( url: URL, method: HTTPMethod, httpBody: Data?, completion: @escaping (Result<ResponseObject, NetworkError>) -> Void ) { retrieveToken { [weak self] result in switch result { case .success(let token): self?.callAPI( url: url, method: method, httpBody: httpBody, httpHeaderFields: self?.prepareHeaderFields(token: token) ) { result in let result = result.flatMap { data -> Result<ResponseObject, NetworkError> in do { let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data) return .success(responseObject) } catch { Log.assertionFailure("Failed to decode json object \nerror: \(error)\nData String: \(String(describing: String(data: data, encoding: .utf8)))") return .failure(.unexpected) } } DispatchQueue.main.async { completion(result) } } case .failure(let error): DispatchQueue.main.async { completion(.failure(error)) } } } } private func retrieveToken(completion: @escaping (Result<String, NetworkError>) -> Void) { if let token = KeyChainService.load(key: HearderConstants.Keys.authorization) { completion(.success(token)) return } Log.info("Retrieving authorization token.") callAPI(url: APIURL.authorization) { result in switch result { case .success(let data): guard let token = String(data: data, encoding: .utf8), KeyChainService.save(key: HearderConstants.Keys.authorization, value: token) else { DispatchQueue.main.async { completion(.failure(.authorizationFailed)) } return } Log.info("Received authorization token.") _ = KeyChainService.save(key: HearderConstants.Keys.authorization, value: token) DispatchQueue.main.async { completion(.success(token)) } case .failure(let error): DispatchQueue.main.async { completion(.failure(error)) } } } } private func callAPI( url: URL, method: HTTPMethod = .get, httpBody: Data? = nil, httpHeaderFields: [String: String]? = nil, completion: @escaping (Result<Data, NetworkError>) -> Void ) { Log.info("Executing request url: \(url))") let urlRequest: URLRequest = { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = method.rawValue urlRequest.httpBody = httpBody urlRequest.allHTTPHeaderFields = httpHeaderFields return urlRequest }() urlSession.dataTask(with: urlRequest) { (data, urlResponse, error) in if let error = error { Log.error("Failed to perform request: \(url), error: \(error)") DispatchQueue.main.async { completion(.failure(.unexpected)) } return } guard let urlResponse = urlResponse as? HTTPURLResponse else { Log.assertionFailure("Unable to convert URLResponse into HTTPURLResponse.") DispatchQueue.main.async { completion(.failure(.unexpected)) } return } if 200..<300 ~= urlResponse.statusCode, let data = data { Log.info("Received response for url: \(String(describing: urlRequest.url))") DispatchQueue.main.async { completion(.success(data)) } } else { let error: NetworkError = urlResponse.statusCode == 408 ? .timeout : .unexpected Log.error("Failed to perform request, status code: \(urlResponse.statusCode), error: \(error)") DispatchQueue.main.async { completion(.failure(error)) } } }.resume() } private func prepareHeaderFields(token: String) -> [String: String] { return [ HearderConstants.Keys.authorization: HearderConstants.Values.authorization(token: token), HearderConstants.Keys.contentType: HearderConstants.Values.contentType ] } }
35.877193
171
0.52828
e24463f6fbc92cef70a6b79bef2d0095c8068e15
771
/* * Copyright 2018 Coodly LLC * * 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 public struct MyDetails: Codable { public let id: Int public let email: String public let apiToken: String public let workspaces: [Workspace] }
29.653846
75
0.735409
75928bdc4a557371d4ef5034fa2a75cfbd17845a
2,458
// This file was generated from JSON Schema using quicktype, do not modify it directly. // To parse the JSON, add this file to your project and do: // // let bWelcome = try? newJSONDecoder().decode(BWelcome.self, from: jsonData) import Foundation // MARK: - BWelcomeElement struct BWelcomeElement: Codable { var name: String var isInstantiable, isReference, hasIndexing, isKeyed: Bool var constructors: [BConstructor] var constants: [BConstant] var methods: [BConstructor] var members: [BMember] var operators: [BOperator] enum CodingKeys: String, CodingKey { case name case isInstantiable = "is_instantiable" case isReference = "is_reference" case hasIndexing = "has_indexing" case isKeyed = "is_keyed" case constructors, constants, methods, members, operators } } // MARK: - BConstant struct BConstant: Codable { var name: String var type: BType var value: String } enum BType: String, Codable { case basis = "Basis" case color = "Color" case float = "float" case int = "int" case plane = "Plane" case quat = "Quat" case transform = "Transform" case transform2D = "Transform2D" case vector2 = "Vector2" case vector2I = "Vector2i" case vector3 = "Vector3" case vector3I = "Vector3i" } // MARK: - BConstructor struct BConstructor: Codable { var name, returnType: String var isConst, hasVarargs: Bool var arguments: [BArgument] enum CodingKeys: String, CodingKey { case name case returnType = "return_type" case isConst = "is_const" case hasVarargs = "has_varargs" case arguments } } // MARK: - BArgument struct BArgument: Codable { var name, type: String var hasDefaultValue: Bool var defaultValue: String enum CodingKeys: String, CodingKey { case name, type case hasDefaultValue = "has_default_value" case defaultValue = "default_value" } } // MARK: - BMember struct BMember: Codable { var name: String var type: BType } // MARK: - BOperator struct BOperator: Codable { var name: String var operatorOperator: Int var otherType, returnType: String enum CodingKeys: String, CodingKey { case name case operatorOperator = "operator" case otherType = "other_type" case returnType = "return_type" } } typealias BWelcome = [BWelcomeElement]
24.828283
87
0.659479
abaa3416d8963074f4cbe55486b72a21a16d1520
1,068
// // RoundedBadge.swift // MovieSwift // // Created by Thomas Ricouard on 16/06/2019. // Copyright © 2019 Thomas Ricouard. All rights reserved. // import SwiftUI struct RoundedBadge : View { let text: String var body: some View { HStack { Text(text.capitalized) .font(.footnote) .fontWeight(.bold) .foregroundColor(.primary) .padding(.leading, 10) .padding([.top, .bottom], 5) Image(systemName: "chevron.right") .resizable() .frame(width: 5, height: 10) .foregroundColor(.primary) .padding(.trailing, 10) } .background( Rectangle() .foregroundColor(.steam_background) .cornerRadius(12) ) .padding(.bottom, 4) } } #if DEBUG struct RoundedBadge_Previews : PreviewProvider { static var previews: some View { RoundedBadge(text: "Test") } } #endif
24.272727
58
0.509363
6238efbfa4fa0d2a59ec79cf4f973f83255b8e6b
4,113
// // NetworkProxy.swift // TasCar // // Created by Enrique Canedo on 18/07/2019. // Copyright © 2019 Enrique Canedo. All rights reserved. // import RxSwift open class NetworkProxy { public init() { } /// JSON /// Process a server call and parse the response as a JSON object /// /// - Important: /// - Use it if you want to get a single object response "only one" /// - If you use a flatmap or map the autocomplete will return a PrimitiveSecuence<T> and you will get errors change it with Single<T> and that's all :D /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Single<T> object with the response func process<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Single<T> { return Network.shared.request(request: networkService, type: type).asSingle() } /// Process a server call and parse the response as a JSON object /// /// - Important: /// Use it if you want to get a maybe object response "only one" /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Maybe<T> object with the response func process<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Maybe<T> { return Network.shared.request(request: networkService, type: type).asMaybe() } /// Process a server call and parse the response as a JSON object /// /// - Important: /// Use it if you want to get N objects response "multiples" /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Observable<T> object with the response func process<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Observable<T> { return Network.shared.request(request: networkService, type: type) } /// ARRAY /// Process a server call and parse the response as a Array object /// /// - Important: /// - Use it if you want to get a single object response "only one" /// - If you use a flatmap or map the autocomplete will return a PrimitiveSecuence<T> and you will get errors change it with Single<T> and that's all :D /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Single<T> object with the response func processArray<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Single<[T]> { return Network.shared.requestArray(request: networkService, type: type).asSingle() } /// Process a server call and parse the response as a Array object /// /// - Important: /// Use it if you want to get a single object response "only one" /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Maybe<T> object with the response func processArray<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Maybe<[T]> { return Network.shared.requestArray(request: networkService, type: type).asMaybe() } /// Process a server call and parse the response as a Array object /// /// - Important: /// Use it if you want to get N objects response "multiples" /// - Parameters: /// - networkService: the configuration to call the API /// - type: use it to parse the object into the type of object that you want /// - Returns: a Observable<T> object with the response func processArray<T: Decodable>(networkService: NetworkAPI, type: T.Type) -> Observable<[T]> { return Network.shared.requestArray(request: networkService, type: type) } }
43.755319
160
0.641624
2191fc211993443d6d7145bc3f5a4c68d53e2065
54,873
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that supplies the values of a sequence one at a time. /// /// The `IteratorProtocol` protocol is tightly linked with the `Sequence` /// protocol. Sequences provide access to their elements by creating an /// iterator, which keeps track of its iteration process and returns one /// element at a time as it advances through the sequence. /// /// Whenever you use a `for`-`in` loop with an array, set, or any other /// collection or sequence, you're using that type's iterator. Swift uses a /// sequence's or collection's iterator internally to enable the `for`-`in` /// loop language construct. /// /// Using a sequence's iterator directly gives you access to the same elements /// in the same order as iterating over that sequence using a `for`-`in` loop. /// For example, you might typically use a `for`-`in` loop to print each of /// the elements in an array. /// /// let animals = ["Antelope", "Butterfly", "Camel", "Dolphin"] /// for animal in animals { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// Behind the scenes, Swift uses the `animals` array's iterator to loop over /// the contents of the array. /// /// var animalIterator = animals.makeIterator() /// while let animal = animalIterator.next() { /// print(animal) /// } /// // Prints "Antelope" /// // Prints "Butterfly" /// // Prints "Camel" /// // Prints "Dolphin" /// /// The call to `animals.makeIterator()` returns an instance of the array's /// iterator. Next, the `while` loop calls the iterator's `next()` method /// repeatedly, binding each element that is returned to `animal` and exiting /// when the `next()` method returns `nil`. /// /// Using Iterators Directly /// ======================== /// /// You rarely need to use iterators directly, because a `for`-`in` loop is the /// more idiomatic approach to traversing a sequence in Swift. Some /// algorithms, however, may call for direct iterator use. /// /// One example is the `reduce1(_:)` method. Similar to the `reduce(_:_:)` /// method defined in the standard library, which takes an initial value and a /// combining closure, `reduce1(_:)` uses the first element of the sequence as /// the initial value. /// /// Here's an implementation of the `reduce1(_:)` method. The sequence's /// iterator is used directly to retrieve the initial value before looping /// over the rest of the sequence. /// /// extension Sequence { /// func reduce1( /// _ nextPartialResult: (Element, Element) -> Element /// ) -> Element? /// { /// var i = makeIterator() /// guard var accumulated = i.next() else { /// return nil /// } /// /// while let element = i.next() { /// accumulated = nextPartialResult(accumulated, element) /// } /// return accumulated /// } /// } /// /// The `reduce1(_:)` method makes certain kinds of sequence operations /// simpler. Here's how to find the longest string in a sequence, using the /// `animals` array introduced earlier as an example: /// /// let longestAnimal = animals.reduce1 { current, element in /// if current.count > element.count { /// return current /// } else { /// return element /// } /// } /// print(longestAnimal) /// // Prints "Butterfly" /// /// Using Multiple Iterators /// ======================== /// /// Whenever you use multiple iterators (or `for`-`in` loops) over a single /// sequence, be sure you know that the specific sequence supports repeated /// iteration, either because you know its concrete type or because the /// sequence is also constrained to the `Collection` protocol. /// /// Obtain each separate iterator from separate calls to the sequence's /// `makeIterator()` method rather than by copying. Copying an iterator is /// safe, but advancing one copy of an iterator by calling its `next()` method /// may invalidate other copies of that iterator. `for`-`in` loops are safe in /// this regard. /// /// Adding IteratorProtocol Conformance to Your Type /// ================================================ /// /// Implementing an iterator that conforms to `IteratorProtocol` is simple. /// Declare a `next()` method that advances one step in the related sequence /// and returns the current element. When the sequence has been exhausted, the /// `next()` method returns `nil`. /// /// For example, consider a custom `Countdown` sequence. You can initialize the /// `Countdown` sequence with a starting integer and then iterate over the /// count down to zero. The `Countdown` structure's definition is short: It /// contains only the starting count and the `makeIterator()` method required /// by the `Sequence` protocol. /// /// struct Countdown: Sequence { /// let start: Int /// /// func makeIterator() -> CountdownIterator { /// return CountdownIterator(self) /// } /// } /// /// The `makeIterator()` method returns another custom type, an iterator named /// `CountdownIterator`. The `CountdownIterator` type keeps track of both the /// `Countdown` sequence that it's iterating and the number of times it has /// returned a value. /// /// struct CountdownIterator: IteratorProtocol { /// let countdown: Countdown /// var times = 0 /// /// init(_ countdown: Countdown) { /// self.countdown = countdown /// } /// /// mutating func next() -> Int? { /// let nextNumber = countdown.start - times /// guard nextNumber > 0 /// else { return nil } /// /// times += 1 /// return nextNumber /// } /// } /// /// Each time the `next()` method is called on a `CountdownIterator` instance, /// it calculates the new next value, checks to see whether it has reached /// zero, and then returns either the number, or `nil` if the iterator is /// finished returning elements of the sequence. /// /// Creating and iterating over a `Countdown` sequence uses a /// `CountdownIterator` to handle the iteration. /// /// let threeTwoOne = Countdown(start: 3) /// for count in threeTwoOne { /// print("\(count)...") /// } /// // Prints "3..." /// // Prints "2..." /// // Prints "1..." public protocol IteratorProtocol { /// The type of element traversed by the iterator. associatedtype Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Repeatedly calling this method returns, in order, all the elements of the /// underlying sequence. As soon as the sequence has run out of elements, all /// subsequent calls return `nil`. /// /// You must not call this method if any other copy of this iterator has been /// advanced with a call to its `next()` method. /// /// The following example shows how an iterator can be used explicitly to /// emulate a `for`-`in` loop. First, retrieve a sequence's iterator, and /// then call the iterator's `next()` method until it returns `nil`. /// /// let numbers = [2, 3, 5, 7] /// var numbersIterator = numbers.makeIterator() /// /// while let num = numbersIterator.next() { /// print(num) /// } /// // Prints "2" /// // Prints "3" /// // Prints "5" /// // Prints "7" /// /// - Returns: The next element in the underlying sequence, if a next element /// exists; otherwise, `nil`. mutating func next() -> Element? } /// A type that provides sequential, iterated access to its elements. /// /// A sequence is a list of values that you can step through one at a time. The /// most common way to iterate over the elements of a sequence is to use a /// `for`-`in` loop: /// /// let oneTwoThree = 1...3 /// for number in oneTwoThree { /// print(number) /// } /// // Prints "1" /// // Prints "2" /// // Prints "3" /// /// While seemingly simple, this capability gives you access to a large number /// of operations that you can perform on any sequence. As an example, to /// check whether a sequence includes a particular value, you can test each /// value sequentially until you've found a match or reached the end of the /// sequence. This example checks to see whether a particular insect is in an /// array. /// /// let bugs = ["Aphid", "Bumblebee", "Cicada", "Damselfly", "Earwig"] /// var hasMosquito = false /// for bug in bugs { /// if bug == "Mosquito" { /// hasMosquito = true /// break /// } /// } /// print("'bugs' has a mosquito: \(hasMosquito)") /// // Prints "'bugs' has a mosquito: false" /// /// The `Sequence` protocol provides default implementations for many common /// operations that depend on sequential access to a sequence's values. For /// clearer, more concise code, the example above could use the array's /// `contains(_:)` method, which every sequence inherits from `Sequence`, /// instead of iterating manually: /// /// if bugs.contains("Mosquito") { /// print("Break out the bug spray.") /// } else { /// print("Whew, no mosquitos!") /// } /// // Prints "Whew, no mosquitos!" /// /// Repeated Access /// =============== /// /// The `Sequence` protocol makes no requirement on conforming types regarding /// whether they will be destructively consumed by iteration. As a /// consequence, don't assume that multiple `for`-`in` loops on a sequence /// will either resume iteration or restart from the beginning: /// /// for element in sequence { /// if ... some condition { break } /// } /// /// for element in sequence { /// // No defined behavior /// } /// /// In this case, you cannot assume either that a sequence will be consumable /// and will resume iteration, or that a sequence is a collection and will /// restart iteration from the first element. A conforming sequence that is /// not a collection is allowed to produce an arbitrary sequence of elements /// in the second `for`-`in` loop. /// /// To establish that a type you've created supports nondestructive iteration, /// add conformance to the `Collection` protocol. /// /// Conforming to the Sequence Protocol /// =================================== /// /// Making your own custom types conform to `Sequence` enables many useful /// operations, like `for`-`in` looping and the `contains` method, without /// much effort. To add `Sequence` conformance to your own custom type, add a /// `makeIterator()` method that returns an iterator. /// /// Alternatively, if your type can act as its own iterator, implementing the /// requirements of the `IteratorProtocol` protocol and declaring conformance /// to both `Sequence` and `IteratorProtocol` are sufficient. /// /// Here's a definition of a `Countdown` sequence that serves as its own /// iterator. The `makeIterator()` method is provided as a default /// implementation. /// /// struct Countdown: Sequence, IteratorProtocol { /// var count: Int /// /// mutating func next() -> Int? { /// if count == 0 { /// return nil /// } else { /// defer { count -= 1 } /// return count /// } /// } /// } /// /// let threeToGo = Countdown(count: 3) /// for i in threeToGo { /// print(i) /// } /// // Prints "3" /// // Prints "2" /// // Prints "1" /// /// Expected Performance /// ==================== /// /// A sequence should provide its iterator in O(1). The `Sequence` protocol /// makes no other requirements about element access, so routines that /// traverse a sequence should be considered O(*n*) unless documented /// otherwise. public protocol Sequence { /// A type that provides the sequence's iteration interface and /// encapsulates its iteration state. associatedtype Element associatedtype Iterator : IteratorProtocol where Iterator.Element == Element /// A type that represents a subsequence of some of the sequence's elements. associatedtype SubSequence // FIXME(ABI)#104 (Recursive Protocol Constraints): // FIXME(ABI)#105 (Associated Types with where clauses): // associatedtype SubSequence : Sequence // where // Element == SubSequence.Element, // SubSequence.SubSequence == SubSequence // // (<rdar://problem/20715009> Implement recursive protocol // constraints) // // These constraints allow processing collections in generic code by // repeatedly slicing them in a loop. /// Returns an iterator over the elements of this sequence. func makeIterator() -> Iterator /// A value less than or equal to the number of elements in /// the sequence, calculated nondestructively. /// /// - Complexity: O(1) var underestimatedCount: Int { get } /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. func forEach(_ body: (Element) throws -> Void) rethrows // Note: The complexity of Sequence.dropFirst(_:) requirement // is documented as O(n) because Collection.dropFirst(_:) is // implemented in O(n), even though the default // implementation for Sequence.dropFirst(_:) is O(1). /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(*n*), where *n* is the number of elements to drop from /// the beginning of the sequence. func dropFirst(_ n: Int) -> SubSequence /// Returns a subsequence containing all but the specified number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func dropLast(_ n: Int) -> SubSequence /// Returns a subsequence by skipping elements while `predicate` returns /// `true` and returning the remaining elements. /// /// - Parameter predicate: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element is a match. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func drop( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the specified maximum length, containing /// the initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. func prefix(_ maxLength: Int) -> SubSequence /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. func prefix( while predicate: (Element) throws -> Bool ) rethrows -> SubSequence /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number /// of elements in the sequence, the result contains all the elements in /// the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of this sequence with /// at most `maxLength` elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. func suffix(_ maxLength: Int) -> SubSequence /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " }) /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. func split( maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] func _customContainsEquatableElement( _ element: Element ) -> Bool? /// If `self` is multi-pass (i.e., a `Collection`), invoke `preprocess` and /// return its result. Otherwise, return `nil`. func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? /// Create a native array buffer containing the elements of `self`, /// in the same order. func _copyToContiguousArray() -> ContiguousArray<Element> /// Copy `self` into an unsafe buffer, returning a partially-consumed /// iterator with any elements that didn't fit remaining. func _copyContents( initializing ptr: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) } /// A default makeIterator() function for `IteratorProtocol` instances that /// are declared to conform to `Sequence` extension Sequence where Self.Iterator == Self { /// Returns an iterator over the elements of this sequence. @_inlineable public func makeIterator() -> Self { return self } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @_versioned @_fixed_layout internal struct _DropFirstSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal var _iterator: Base @_versioned internal let _limit: Int @_versioned internal var _dropped: Int @_versioned @_inlineable internal init(_iterator: Base, limit: Int, dropped: Int = 0) { self._iterator = _iterator self._limit = limit self._dropped = dropped } @_versioned @_inlineable internal func makeIterator() -> _DropFirstSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Base.Element? { while _dropped < _limit { if _iterator.next() == nil { _dropped = _limit return nil } _dropped += 1 } return _iterator.next() } @_versioned @_inlineable internal func dropFirst(_ n: Int) -> AnySequence<Base.Element> { // If this is already a _DropFirstSequence, we need to fold in // the current drop count and drop limit so no data is lost. // // i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to // [1,2,3,4].dropFirst(2). return AnySequence( _DropFirstSequence( _iterator: _iterator, limit: _limit + n, dropped: _dropped)) } } /// A sequence that only consumes up to `n` elements from an underlying /// `Base` iterator. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @_versioned internal struct _PrefixSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { @_versioned internal let _maxLength: Int @_versioned internal var _iterator: Base @_versioned internal var _taken: Int @_versioned @_inlineable internal init(_iterator: Base, maxLength: Int, taken: Int = 0) { self._iterator = _iterator self._maxLength = maxLength self._taken = taken } @_versioned @_inlineable internal func makeIterator() -> _PrefixSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Base.Element? { if _taken >= _maxLength { return nil } _taken += 1 if let next = _iterator.next() { return next } _taken = _maxLength return nil } @_versioned @_inlineable internal func prefix(_ maxLength: Int) -> AnySequence<Base.Element> { return AnySequence( _PrefixSequence( _iterator: _iterator, maxLength: Swift.min(maxLength, self._maxLength), taken: _taken)) } } /// A sequence that lazily consumes and drops `n` elements from an underlying /// `Base` iterator before possibly returning the first available element. /// /// The underlying iterator's sequence may be infinite. @_fixed_layout @_versioned internal struct _DropWhileSequence<Base : IteratorProtocol> : Sequence, IteratorProtocol { typealias Element = Base.Element @_versioned internal var _iterator: Base @_versioned internal var _nextElement: Base.Element? @_versioned @_inlineable internal init( iterator: Base, nextElement: Base.Element?, predicate: (Base.Element) throws -> Bool ) rethrows { self._iterator = iterator self._nextElement = nextElement ?? _iterator.next() while try _nextElement.flatMap(predicate) == true { _nextElement = _iterator.next() } } @_versioned @_inlineable internal func makeIterator() -> _DropWhileSequence<Base> { return self } @_versioned @_inlineable internal mutating func next() -> Element? { guard _nextElement != nil else { return _iterator.next() } let next = _nextElement _nextElement = nil return next } @_versioned @_inlineable internal func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { // If this is already a _DropWhileSequence, avoid multiple // layers of wrapping and keep the same iterator. return try AnySequence( _DropWhileSequence( iterator: _iterator, nextElement: _nextElement, predicate: predicate)) } } //===----------------------------------------------------------------------===// // Default implementations for Sequence //===----------------------------------------------------------------------===// extension Sequence { /// Returns an array containing the results of mapping the given closure /// over the sequence's elements. /// /// In this example, `map` is used first to convert the names in the array /// to lowercase strings and then to count their characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let lowercaseNames = cast.map { $0.lowercased() } /// // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] /// let letterCounts = cast.map { $0.count } /// // 'letterCounts' == [6, 6, 3, 4] /// /// - Parameter transform: A mapping closure. `transform` accepts an /// element of this sequence as its parameter and returns a transformed /// value of the same or of a different type. /// - Returns: An array containing the transformed elements of this /// sequence. @_inlineable public func map<T>( _ transform: (Element) throws -> T ) rethrows -> [T] { let initialCapacity = underestimatedCount var result = ContiguousArray<T>() result.reserveCapacity(initialCapacity) var iterator = self.makeIterator() // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { result.append(try transform(iterator.next()!)) } // Add remaining elements, if any. while let element = iterator.next() { result.append(try transform(element)) } return Array(result) } /// Returns an array containing, in order, the elements of the sequence /// that satisfy the given predicate. /// /// In this example, `filter(_:)` is used to include only names shorter than /// five characters. /// /// let cast = ["Vivien", "Marlon", "Kim", "Karl"] /// let shortNames = cast.filter { $0.count < 5 } /// print(shortNames) /// // Prints "["Kim", "Karl"]" /// /// - Parameter isIncluded: A closure that takes an element of the /// sequence as its argument and returns a Boolean value indicating /// whether the element should be included in the returned array. /// - Returns: An array of the elements that `isIncluded` allowed. @_inlineable public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { return try _filter(isIncluded) } @_transparent public func _filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray<Element>() var iterator = self.makeIterator() while let element = iterator.next() { if try isIncluded(element) { result.append(element) } } return Array(result) } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the sequence. /// /// The sequence must be finite. If the maximum length exceeds the number of /// elements in the sequence, the result contains all the elements in the /// sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func suffix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence") if maxLength == 0 { return AnySequence([]) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements into a ring buffer to save space. Once all // elements are consumed, reorder the ring buffer into an `Array` // and return it. This saves memory for sequences particularly longer // than `maxLength`. var ringBuffer: [Element] = [] ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount)) var i = ringBuffer.startIndex for element in self { if ringBuffer.count < maxLength { ringBuffer.append(element) } else { ringBuffer[i] = element i += 1 i %= maxLength } } if i != ringBuffer.startIndex { let s0 = ringBuffer[i..<ringBuffer.endIndex] let s1 = ringBuffer[0..<i] return AnySequence([s0, s1].joined()) } return AnySequence(ringBuffer) } /// Returns the longest possible subsequences of the sequence, in order, that /// don't contain elements satisfying the given predicate. Elements that are /// used to split the sequence are not returned as part of any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string using a /// closure that matches spaces. The first use of `split` returns each word /// that was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print( /// line.split(maxSplits: 1, whereSeparator: { $0 == " " }) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `true` for the `allowEmptySlices` parameter, so /// the returned array contains empty strings where spaces were repeated. /// /// print( /// line.split( /// omittingEmptySubsequences: false, /// whereSeparator: { $0 == " " } /// ).map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each pair of consecutive elements /// satisfying the `isSeparator` predicate and for each element at the /// start or end of the sequence satisfying the `isSeparator` predicate. /// If `true`, only nonempty subsequences are returned. The default /// value is `true`. /// - isSeparator: A closure that returns `true` if its argument should be /// used to split the sequence; otherwise, `false`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Element) throws -> Bool ) rethrows -> [AnySequence<Element>] { _precondition(maxSplits >= 0, "Must take zero or more splits") var result: [AnySequence<Element>] = [] var subSequence: [Element] = [] @discardableResult func appendSubsequence() -> Bool { if subSequence.isEmpty && omittingEmptySubsequences { return false } result.append(AnySequence(subSequence)) subSequence = [] return true } if maxSplits == 0 { // We aren't really splitting the sequence. Convert `self` into an // `Array` using a fast entry point. subSequence = Array(self) appendSubsequence() return result } var iterator = self.makeIterator() while let element = iterator.next() { if try isSeparator(element) { if !appendSubsequence() { continue } if result.count == maxSplits { break } } else { subSequence.append(element) } } while let element = iterator.next() { subSequence.append(element) } appendSubsequence() return result } /// Returns a value less than or equal to the number of elements in /// the sequence, nondestructively. /// /// - Complexity: O(*n*) @_inlineable public var underestimatedCount: Int { return 0 } @_inlineable public func _preprocessingPass<R>( _ preprocess: () throws -> R ) rethrows -> R? { return nil } @_inlineable public func _customContainsEquatableElement( _ element: Iterator.Element ) -> Bool? { return nil } /// Calls the given closure on each element in the sequence in the same order /// as a `for`-`in` loop. /// /// The two loops in the following example produce the same output: /// /// let numberWords = ["one", "two", "three"] /// for word in numberWords { /// print(word) /// } /// // Prints "one" /// // Prints "two" /// // Prints "three" /// /// numberWords.forEach { word in /// print(word) /// } /// // Same as above /// /// Using the `forEach` method is distinct from a `for`-`in` loop in two /// important ways: /// /// 1. You cannot use a `break` or `continue` statement to exit the current /// call of the `body` closure or skip subsequent calls. /// 2. Using the `return` statement in the `body` closure will exit only from /// the current call to `body`, not from any outer scope, and won't skip /// subsequent calls. /// /// - Parameter body: A closure that takes an element of the sequence as a /// parameter. @_inlineable public func forEach( _ body: (Element) throws -> Void ) rethrows { for element in self { try body(element) } } } @_versioned @_fixed_layout internal enum _StopIteration : Error { case stop } extension Sequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// The following example uses the `first(where:)` method to find the first /// negative number in an array of integers: /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// if let firstNegative = numbers.first(where: { $0 < 0 }) { /// print("The first negative number is \(firstNegative).") /// } /// // Prints "The first negative number is -2." /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @_inlineable public func first( where predicate: (Element) throws -> Bool ) rethrows -> Element? { var foundElement: Element? do { try self.forEach { if try predicate($0) { foundElement = $0 throw _StopIteration.stop } } } catch is _StopIteration { } return foundElement } } extension Sequence where Element : Equatable { /// Returns the longest possible subsequences of the sequence, in order, /// around elements equal to the given element. /// /// The resulting array consists of at most `maxSplits + 1` subsequences. /// Elements that are used to split the sequence are not returned as part of /// any subsequence. /// /// The following examples show the effects of the `maxSplits` and /// `omittingEmptySubsequences` parameters when splitting a string at each /// space character (" "). The first use of `split` returns each word that /// was originally separated by one or more spaces. /// /// let line = "BLANCHE: I don't want realism. I want magic!" /// print(line.split(separator: " ") /// .map(String.init)) /// // Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// The second example passes `1` for the `maxSplits` parameter, so the /// original string is split just once, into two new strings. /// /// print(line.split(separator: " ", maxSplits: 1) /// .map(String.init)) /// // Prints "["BLANCHE:", " I don\'t want realism. I want magic!"]" /// /// The final example passes `false` for the `omittingEmptySubsequences` /// parameter, so the returned array contains empty strings where spaces /// were repeated. /// /// print(line.split(separator: " ", omittingEmptySubsequences: false) /// .map(String.init)) /// // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" /// /// - Parameters: /// - separator: The element that should be split upon. /// - maxSplits: The maximum number of times to split the sequence, or one /// less than the number of subsequences to return. If `maxSplits + 1` /// subsequences are returned, the last one is a suffix of the original /// sequence containing the remaining elements. `maxSplits` must be /// greater than or equal to zero. The default value is `Int.max`. /// - omittingEmptySubsequences: If `false`, an empty subsequence is /// returned in the result for each consecutive pair of `separator` /// elements in the sequence and for each instance of `separator` at the /// start or end of the sequence. If `true`, only nonempty subsequences /// are returned. The default value is `true`. /// - Returns: An array of subsequences, split from this sequence's elements. @_inlineable public func split( separator: Element, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true ) -> [AnySequence<Element>] { return split( maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: { $0 == separator }) } } extension Sequence where SubSequence : Sequence, SubSequence.Element == Element, SubSequence.SubSequence == SubSequence { /// Returns a subsequence containing all but the given number of initial /// elements. /// /// If the number of elements to drop exceeds the number of elements in /// the sequence, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// print(numbers.dropFirst(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop from the beginning of /// the sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence starting after the specified number of /// elements. /// /// - Complexity: O(1). @_inlineable public func dropFirst(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } return AnySequence(_DropFirstSequence(_iterator: makeIterator(), limit: n)) } /// Returns a subsequence containing all but the given number of final /// elements. /// /// The sequence must be finite. If the number of elements to drop exceeds /// the number of elements in the sequence, the result is an empty /// subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter n: The number of elements to drop off the end of the /// sequence. `n` must be greater than or equal to zero. /// - Returns: A subsequence leaving off the specified number of elements. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast(_ n: Int) -> AnySequence<Element> { _precondition(n >= 0, "Can't drop a negative number of elements from a sequence") if n == 0 { return AnySequence(self) } // FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T> // Put incoming elements from this sequence in a holding tank, a ring buffer // of size <= n. If more elements keep coming in, pull them out of the // holding tank into the result, an `Array`. This saves // `n` * sizeof(Element) of memory, because slices keep the entire // memory of an `Array` alive. var result: [Element] = [] var ringBuffer: [Element] = [] var i = ringBuffer.startIndex for element in self { if ringBuffer.count < n { ringBuffer.append(element) } else { result.append(ringBuffer[i]) ringBuffer[i] = element i = ringBuffer.index(after: i) % n } } return AnySequence(result) } /// Returns a subsequence by skipping the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `drop(while:)` method to skip over the /// positive numbers at the beginning of the `numbers` array. The result /// begins with the first element of `numbers` that does not satisfy /// `predicate`. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let startingWithNegative = numbers.drop(while: { $0 > 0 }) /// // startingWithNegative == [-2, 9, -6, 10, 1] /// /// If `predicate` matches every element in the sequence, the result is an /// empty sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence starting after the initial, consecutive elements /// that satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func drop( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { return try AnySequence( _DropWhileSequence( iterator: makeIterator(), nextElement: nil, predicate: predicate)) } /// Returns a subsequence, up to the specified maximum length, containing the /// initial elements of the sequence. /// /// If the maximum length exceeds the number of elements in the sequence, /// the result contains all the elements in the sequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.prefix(2)) /// // Prints "[1, 2]" /// print(numbers.prefix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. The /// value of `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence starting at the beginning of this sequence /// with at most `maxLength` elements. /// /// - Complexity: O(1) @_inlineable public func prefix(_ maxLength: Int) -> AnySequence<Element> { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence") if maxLength == 0 { return AnySequence(EmptyCollection<Element>()) } return AnySequence( _PrefixSequence(_iterator: makeIterator(), maxLength: maxLength)) } /// Returns a subsequence containing the initial, consecutive elements that /// satisfy the given predicate. /// /// The following example uses the `prefix(while:)` method to find the /// positive numbers at the beginning of the `numbers` array. Every element /// of `numbers` up to, but not including, the first negative value is /// included in the result. /// /// let numbers = [3, 7, 4, -2, 9, -6, 10, 1] /// let positivePrefix = numbers.prefix(while: { $0 > 0 }) /// // positivePrefix == [3, 7, 4] /// /// If `predicate` matches every element in the sequence, the resulting /// sequence contains every element of the sequence. /// /// - Parameter predicate: A closure that takes an element of the sequence as /// its argument and returns a Boolean value indicating whether the /// element should be included in the result. /// - Returns: A subsequence of the initial, consecutive elements that /// satisfy `predicate`. /// /// - Complexity: O(*n*), where *n* is the length of the collection. @_inlineable public func prefix( while predicate: (Element) throws -> Bool ) rethrows -> AnySequence<Element> { var result: [Element] = [] for element in self { guard try predicate(element) else { break } result.append(element) } return AnySequence(result) } } extension Sequence { /// Returns a subsequence containing all but the first element of the /// sequence. /// /// The following example drops the first element from an array of integers. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropFirst()) /// // Prints "[]" /// /// - Returns: A subsequence starting after the first element of the /// sequence. /// /// - Complexity: O(1) @_inlineable public func dropFirst() -> SubSequence { return dropFirst(1) } /// Returns a subsequence containing all but the last element of the /// sequence. /// /// The sequence must be finite. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// /// If the sequence has no elements, the result is an empty subsequence. /// /// let empty: [Int] = [] /// print(empty.dropLast()) /// // Prints "[]" /// /// - Returns: A subsequence leaving off the last element of the sequence. /// /// - Complexity: O(*n*), where *n* is the length of the sequence. @_inlineable public func dropLast() -> SubSequence { return dropLast(1) } } extension Sequence { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` are /// initialized. @_inlineable public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { var it = self.makeIterator() guard var ptr = buffer.baseAddress else { return (it,buffer.startIndex) } for idx in buffer.startIndex..<buffer.count { guard let x = it.next() else { return (it, idx) } ptr.initialize(to: x) ptr += 1 } return (it,buffer.endIndex) } } // FIXME(ABI)#182 // Pending <rdar://problem/14011860> and <rdar://problem/14396120>, // pass an IteratorProtocol through IteratorSequence to give it "Sequence-ness" /// A sequence built around an iterator of type `Base`. /// /// Useful mostly to recover the ability to use `for`...`in`, /// given just an iterator `i`: /// /// for x in IteratorSequence(i) { ... } @_fixed_layout public struct IteratorSequence< Base : IteratorProtocol > : IteratorProtocol, Sequence { /// Creates an instance whose iterator is a copy of `base`. @_inlineable public init(_ base: Base) { _base = base } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @_inlineable public mutating func next() -> Base.Element? { return _base.next() } @_versioned internal var _base: Base } @available(*, unavailable, renamed: "IteratorProtocol") public typealias GeneratorType = IteratorProtocol @available(*, unavailable, renamed: "Sequence") public typealias SequenceType = Sequence extension Sequence { @available(*, unavailable, renamed: "makeIterator()") public func generate() -> Iterator { Builtin.unreachable() } @available(*, unavailable, renamed: "getter:underestimatedCount()") public func underestimateCount() -> Int { Builtin.unreachable() } @available(*, unavailable, message: "call 'split(maxSplits:omittingEmptySubsequences:whereSeparator:)' and invert the 'allowEmptySlices' argument") public func split(_ maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Element) throws -> Bool ) rethrows -> [SubSequence] { Builtin.unreachable() } } extension Sequence where Element : Equatable { @available(*, unavailable, message: "call 'split(separator:maxSplits:omittingEmptySubsequences:)' and invert the 'allowEmptySlices' argument") public func split( _ separator: Element, maxSplit: Int = Int.max, allowEmptySlices: Bool = false ) -> [AnySequence<Element>] { Builtin.unreachable() } } @available(*, unavailable, renamed: "IteratorSequence") public struct GeneratorSequence<Base : IteratorProtocol> {}
36.339735
149
0.633955
183612eab21ad46026faae0173087a2d7d4dd2fb
5,448
// Copyright © 2018 Stormbird PTE. LTD. import UIKit import PromiseKit protocol ServersCoordinatorDelegate: AnyObject { func didSelectServer(selection: ServerSelection, in coordinator: ServersCoordinator) func didSelectDismiss(in coordinator: ServersCoordinator) } class ServersCoordinator: Coordinator { //Cannot be `let` as the chains can change dynamically without the app being restarted (i.e. killed). The UI can be restarted though (when switching changes) static var serversOrdered: [RPCServer] { let all: [RPCServer] = [ .main, .xDai, .classic, .poa, .ropsten, .goerli, .kovan, .rinkeby, .sokol, .binance_smart_chain, .binance_smart_chain_testnet, .callisto, .heco, .heco_testnet, .artis_sigma1, .artis_tau1, .fantom, .fantom_testnet, .avalanche, .avalanche_testnet, .polygon, .mumbai_testnet, .optimistic, .optimisticKovan, .cronosTestnet, .arbitrum, .arbitrumRinkeby, ] + RPCServer.customServers if Features.isPalmEnabled { return all + [.palm, .palmTestnet] } else { return all } } let viewModel: ServersViewModel private lazy var serversViewController: ServersViewController = { let controller = ServersViewController(viewModel: viewModel) controller.delegate = self controller.hidesBottomBarWhenPushed = true return controller }() let navigationController: UINavigationController var coordinators: [Coordinator] = [] weak var delegate: ServersCoordinatorDelegate? init(defaultServer: RPCServerOrAuto, config: Config, navigationController: UINavigationController) { self.navigationController = navigationController let serverChoices = ServersCoordinator.serverChoices(includeAny: true, config: config) self.viewModel = ServersViewModel(servers: serverChoices, selectedServers: [defaultServer]) } init(defaultServer: RPCServer, config: Config, navigationController: UINavigationController) { self.navigationController = navigationController let serverChoices = ServersCoordinator.serverChoices(includeAny: false, config: config) self.viewModel = ServersViewModel(servers: serverChoices, selectedServers: [.server(defaultServer)]) } init(viewModel: ServersViewModel, navigationController: UINavigationController) { self.navigationController = navigationController self.viewModel = viewModel } private static func serverChoices(includeAny: Bool, config: Config) -> [RPCServerOrAuto] { let enabledServers = ServersCoordinator.serversOrdered.filter { config.enabledServers.contains($0) } let servers: [RPCServerOrAuto] = enabledServers.map { .server($0) } if includeAny { return [.auto] + servers } else { return servers } } func start() { navigationController.pushViewController(serversViewController, animated: true) } } extension ServersCoordinator: ServersViewControllerDelegate { func didSelectServer(selection: ServerSelection, in viewController: ServersViewController) { delegate?.didSelectServer(selection: selection, in: self) } func didClose(in viewController: ServersViewController) { delegate?.didSelectDismiss(in: self) } } private class ServersCoordinatorBridgeToPromise { private let navigationController: UINavigationController private let (promiseToReturn, seal) = Promise<ServerSelection>.pending() private var retainCycle: ServersCoordinatorBridgeToPromise? init(_ navigationController: UINavigationController, coordinator: Coordinator, viewModel: ServersViewModel) { self.navigationController = navigationController retainCycle = self let newCoordinator = ServersCoordinator(viewModel: viewModel, navigationController: navigationController) newCoordinator.delegate = self coordinator.addCoordinator(newCoordinator) promiseToReturn.ensure { // ensure we break the retain cycle coordinator.removeCoordinator(newCoordinator) self.retainCycle = nil }.cauterize() newCoordinator.start() } var promise: Promise<ServerSelection> { return promiseToReturn } } extension ServersCoordinatorBridgeToPromise: ServersCoordinatorDelegate { func didSelectServer(selection: ServerSelection, in coordinator: ServersCoordinator) { navigationController.popViewController(animated: true) { self.seal.fulfill(selection) } } func didSelectDismiss(in coordinator: ServersCoordinator) { navigationController.popViewController(animated: true) { self.seal.reject(PMKError.cancelled) } } } extension ServersCoordinator { static func promise(_ navigationController: UINavigationController, viewModel: ServersViewModel, coordinator: Coordinator) -> Promise<ServerSelection> { let bridge = ServersCoordinatorBridgeToPromise(navigationController, coordinator: coordinator, viewModel: viewModel) return bridge.promise } }
34.481013
161
0.683186
e9ae4206e098902e66664034164a066562e9f129
21,820
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import AVFoundation import UIKit /// A protocol for drawer item view controller management. public protocol DrawerItemViewController { /// Configures a view controller's drawer panner. /// /// - Parameter drawerViewController: The view controller to configure. func setUpDrawerPanner(with drawerViewController: DrawerViewController) /// Resets the view controller. func reset() } /// A protocol to update view controllers about the position of the drawer. public protocol DrawerPositionListener: AnyObject { /// Called when the drawer is about to change position. /// /// - Parameters: /// - drawerViewController: The drawer view controller. /// - position: The drawer position. func drawerViewController(_ drawerViewController: DrawerViewController, willChangeDrawerPosition position: DrawerPosition) /// Called when the drawer changed position. /// /// - Parameters: /// - drawerViewController: The drawer view controller. /// - position: The drawer position. func drawerViewController(_ drawerViewController: DrawerViewController, didChangeDrawerPosition position: DrawerPosition) /// Called when the drawer is panning. /// /// - Parameters: /// - drawerViewController: The drawer view controller. /// - position: The drawer position. func drawerViewController(_ drawerViewController: DrawerViewController, isPanningDrawerView drawerView: DrawerView) /// Called when the drawer pans upward beyond its bounds. /// /// - Parameters: /// - drawerViewController: The drawer view controller. /// - panDistance: The distance of the pan upward beyond the drawer's bounds. func drawerViewController(_ drawerViewController: DrawerViewController, didPanBeyondBounds panDistance: CGFloat) } /// Extends UIViewController for drawer contained view controllers. extension UIViewController { /// If the receiver is contained by a drawer view controller and is in the current hierarchy, this /// returns the drawer view controller. var drawerViewController: DrawerViewController? { var vcParent = parent while vcParent != nil { if let drawerViewController = vcParent as? DrawerViewController { return drawerViewController } vcParent = vcParent?.parent } return nil } /// Returns true if the receiver is the current view controller being displayed in the drawer. var isDisplayedInDrawer: Bool { return drawerViewController?.currentViewController == self } } /// A container view controller that switches between view controllers by pressing buttons in the /// `DrawerView`'s tab bar. open class DrawerViewController: UIViewController, DrawerViewDelegate { // MARK: - Properties /// The notes view controller. var notesViewController: NotesViewController { // swiftlint:disable force_cast return drawerItems.viewControllerForKey(DrawerItemKeys.notesViewControllerKey) as! NotesViewController // swiftlint:enable force_cast } /// The observe view controller. var observeViewController: ObserveViewController { // swiftlint:disable force_cast return drawerItems.viewControllerForKey(DrawerItemKeys.observeViewControllerKey) as! ObserveViewController // swiftlint:enable force_cast } /// The camera view controller. var cameraViewController: CameraViewController { // swiftlint:disable force_cast return drawerItems.viewControllerForKey(DrawerItemKeys.cameraViewControllerKey) as! CameraViewController // swiftlint:enable force_cast } /// The photo library view controller. var photoLibraryViewController: PhotoLibraryViewController { // swiftlint:disable force_cast return drawerItems.viewControllerForKey(DrawerItemKeys.photoLibraryViewControllerKey) as! PhotoLibraryViewController // swiftlint:enable force_cast } /// The view controller currently being shown. var currentViewController: UIViewController? /// The drawer view. var drawerView: DrawerView { // swiftlint:disable force_cast return view as! DrawerView // swiftlint:enable force_cast } /// Whether or not the drawer is being displayed as a sidebar. var isDisplayedAsSidebar = false { didSet { drawerView.isDisplayedAsSidebar = isDisplayedAsSidebar } } /// Whether or not the camera item in the tab bar should have an enabled or disabled appearance. var isCameraItemEnabled = true { didSet { guard oldValue != isCameraItemEnabled else { return } let cameraTabItem = drawerView.tabBar.items[cameraItemIndex] cameraTabItem.image = UIImage(named: isCameraItemEnabled ? "ic_camera_alt" : "ic_camera_alt_disabled") } } /// Drawer items. public let drawerItems: DrawerItems private var notesDrawerItem: DrawerItem { return drawerItems.drawerItemForKey(DrawerItemKeys.notesViewControllerKey) } private var observeDrawerItem: DrawerItem { return drawerItems.drawerItemForKey(DrawerItemKeys.observeViewControllerKey) } private let cameraItemIndex = 2 private let analyticsReporter: AnalyticsReporter /// Objects to be called with DrawerPositionListener methods. Uses a weak hash table to avoid /// creating retain cycles. private var drawerPositionListeners = NSHashTable<AnyObject>.weakObjects() // MARK: - Public /// Public initializer. /// /// - Parameters: /// - analyticsReporter: An instance of AnalyticsReporter to inject into all related classes. /// - drawerConfig: An instance of a DrawerConfig class to configure drawer items and their view /// controllers. /// - preferenceManager: A preference manager. /// - sensorController: A sensor controller. /// - sensorDataManager: A sensor data manager. init(analyticsReporter: AnalyticsReporter, drawerConfig: DrawerConfig, preferenceManager: PreferenceManager, sensorController: SensorController, sensorDataManager: SensorDataManager) { self.analyticsReporter = analyticsReporter drawerItems = DrawerItems(analyticsReporter: analyticsReporter, drawerConfig: drawerConfig, preferenceManager: preferenceManager, sensorController: sensorController, sensorDataManager: sensorDataManager) super.init(nibName: nil, bundle: nil) // Set up position tracking and drawer panners on drawer item VCs that require it. for case let listener as DrawerPositionListener & DrawerItemViewController in drawerItems.viewControllers { addDrawerPositionListener(listener) listener.setUpDrawerPanner(with: self) } } deinit { // Remove position tracking on drawer item VCs that require it. for case let listener as DrawerPositionListener in drawerItems.viewControllers { removeDrawerPositionListener(listener) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override open func loadView() { super.loadView() view = DrawerView(items: drawerItems.allItems, delegate: self) } override open func viewDidLoad() { super.viewDidLoad() updateItemViewController() NotificationCenter.default.addObserver(self, selector: #selector(captureSessionWasInterrupted(_:)), name: .AVCaptureSessionWasInterrupted, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(captureSessionInterruptionEnded(_:)), name: .AVCaptureSessionInterruptionEnded, object: nil) } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isCameraItemEnabled = CaptureSessionInterruptionObserver.shared.isCameraUseAllowed } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) updateAllowedDrawerPositions(for: view.bounds.size) } override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) updateAllowedDrawerPositions(for: size) // TODO: Fix the layout when there is an in-call status bar. http://b/62135678 } /// Resets the drawer to be used for a new experiment. func reset() { drawerView.resetHeight() drawerItems.viewControllers.forEach { $0.reset() } selectNotes() } // MARK: - Drawer Position /// Sets the drawer position to full. /// /// - Parameter: animated: Whether or not to animate. Default is true. func setPositionToFull(animated: Bool = true) { setPosition(drawerView.openFullPosition, animated: animated) } /// Sets the drawer position to half. /// /// - Parameters: /// - animated: Whether or not to animate. Default is true. /// - completion: Called when setting the position to half completes, if it can open to half. /// Otherwise called immediately. func setPositionToHalf(animated: Bool = true, completion: (() -> Void)? = nil) { guard drawerView.canOpenHalf && !isDisplayedAsSidebar else { completion?() return } setPosition(drawerView.openHalfPosition, animated: animated, completion: completion) } /// Sets the drawer position to peeking. /// /// - Parameters: /// - animated: Whether or not to animate. Default is true. /// - completion: Called when setting the position to peeking completes, if it can open to /// peeking. Otherwise called immediately. func setPositionToPeeking(animated: Bool = true, completion: (() -> Void)? = nil) { guard !isDisplayedAsSidebar else { completion?(); return } setPosition(drawerView.peekingPosition, animated: animated, completion: completion) } /// If the drawer can open halfway, open it halfway. Otherwise open it full. If the drawer is not /// in the peeking position, this method does nothing. func showContent() { guard isPeeking else { return } if drawerView.canOpenHalf { setPositionToHalf() } else { setPositionToFull() } } /// If the drawer can open halfway, open it halfway. Otherwise set it to the peeking position. /// /// - Parameter animated: Whether or not to animate. func setPositionToHalfOrPeeking(animated: Bool) { if drawerView.canOpenHalf { setPositionToHalf(animated: animated) } else { setPositionToPeeking(animated: animated) } } /// If the drawer can open halfway, open it halfway. Otherwise, set it to peeking. If the drawer /// is displayed as a sidebar or is not open full, this method does nothing and calls completion /// immediately. /// /// - Parameter completion: Called when the drawer position is set or immediately if there will be /// no position change. func minimizeFromFull(completion: (() -> Void)? = nil) { guard !isDisplayedAsSidebar && isOpenFull else { completion?(); return } if drawerView.canOpenHalf { setPositionToHalf(completion: completion) } else { setPositionToPeeking(completion: completion) } } /// Sets the drawer to the custom position if it is full. /// /// - Parameter completion: Called when setting the position to half completes if it was full. /// Otherwise called immediately. func setToCustomPositionIfFull(completion: (() -> Void)? = nil) { if isOpenFull { setPositionToCustom(completion: completion) } else { completion?() } } /// Sets the drawer to the custom position, if it exists. /// /// - Parameters: /// - animated: Whether or not to animate. Default is true. /// - completion: Called when setting the position to custom completes, if it can open to /// custom. Otherwise called immediately. func setPositionToCustom(animated: Bool = true, completion: (() -> Void)? = nil) { guard !isDisplayedAsSidebar && drawerView.canOpenToCustomPosition, let customDrawerPosition = drawerView.customPosition else { completion?(); return } setPosition(customDrawerPosition, animated: animated, completion: completion) } /// Sets the drawer to open half if it is open to the custom position. func setPositionToHalfIfCustom() { if isCustomPosition { setPositionToHalf() } } /// Whether or not the drawer's current position is full. var isOpenFull: Bool { return isPositionOpenFull(drawerView.currentPosition) } /// Whether or not the drawer view's current position is half. var isOpenHalf: Bool { return isPositionOpenHalf(drawerView.currentPosition) } /// Whether or not the drawer view's current position is peeking. var isPeeking: Bool { return isPositionPeeking(drawerView.currentPosition) } /// Whether or not the drawer view's current position is the custom one. var isCustomPosition: Bool { return isPositionCustom(drawerView.currentPosition) } /// Whether or not the positon is open full. /// /// - Parameter position: The position. /// - Returns: True if it is open full, otherwise false. func isPositionOpenFull(_ position: DrawerPosition) -> Bool { return position == drawerView.openFullPosition } /// Whether or not the positon is open half. /// /// - Parameter position: The position. /// - Returns: True if it is open half, otherwise false. func isPositionOpenHalf(_ position: DrawerPosition) -> Bool { return position == drawerView.openHalfPosition } /// Whether or not the positon is peeking. /// /// - Parameter position: The position. /// - Returns: True if it is peeking, otherwise false. func isPositionPeeking(_ position: DrawerPosition) -> Bool { return position == drawerView.peekingPosition } /// Whether or not the positon is the custom one. /// /// - Parameter position: The position. /// - Returns: True if it is open to the custom position, otherwise false. func isPositionCustom(_ position: DrawerPosition) -> Bool { return position == drawerView.customPosition } /// Whether or not partial drawer positions are supported. var canOpenPartially: Bool { return !view.bounds.size.isWiderThanTall } // MARK: Item selection /// Selects notes in the drawer. func selectNotes() { select(item: notesDrawerItem) } /// Selects observe in the drawer. func selectObserve() { select(item: observeDrawerItem) } // MARK: - Private /// Sets the drawer position. /// /// - Parameters: /// - position: The position. /// - animated: Whether or not to animate the change. /// - completion: Called when setting the position completes. private func setPosition(_ position: DrawerPosition, animated: Bool = true, completion: (() -> Void)? = nil) { drawerView.panToPosition(position, animated: animated, completion: completion) } /// Selects a drawer view tab bar item and shows its view controller. /// /// - Parameter item: The item to select. func select(item: DrawerItem) { guard let index = drawerItems.allItems.firstIndex(where: { $0 === item }) else { return } show(viewController: item.viewController) drawerView.tabBar.selectedItem = drawerView.tabBar.items[index] } /// Shows a view controller in the drawer view's content view. /// /// - Parameter viewController: The view controller to show. func show(viewController: UIViewController) { guard viewController != currentViewController else { // Do nothing if `viewController` is already being shown. return } // If a VC's view was already added to the drawer, remove it. if let currentViewController = currentViewController { currentViewController.view.removeFromSuperview() currentViewController.removeFromParent() } // Add the VC's view to the drawer. currentViewController = viewController addChild(currentViewController!) drawerView.displayViewInContentView(currentViewController!.view) if currentViewController == cameraViewController { cameraViewController.setPreviewHeightAnchor(equalTo: drawerView.panningView.heightAnchor) } } // Shows the first view controller if nothing has loaded yet. Also, updates the selected item for // whether the drawer is open or not. func updateItemViewController(for drawerPosition: DrawerPosition? = nil) { /// Determines if the content view is visible, based on either the drawer's position or by /// asking the drawer view. var isContentViewVisible: Bool { if let position = drawerPosition { return position != drawerView.peekingPosition } else { return drawerView.isContentViewVisible } } if currentViewController == nil { selectNotes() } // Deleselect the tab bar only if the drawer is in peeking position or if nothing has been // selected (e.g. on initial launch). var shouldDeselectItem = !isContentViewVisible if let drawerPosition = drawerPosition { shouldDeselectItem = drawerPosition == drawerView.peekingPosition } if shouldDeselectItem { drawerView.tabBar.selectedItem = nil } else if let currentViewController = currentViewController { if let index = drawerItems.allItems.firstIndex(where: { (drawerItem) -> Bool in return drawerItem.viewController === currentViewController }) { drawerView.tabBar.selectedItem = drawerView.tabBar.items[index] } } } // MARK: - Drawer position listeners /// Adds a drawer position listener. /// /// - Parameter listener: The drawer position listener object. func addDrawerPositionListener(_ listener: DrawerPositionListener) { drawerPositionListeners.add(listener) } /// Removes a drawer position listener. /// /// - Parameter listener: The drawer position listener object. func removeDrawerPositionListener(_ listener: DrawerPositionListener) { drawerPositionListeners.remove(listener) } func updateAllowedDrawerPositions(for viewSize: CGSize, animated: Bool = false) { drawerView.canOpenHalf = !viewSize.isWiderThanTall drawerView.canOpenToCustomPosition = !viewSize.isWiderThanTall } // MARK: - DrawerViewDelegate public func drawerView(_ drawerView: DrawerView, didSelectItemAtIndex index: Int) { // Perform without animation to avoid undesirable animations when showing a view controller. UIView.performWithoutAnimation { show(viewController: drawerItems.allItems[index].viewController) } showContent() } public func drawerView(_ drawerView: DrawerView, willChangePosition position: DrawerPosition) { updateItemViewController(for: position) drawerPositionListeners.allObjects.forEach { (object) in guard let listener = object as? DrawerPositionListener else { return } listener.drawerViewController(self, willChangeDrawerPosition: position) } } public func drawerView(_ drawerView: DrawerView, didChangePosition position: DrawerPosition) { drawerPositionListeners.allObjects.forEach { (object) in guard let listener = object as? DrawerPositionListener else { return } listener.drawerViewController(self, didChangeDrawerPosition: position) } drawerView.updateDrawerShadow(for: position) } public func drawerViewIsPanning(_ drawerView: DrawerView) { updateItemViewController() drawerPositionListeners.allObjects.forEach { (object) in guard let listener = object as? DrawerPositionListener else { return } listener.drawerViewController(self, isPanningDrawerView: drawerView) } } public func drawerView(_ drawerView: DrawerView, didPanBeyondBounds panDistance: CGFloat) { drawerPositionListeners.allObjects.forEach { (object) in guard let listener = object as? DrawerPositionListener else { return } listener.drawerViewController(self, didPanBeyondBounds: panDistance) } } // MARK: - Notifications @objc private func captureSessionWasInterrupted(_ notification: Notification) { guard Thread.isMainThread else { DispatchQueue.main.async { self.captureSessionWasInterrupted(notification) } return } guard AVCaptureSession.InterruptionReason(notificationUserInfo: notification.userInfo) == .videoDeviceNotAvailableWithMultipleForegroundApps else { return } isCameraItemEnabled = false } @objc private func captureSessionInterruptionEnded(_ notification: Notification) { guard Thread.isMainThread else { DispatchQueue.main.async { self.captureSessionInterruptionEnded(notification) } return } isCameraItemEnabled = !CaptureSessionInterruptionObserver.shared.isBrightnessSensorInUse } }
35.888158
100
0.703437
1d564db61754f27c9245fc5af8369a5f21c55b99
286
// // OrderType.swift // CupcakeCorner // // Created by Jessica Lewinter on 09/07/20. // Copyright © 2020 Jessica Lewinter. All rights reserved. // import Foundation enum OrderType: String, CaseIterable { case vanilla case strawberry case chocolate case rainbow }
16.823529
59
0.699301
9c0d8ecef7dc1f57f560d41c0f8df69cce7b1dd8
1,097
// // HTKUtils.swift // // Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai) // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import Foundation class HTKUtils { class func setDefaults(key: String, withValue value: AnyObject) { var defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(value, forKey: key) defaults.synchronize() } class func getDefaults(key: String) -> AnyObject? { var defaults = NSUserDefaults.standardUserDefaults() var value: AnyObject? = defaults.objectForKey(key) return value } class func getStringFromInfoBundleForKey(key: String) -> String { var value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String return value ?? "" } class func formatCurrency(amount: Double) -> String { var numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle var formattedAmount = numberFormatter.stringFromNumber(amount) return formattedAmount } }
29.648649
84
0.690975
f485c9069c451fdcdf4a93c4b2d97ab11853dfec
4,615
// // Measurement.swift // LibreMonitor // // Created by Uwe Petersen on 25.08.16. // Copyright © 2016 Uwe Petersen. All rights reserved. // import Foundation protocol MeasurementProtocol { var rawGlucose: Int { get } /// The raw temperature as read from the sensor var rawTemperature: Int { get } var rawTemperatureAdjustment: Int { get } var error : [MeasurementError] { get} } public enum MeasurementError: Int, CaseIterable { case OK = 0 case SD14_FIFO_OVERFLOW = 1 case FILTER_DELTA = 0x02 case WORK_VOLTAGE = 0x04 case PEAK_DELTA_EXCEEDED = 0x08 case AVG_DELTA_EXCEEDED = 0x10 case RF = 0x20 case REF_R = 0x40 case SIGNAL_SATURATED = 128 // 0x80 case SENSOR_SIGNAL_LOW = 256 // 0x100 case THERMISTOR_OUT_OF_RANGE = 2048 // 0x800 case TEMP_HIGH = 8192 // 0x2000 case TEMP_LOW = 16384 // 0x4000 case INVALID_DATA = 32768 // 0x8000 static var allErrorCodes : [MeasurementError] { var allErrorCases = MeasurementError.allCases allErrorCases.removeAll { $0 == .OK} return allErrorCases } } struct SimplifiedMeasurement: MeasurementProtocol { var rawGlucose: Int var rawTemperature: Int var rawTemperatureAdjustment: Int = 0 var error = [MeasurementError.OK] } /// Structure for one glucose measurement including value, date and raw data bytes public struct Measurement: MeasurementProtocol { /// The date for this measurement let date: Date /// The minute counter for this measurement let counter: Int /// The bytes as read from the sensor. All data is derived from this \"raw data" let bytes: [UInt8] /// The bytes as String let byteString: String /// The raw glucose as read from the sensor let rawGlucose: Int /// The raw temperature as read from the sensor let rawTemperature: Int let rawTemperatureAdjustment: Int let error : [MeasurementError] let idValue : Int init(date: Date, rawGlucose: Int, rawTemperature: Int, rawTemperatureAdjustment: Int, idValue: Int = 0) { self.date = date self.rawGlucose = rawGlucose self.rawTemperature = rawTemperature self.rawTemperatureAdjustment = rawTemperatureAdjustment //not really needed when setting the other properties above explicitly self.bytes = [] self.byteString = "" self.error = [MeasurementError.OK] self.counter = 0 //only used for sorting purposes self.idValue = idValue } /// /// - parameter bytes: raw data bytes as read from the sensor /// - parameter slope: slope to calculate glucose from raw value in (mg/dl)/raw /// - parameter offset: glucose offset to be added in mg/dl /// - parameter date: date of the measurement /// /// - returns: Measurement init(bytes: [UInt8], slope: Double = 0.1, offset: Double = 0.0, counter: Int = 0, date: Date, idValue: Int = 0) { self.bytes = bytes self.byteString = bytes.reduce("", { $0 + String(format: "%02X", arguments: [$1]) }) //self.rawGlucose = (Int(bytes[1] & 0x1F) << 8) + Int(bytes[0]) // switched to 13 bit mask on 2018-03-15 self.rawGlucose = SensorData.readBits(bytes, 0, 0, 0xe) //self.rawTemperature = (Int(bytes[4] & 0x3F) << 8) + Int(bytes[3]) // 14 bit-mask for raw temperature //raw temperature in libre FRAM is always stored in multiples of four self.rawTemperature = SensorData.readBits(bytes, 0, 0x1a, 0xc) << 2 let temperatureAdjustment = (SensorData.readBits(bytes, 0, 0x26, 0x9) << 2) let negativeAdjustment = SensorData.readBits(bytes, 0, 0x2f, 0x1) != 0 self.rawTemperatureAdjustment = negativeAdjustment ? -temperatureAdjustment : temperatureAdjustment self.date = date self.counter = counter let errorBitField = SensorData.readBits(bytes,0, 0xe, 0xc) self.error = Self.extractErrorBitField(errorBitField) //only used for sorting purposes self.idValue = idValue } static func extractErrorBitField(_ errBitField: Int) -> [MeasurementError]{ errBitField == 0 ? [MeasurementError.OK] : MeasurementError.allErrorCodes.filter { (errBitField & $0.rawValue) != 0} } var description: String { String(" date: \(date), rawGlucose: \(rawGlucose), rawTemperature: \(rawTemperature), bytes: \(bytes) \n") } }
32.272727
117
0.63727
e8506bd1a22060a419fa8270bdab02990e5de559
9,624
// // DeviceInfoViewController.swift // BLE-Swift // // Created by SuJiang on 2019/1/4. // Copyright © 2019 ss. All rights reserved. // import UIKit class DeviceInfoViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, CharacteristicCellTableViewCellDelegate, CmdKeyBoardViewDelegate { var device: BLEDevice @IBOutlet weak var deviceNameLbl: UILabel! @IBOutlet weak var uuidLbl: UILabel! @IBOutlet weak var stateLbl: UILabel! @IBOutlet weak var connectBtn: UIButton! @IBOutlet weak var disconnectBtn: UIButton! @IBOutlet weak var tableView: UITableView! var deviceInfos: Array<DeviceInfo>! init(device: BLEDevice) { self.device = device super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() configNav() createView() reloadData() NotificationCenter.default.addObserver(self, selector: #selector(deviceDataUpdate), name: BLEInnerNotification.deviceDataUpdate, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) DeviceResponseLogView.create() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) DeviceResponseLogView.destroy() } func configNav() { self.title = TR("Device Information") setNavLeftButton(withIcon: "fanhui", sel: #selector(backClick)) setNavRightButton(text: TR("日志"), sel: #selector(showLogBtnClick)) } func createView() { tableView.dataSource = self tableView.delegate = self tableView.register(UINib(nibName: "CharacteristicCellTableViewCell", bundle: nil), forCellReuseIdentifier: "cellId") reloadData() } func reloadData() { deviceInfos = generateInfos(withDevice: device) deviceNameLbl.text = device.name uuidLbl.text = "UUID: " + device.name if device.state == .disconnected { stateLbl.text = TR("Disconnected") stateLbl.textColor = rgb(200, 30, 30) connectBtn.isHidden = false disconnectBtn.isHidden = true } else { stateLbl.text = TR("Connected") stateLbl.textColor = rgb(30, 200, 30) connectBtn.isHidden = true disconnectBtn.isHidden = false } tableView.reloadData() } // MARK: - 业务逻辑 func generateInfos(withDevice deive:BLEDevice) -> Array<DeviceInfo> { var deviceInfoArr = Array<DeviceInfo>(); // advertisement data let adInfo = DeviceInfo(type: .advertisementData) adInfo.name = TR("ADVERTISEMENT DATA") deviceInfoArr.append(adInfo) for (uuid, service) in device.services { let sInfo = DeviceInfo(type: .service, uuid: uuid, name: "", properties: "", id: uuid) deviceInfoArr.append(sInfo) guard let characteristics = service.characteristics else { continue } for ch in characteristics { let uuid = ch.uuid.uuidString let name = uuid.count > 4 ? "Characteristic " + uuid.suffix(4) : "Characteristic " + uuid var properties = "" if ch.properties.contains(.read) { properties += "Read " } if ch.properties.contains(.write) { properties += "Write " } if ch.properties.contains(.writeWithoutResponse) { properties += "Write Without Response " } if ch.properties.contains(.notify) { properties += "Notify" } let cInfo = DeviceInfo(type: .characteristic, uuid: uuid, name: name, properties: properties, id: uuid) sInfo.subItems.append(cInfo) } } return deviceInfoArr; } // MARK: - 事件处理 @objc func backClick() { self.navigationController?.dismiss(animated: true, completion: nil) } @IBAction func connectBtnClick(_ sender: Any) { startLoading(nil) weak var weakSelf = self BLECenter.shared.connect(device: device, callback:{ (d, err) in if err != nil { weakSelf?.handleBleError(error: err) } else { weakSelf?.showSuccess(TR("Connected")) weakSelf?.device = d!; weakSelf?.reloadData() } }) } @IBAction func disconnectBtnClick(_ sender: Any) { startLoading(nil) weak var weakSelf = self BLECenter.shared.disconnect(device: device, callback:{ (d, err) in if err != nil { weakSelf?.handleBleError(error: err) } else { weakSelf?.showSuccess(TR("Connected")) weakSelf?.device = d!; weakSelf?.reloadData() } }) } @objc func showLogBtnClick() { DeviceResponseLogView.show() } // MARK: - 代理 func numberOfSections(in tableView: UITableView) -> Int { return deviceInfos.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let dInfo = deviceInfos[section] return dInfo.subItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! CharacteristicCellTableViewCell let dInfo = deviceInfos[indexPath.section] cell.updateUI(withDeviceInfo: dInfo.subItems[indexPath.row]) cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let dInfo = deviceInfos[section] if dInfo.type == .advertisementData { return dInfo.name } else { return "UUID: " + dInfo.uuid } } private var keyboard = CmdKeyBoardView() private var textField: UITextField? func didClickSendBtn(cell: UITableViewCell) { let indexPath = tableView.indexPath(for: cell)! let dInfo = deviceInfos[indexPath.section] let cInfo = dInfo.subItems[indexPath.row] keyboard.delegate = self let alert = UIAlertController(title: nil, message: "输入要发送的数据(16进制)", preferredStyle: .alert) let ok = UIAlertAction(title: TR("OK"), style: .default) { (action) in if self.device.state == .ready { guard let sendStr = alert.textFields![0].text, sendStr.count > 0 else { self.showError("不能发送空的") return } self.printLog(log: "向 \(cInfo.uuid) 发送数据:\(sendStr)") _ = self.device.write(sendStr.hexadecimal ?? Data(), characteristicUUID: cInfo.uuid) } else { self.printLog(log: "设备断连了,无法发送数据") } } let cancel = UIAlertAction(title: TR("CANCEL"), style: .cancel, handler: nil) alert.addTextField { (textField) in textField.font = font(12) textField.inputView = self.keyboard self.textField = textField } alert.addAction(ok) alert.addAction(cancel) navigationController?.present(alert, animated: true, completion: nil) } func didEnterStr(str: String) { if str.hasPrefix("Str") || str.hasPrefix("Int") || str.hasPrefix("Len") { return } textField?.text = (textField?.text ?? "") + str } func didFinishInput() { } func didFallback() { guard let text = textField?.text, text.count > 0 else { return } textField?.text = String(text.prefix(text.count - 1)) } @objc func deviceDataUpdate(notification: Notification) { guard let uuid = notification.userInfo?[BLEKey.uuid] as? String else { return } guard let data = notification.userInfo?[BLEKey.data] as? Data else { return } guard let device = notification.userInfo?[BLEKey.device] as? BLEDevice else { return } if device == self.device { DeviceResponseLogView.printLog(log: "(\(uuid)) recv data:\(data.hexEncodedString())") DeviceResponseLogView.show() } // if uuid == self.data.recvFromUuid && device == self.device { // parser.standardParse(data: data, sendData: self.data.sendData, recvCount: self.data.recvDataCount) // } } func printLog(log: String) { DeviceResponseLogView.printLog(log: log) } }
31.45098
162
0.565669
1e13aa9254b950ea8ce318b9144685ac2f0a3d0e
5,437
import XCTest import UIKit import TorusUtils @testable import TorusSwiftDirectSDK @available(iOS 11.0, *) final class TorusSwiftDirectSDKTests: XCTestCase { func testGetTorusKey() { let expectation = XCTestExpectation(description: "getTorusKey should correctly proxy input and output to/from TorusUtils") let expectedPrivateKey = fakeData.generatePrivateKey() let expectedPublicAddress = fakeData.generatePublicKey() let expectedVerifier = fakeData.generateVerifier() let expectedVerfierId = fakeData.generateRandomEmail(of: 6) let subVerifier = [SubVerifierDetails(loginProvider: .jwt, clientId: fakeData.generateVerifier(), verifierName: expectedVerifier, redirectURL: fakeData.generateVerifier())] let factory = MockFactory() let torusSwiftDirectSDK = TorusSwiftDirectSDK(aggregateVerifierType: .singleLogin, aggregateVerifierName: expectedVerifier, subVerifierDetails: subVerifier, factory: factory) var mockTorusUtils = torusSwiftDirectSDK.torusUtils as! MockAbstractTorusUtils // Set Mock data mockTorusUtils.retrieveShares_output["privateKey"] = expectedPrivateKey mockTorusUtils.retrieveShares_output["publicAddress"] = expectedPublicAddress torusSwiftDirectSDK.getTorusKey(verifier: expectedVerifier, verifierId: expectedVerfierId, idToken: fakeData.generateVerifier()) .done { data in let mockTorusUtils = torusSwiftDirectSDK.torusUtils as! MockAbstractTorusUtils XCTAssertEqual(mockTorusUtils.retrieveShares_input["endpoints"] as? [String], torusSwiftDirectSDK.endpoints) XCTAssertEqual(mockTorusUtils.retrieveShares_input["verifierIdentifier"] as? String, expectedVerifier) XCTAssertEqual(mockTorusUtils.retrieveShares_input["verifierId"] as? String, expectedVerfierId) XCTAssertEqual(data["privateKey"] as? String, expectedPrivateKey) XCTAssertEqual(data["publicAddress"] as? String, expectedPublicAddress) }.catch { err in XCTFail(err.localizedDescription) }.finally { expectation.fulfill() } wait(for: [expectation], timeout: 5) } func testGetAggregateTorusKey() { let expectation = XCTestExpectation(description: "getAggregateTorusKey should correctly proxy input and output to/from TorusUtils") let expectedPrivateKey = fakeData.generatePrivateKey() let expectedPublicAddress = fakeData.generatePublicKey() let expectedVerifier = fakeData.generateVerifier() let expectedVerfierId = fakeData.generateRandomEmail(of: 6) let subVerifier = [SubVerifierDetails(loginProvider: .jwt, clientId: fakeData.generateVerifier(), verifierName: expectedVerifier, redirectURL: fakeData.generateVerifier())] let factory = MockFactory() let torusSwiftDirectSDK = TorusSwiftDirectSDK(aggregateVerifierType: .singleIdVerifier, aggregateVerifierName: expectedVerifier, subVerifierDetails: subVerifier, factory: factory) var mockTorusUtils = torusSwiftDirectSDK.torusUtils as! MockAbstractTorusUtils // Set Mock data mockTorusUtils.retrieveShares_output["privateKey"] = expectedPrivateKey mockTorusUtils.retrieveShares_output["publicAddress"] = expectedPublicAddress torusSwiftDirectSDK.getAggregateTorusKey(verifier: expectedVerifier, verifierId: expectedVerfierId, idToken: fakeData.generateVerifier(), subVerifierDetails: subVerifier[0]) .done { data in let mockTorusUtils = torusSwiftDirectSDK.torusUtils as! MockAbstractTorusUtils XCTAssertEqual(mockTorusUtils.retrieveShares_input["endpoints"] as? [String], torusSwiftDirectSDK.endpoints) XCTAssertEqual(mockTorusUtils.retrieveShares_input["verifierIdentifier"] as? String, expectedVerifier) XCTAssertEqual(mockTorusUtils.retrieveShares_input["verifierId"] as? String, expectedVerfierId) XCTAssertEqual(data["privateKey"] as? String, expectedPrivateKey) XCTAssertEqual(data["publicAddress"] as? String, expectedPublicAddress) }.catch { err in XCTFail(err.localizedDescription) }.finally { expectation.fulfill() } wait(for: [expectation], timeout: 5) } static var allTests = [ ("testGetTorusKey", testGetTorusKey), // ("testGetAggregateTorusKey", testGetAggregateTorusKey), ] } class fakeData{ static func generateVerifier() -> String{ return String.randomString(length: 10) } static func generatePrivateKey() -> String{ let privateKey = Data.randomOfLength(32) return (privateKey?.toHexString())! } static func generatePublicKey() -> String{ let privateKey = Data.randomOfLength(32)! let publicKey = SECP256K1.privateToPublic(privateKey: privateKey)?.subdata(in: 1..<65) return publicKey!.toHexString() } static func generateRandomEmail(of length: Int) -> String { let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var s = "" for _ in 0 ..< length { s.append(letters.randomElement()!) } return s + "@gmail.com" } }
49.880734
187
0.699651
71c9fd81bd4a822042665d8aebbb04e10734913b
3,508
import Foundation var table = [[String]]() let strange = "You input something strange.\nPlease, check the format again: you must write the 'ROW COLUMN', so your input will look like '1 2' or '0 3' (without quotes, obviously)." func start(){ table = [[" "," "," "],[" "," "," "],[" "," "," "]] print("Basic Tic-tac-toe (tabled)") print(" 1 2 3") print("1 1 1 2 1 3 1") print("2 1 2 2 2 3 2") print("3 1 3 2 3 3 3") print("\nYou are the 'X' in the table.") play() } func play(){ print("\n 1 2 3") print("1 \(table[0][0]) \(table[0][1]) \(table[0][2])") print("2 \(table[1][0]) \(table[1][1]) \(table[1][2])") print("3 \(table[2][0]) \(table[2][1]) \(table[2][2])") checkWin() print("Enter the cell you want to put in your symbol in format 'ROW COLUMN':") let answer = readLine() let splitted = answer?.split(separator: " ") guard splitted?.capacity == 2 else { print(strange) play() return } for e in splitted! { let num = Int(e) guard num != nil && num! <= 3 && num! >= 1 else { print(strange) play() return } } let n1 = Int(splitted![0]) ?? 0 let n2 = Int(splitted![1]) ?? 0 var somebody = "" guard table[n1 - 1][n2 - 1] == " " else { if table[n1 - 1][n2 - 1] == "X" { somebody = "you" } else { somebody = "computer" } print("This cell is already taken by \(somebody)! Enter another.") play() return } table[n1 - 1][n2 - 1] = "X" AI() play() } func checkWin(){ if table[0][0] == table[0][1] && table[0][0] == table[0][2] && table[0][0] != " " { win(sym: table[0][0]) return } else if table[1][0] == table[1][1] && table[1][0] == table[1][2] && table[1][0] != " " { win(sym: table[1][0]) return } else if table[2][0] == table[2][1] && table[2][0] == table[2][2] && table[2][0] != " " { win(sym: table[2][0]) return } else if table[0][0] == table[1][0] && table[0][0] == table[2][0] && table[0][0] != " " { win(sym: table[0][0]) return } else if table[0][1] == table[1][1] && table[0][1] == table[2][1] && table[0][1] != " " { win(sym: table[0][1]) return } else if table[0][2] == table[1][2] && table[0][2] == table[2][2] && table[0][2] != " " { win(sym: table[0][2]) return } else if table[0][0] == table[1][1] && table[0][0] == table[2][2] && table[0][0] != " " { win(sym: table[0][0]) return } else if table[0][2] == table[1][1] && table[0][2] == table[2][0] && table[0][2] != " " { win(sym: table[0][2]) return } else {return} } func win(sym: String) { var winner = "" if sym == "X" { winner = "player" } else if sym == "O" { winner = "computer" } print("The \(winner) won! Wanna play one more time? (y/n)") let input = readLine() if input == "y" { start() return } else { print("Bye-bye!") exit(0) } } func AI(){ guard table[1][1] != " " else { table[1][1] = "O" return } for (i1, row) in table.enumerated().shuffled() { for (i2, item) in row.enumerated().shuffled() { guard item == "X" else { table[i1][i2] = "O" break } } break } } start()
29.233333
183
0.454675
dd45d2cb5a64a3587bd67d878738f5471a150133
1,566
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/master/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore /// Error enum for CloudHSM public enum CloudHSMErrorType: AWSErrorType { case cloudHsmInternalException(message: String?) case cloudHsmServiceException(message: String?) case invalidRequestException(message: String?) } extension CloudHSMErrorType { public init?(errorCode: String, message: String?){ var errorCode = errorCode if let index = errorCode.firstIndex(of: "#") { errorCode = String(errorCode[errorCode.index(index, offsetBy: 1)...]) } switch errorCode { case "CloudHsmInternalException": self = .cloudHsmInternalException(message: message) case "CloudHsmServiceException": self = .cloudHsmServiceException(message: message) case "InvalidRequestException": self = .invalidRequestException(message: message) default: return nil } } } extension CloudHSMErrorType : CustomStringConvertible { public var description : String { switch self { case .cloudHsmInternalException(let message): return "CloudHsmInternalException: \(message ?? "")" case .cloudHsmServiceException(let message): return "CloudHsmServiceException: \(message ?? "")" case .invalidRequestException(let message): return "InvalidRequestException: \(message ?? "")" } } }
36.418605
158
0.670498
713b369b830b69794cbf7792eb0696851d0d12dd
3,783
// // Client.swift // Zaym // // Created by Mikhail Lutskiy on 09.03.2018. // Copyright © 2018 Mikhail Lutskii. All rights reserved. // import Foundation import ObjectMapper import Alamofire import AlamofireObjectMapper class Client:Mappable { var id: Int? var name: String? var email: String? var password: String? var date_of_birth: String? var pass_num: String? var pass_country: String? var pass_issue: String? var pass_exp: String? var pass_authority: String? var place_of_birth: String? var fraud_scoring: String? required convenience init?(map: Map) { self.init() } func mapping(map: Map) { id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) name <- map["name"] email <- map["email"] password <- map["password"] date_of_birth <- map["date_of_birth"] pass_num <- map["pass_num"] pass_country <- map["pass_country"] pass_issue <- map["pass_issue"] pass_exp <- map["pass_exp"] pass_authority <- map["pass_authority"] place_of_birth <- map["place_of_birth"] fraud_scoring <- map["fraud_scoring"] } func auth () { Alamofire.request(ApiUrl.authClient, method: .post, parameters: Mapper().toJSON(self)).validate(statusCode: 200..<300).responseObject { (response: DataResponse<Client>) in switch response.result { case .success: UserCache.setUserId((response.result.value?.id)!) UserCache.changeLoginState(true) UserCache.changeClientState(true) print(UserCache.userId()) print("Validation Successful") ViewManager.topViewController().dismiss(animated: true, completion: nil) case .failure(let error): if response.response?.statusCode == 400 { ViewManager.topViewController().showAlertMessage(text: "Введенный email или пароль неверен", title: "Ошибка") } else { ViewManager.topViewController().showAlertMessage(text: "Проверьте интернет соединение", title: "Ошибка") } print(error) } } } func register () { Alamofire.request(ApiUrl.register, method: .post, parameters: Mapper().toJSON(self)).validate(statusCode: 200..<300).responseObject { (response: DataResponse<Client>) in switch response.result { case .success: UserCache.setUserId((response.result.value?.id)!) UserCache.changeLoginState(true) UserCache.changeClientState(true) print(UserCache.userId()) print("Validation Successful") ViewManager.topViewController().dismiss(animated: true, completion: nil) case .failure(let error): if response.response?.statusCode == 500 { ViewManager.topViewController().showAlertMessage(text: "Введенный email уже занят", title: "Ошибка") } else { ViewManager.topViewController().showAlertMessage(text: "Проверьте интернет соединение", title: "Ошибка") } print(error) } } } func update () { Alamofire.request(ApiUrl.getClientById(UserCache.userId()), method: .post, parameters: Mapper().toJSON(self)).validate(statusCode: 200..<300).responseObject { (response: DataResponse<Client>) in switch response.result { case .success: print("success") case .failure(let error): print(error) } } } }
37.83
202
0.587365
7607cf368c3df02d885e13cfae50a51485a577b4
1,497
// // CGPoint.swift // // The MIT License // Copyright (c) 2015 - 2021 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit extension CGPoint { var phase: CGFloat { return atan2(y, x) } var magnitude: CGFloat { return hypot(x, y) } static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint { return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y) } }
35.642857
81
0.702071
72f2fdb99a813ac7935198520263b175acf07566
2,367
// // AppDelegate.swift // DependencyInjectorSample-iOS // // Created by Benoit BRIATTE on 23/12/2016. // Copyright © 2016 Digipolitan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = UINavigationController(rootViewController: ViewController()) self.window = window window.makeKeyAndVisible() 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:. } }
49.3125
194
0.748204
7662415f3a59c6a5e067ac1acfabb888df3616e4
2,155
// // LocationFormatterTests.swift // FormatterKit Example // // Created by Barış Özdağ on 25.04.2017. // // import XCTest import FormatterKit class LocationFormatterTests: XCTestCase { var formatter: TTTLocationFormatter! var austin: CLLocation { return CLLocation(latitude: 30.2669444, longitude:-97.7427778) } var pittsburgh: CLLocation { return CLLocation(latitude: 40.4405556, longitude:-79.9961111) } override func setUp() { super.setUp() formatter = TTTLocationFormatter() } // MARK: Tests func testDistance() { let result = formatter.stringFromDistance(from: pittsburgh, to: austin) XCTAssertEqual(result, "2.000 km") } func testDistanceAndBearing() { let result = formatter.stringFromDistanceAndBearing(from: pittsburgh, to: austin) XCTAssertEqual(result, "2.000 km Güneybatı") } func testDistanceInMetricUnitswithCardinalDirectionAbbreviations() { formatter.numberFormatter.maximumSignificantDigits = 4 formatter.bearingStyle = .bearingAbbreviationWordStyle let result = formatter.stringFromDistanceAndBearing(from: pittsburgh, to: austin) XCTAssertEqual(result, "1.963 km GB") } func testDistanceInImperialUnit() { formatter.unitSystem = .imperialSystem let result = formatter.stringFromDistance(from: pittsburgh, to: austin) XCTAssertEqual(result, "1.200 mil") } // TODO: might be a bug as it returns `56 mph` func pending_testSpeed() { XCTAssertEqual(formatter.string(fromSpeed: 25), "25 km/sa") } // TODO: returns 240 which doesn't match with the example in readme. Might be a bug func pending_testBearingInDegrees() { formatter.bearingStyle = .bearingNumericStyle XCTAssertEqual(formatter.stringFromBearing(from: pittsburgh, to: austin), "310°") } func testCoordinates() { formatter.numberFormatter.maximumSignificantDigits = 9 XCTAssertEqual(formatter.string(from: austin), "30,2669444, -97,7427778") } }
30.352113
89
0.668213
6456f0468e974d077e9f0b041b46842e37dabc8f
1,283
// // SwiftDrawerNavigationOneUITests.swift // SwiftDrawerNavigationOneUITests // // Created by NextDot on 2/4/16. // Copyright © 2016 RzRasel. All rights reserved. // import XCTest class SwiftDrawerNavigationOneUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.675676
182
0.674201
e51b9e4d9be866b00dde8a0bfbe2bb98f8bb6ccc
1,319
// // Constants.swift // // Copyright (c) 2020 Chris Pflepsen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation enum Constants { static let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" static let phoneNumberLength: Int = 10 }
42.548387
81
0.732373
f46e762764569b135ea73c10c591f2a0001161d1
7,075
// // DownloadViewController.swift // PersonalMusic // // Created by 李小争 on 2018/3/2. // Copyright © 2018年 Citynight. All rights reserved. // import UIKit import GCDWebServers.GCDWebUploader import SnapKit import AVFoundation class DownloadViewController: UIViewController { private lazy var downloadTipView: DownloadTipView = { let view = UINib(nibName: "DownloadTipView", bundle: nil).instantiate(withOwner: self, options: nil).first as! DownloadTipView return view }() private lazy var tableView: UITableView = { let tableView = UITableView(frame: self.view.bounds) tableView.delegate = self tableView.dataSource = self return tableView }() private var webServer: GCDWebUploader? private lazy var dataSource:[MusicModel] = [] private lazy var documentsPath: String = { guard let documentsPathStr = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentationDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first else { return "" } let documentsPath = documentsPathStr + "/musics" if !FileManager.default.fileExists(atPath: documentsPath) { try? FileManager.default.createDirectory(atPath: documentsPath, withIntermediateDirectories: true, attributes: nil) } print("歌曲文件路径:",documentsPath) return documentsPath }() override func viewDidLoad() { super.viewDidLoad() setupUI() fetchFileNames() } deinit { webServer?.stop() print("jieshu") } } extension DownloadViewController { func setupUI() { view.backgroundColor = UIColor.white configTableView() configIpView() configNav() } func configNav() { let rightBarButtonItem = UIBarButtonItem(title: "从电脑导歌", style: .plain, target: self, action: #selector(downloadMusic)) navigationItem.rightBarButtonItem = rightBarButtonItem self.navigationController?.setNavigationAlpha(1) self.navigationController?.setTitleColor(UIColor.black) } func configTableView() { view.addSubview(tableView) tableView.registerClassFromClass(type: UITableViewCell.self) tableView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } } func configIpView() { view.addSubview(downloadTipView) downloadTipView.isHidden = true downloadTipView.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.height.equalTo(250) } } func fetchFileNames() { let subpaths = FileManager.default.subpaths(atPath: documentsPath) let dataSource = subpaths ?? [] var tempMusics = [MusicModel]() for i in dataSource { let url = URL(fileURLWithPath: documentsPath + "/\(i)") let mp3Asset = AVAsset(url: url) let music = MusicModel() music.filePath = url for format in mp3Asset.availableMetadataFormats { for item in mp3Asset.metadata(forFormat: format) { // 歌曲图片 if item.commonKey?.rawValue == "artwork" { if let data = item.value as? Data { let image = UIImage(data: data) music.iconImage = image } } // 专辑名称 if item.commonKey?.rawValue == "albumName" { if let value = item.value { music.albumName = String(describing: value) } } // 艺术家 if item.commonKey?.rawValue == "artist" { if let value = item.value { music.artist = String(describing: value) } } // 歌曲名称 if item.commonKey?.rawValue == "title" { if let value = item.value { music.title = String(describing: value) } } } } tempMusics.append(music) } self.dataSource = tempMusics tableView.reloadData() } } @objc extension DownloadViewController { func downloadMusic() { downloadTipView.isHidden = false if webServer == nil { webServerConfig(with: documentsPath) } } } extension DownloadViewController { func webServerConfig(with path: String) { let webServer = GCDWebUploader(uploadDirectory: path) webServer.delegate = self webServer.allowHiddenItems = true if webServer.start() { print("服务器启动") let ip = webServer.serverURL?.absoluteString downloadTipView.ipLabel.text = ip }else { print("启动失败") downloadTipView.isHidden = true } self.webServer = webServer downloadTipView.closeComplete = {[weak self] in guard let `self` = self else { return } webServer.stop() self.webServer = nil self.downloadTipView.isHidden = true } } } extension DownloadViewController: GCDWebUploaderDelegate { func webUploader(_ uploader: GCDWebUploader, didUploadFileAtPath path: String) { print("upload", path) fetchFileNames() } func webUploader(_ uploader: GCDWebUploader, didMoveItemFromPath fromPath: String, toPath: String) { print("MOVE",fromPath,toPath) fetchFileNames() } func webUploader(_ uploader: GCDWebUploader, didDeleteItemAtPath path: String) { print("DELETE",path) fetchFileNames() } func webUploader(_ uploader: GCDWebUploader, didCreateDirectoryAtPath path: String) { print("CREATE",path) fetchFileNames() } } extension DownloadViewController: UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(type: UITableViewCell.self, forIndexPath: indexPath) cell.textLabel?.text = dataSource[indexPath.row].artist return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = dataSource[indexPath.row] MusicOperationTool.shared.musicMs = dataSource MusicOperationTool.shared.playMusic(with: model) let vc = MusicDetailViewController(nibName: "MusicDetailViewController", bundle: nil) self.navigationController?.pushViewController(vc, animated: true) } }
34.681373
196
0.596184
8aac4535ba867e102fac3d90082fc8045f238371
4,159
// // AppDelegate.swift // Instagram // // Created by Gerardo Parra on 6/26/17. // Copyright © 2017 Gerardo Parra. All rights reserved. // import UIKit import Parse @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Initialize Parse // Set applicationId and server based on the values in the Heroku settings. // clientKey is not used on Parse open source unless explicitly configured Parse.initialize( with: ParseClientConfiguration(block: { (configuration: ParseMutableClientConfiguration) -> Void in configuration.applicationId = "instaGreat" configuration.clientKey = "sdncvreilcnx,iejofm2e" configuration.server = "https://instagr8.herokuapp.com/parse" }) ) // Persist user if PFUser.current() != nil { let storyboard = UIStoryboard(name: "Main", bundle: nil) let feedNavController = storyboard.instantiateViewController(withIdentifier: "FeedNavController") window?.rootViewController = feedNavController } // Log user out NotificationCenter.default.addObserver(forName: NSNotification.Name("logoutNotification"), object: nil, queue: OperationQueue.main) { (Notification) in // Take user to logout screen let storyboard = UIStoryboard(name: "Main", bundle: nil) let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController") self.window?.rootViewController = loginViewController } // Finish Post NotificationCenter.default.addObserver(forName: NSNotification.Name("sentPostNotification"), object: nil, queue: OperationQueue.main) { (Notification) in // Take user to logout screen let storyboard = UIStoryboard(name: "Main", bundle: nil) let feedNavController = storyboard.instantiateViewController(withIdentifier: "FeedNavController") self.window?.rootViewController = feedNavController } // Remove back button titles UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), for:UIBarMetrics.default) 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:. } }
48.929412
285
0.709546
332bed7fa8c61228634166d897c22cc7813cac14
3,400
// // Business.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit class Business: NSObject { let name: String? let address: String? let imageURL: URL? let categories: String? let distance: String? let ratingImageURL: URL? let reviewCount: NSNumber? init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = URL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["address"] as? NSArray if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } } self.address = address let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joined(separator: ", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = URL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber } class func businesses(array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } func contains(searchText: String) -> Bool{ print("Business Name: \(self.name), Search Text: \(searchText)") return (self.name?.lowercased().contains(searchText.lowercased()))! } class func searchWithTerm(term: String, completion: @escaping ([Business]?, Error?) -> Void) { _ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void { _ = YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, completion: completion) } }
34
164
0.571471
f838f744cad592bc050295b21fcfa3ca992c2f06
3,117
// // RadioColorCollectionViewCell.swift // AdForest // // Created by Furqan Nadeem on 31/01/2019. // Copyright © 2019 apple. All rights reserved. // import UIKit class RadioColorCollectionViewCell: UICollectionViewCell { //MARK:- Outlets @IBOutlet weak var imgViewRadio: UIImageView! var dataArray = [SearchValue]() var data : SearchValue? var radioButtonCell: RadioColorTableViewCell! var indexPath = 0 var id = "" //MARK:- View Life Cycle override func awakeFromNib() { super.awakeFromNib() //self.selectionStyle = .none } func initializeData(value: SearchValue, radioButtonCellRef: RadioColorTableViewCell, index: Int) { data = value indexPath = index radioButtonCell = radioButtonCellRef // buttonRadio.addTarget(self, action: #selector(self.radioButtonTapped), for: .touchUpInside) } func initCellItem() { let deselectedImage = UIImage(named: "empty (1)")?.withRenderingMode(.alwaysTemplate) let selectedImage = UIImage(named: "radio-on-button")?.withRenderingMode(.alwaysTemplate) //buttonRadio.setImage(deselectedImage, for: .normal) //buttonRadio.setImage(selectedImage, for: .selected) // buttonRadio.addTarget(self, action: #selector(self.radioButtonTapped), for: .touchUpInside) } // @objc func radioButtonTapped(_ radioButton: UIButton) { // // if (radioButtonCell.dataArray[indexPath].isSelected) { // radioButton.backgroundColor = UIColor.clear //radioButton.tintColor // //radioButton.layer.borderColor = radioButton.tintColor.cgColor // // data?.isSelected = false // radioButtonCell.dataArray[indexPath].isSelected = true // } // else { // radioButton.backgroundColor = radioButton.backgroundColor // radioButton.layer.borderColor = radioButton.layer.borderColor // radioButton.layer.cornerRadius = 13 // radioButtonCell.dataArray[indexPath].isSelected = false // id = (radioButton.titleLabel?.text)! // } // // for (i, value) in radioButtonCell.dataArray.enumerated() { // if i != indexPath { // radioButtonCell.dataArray[i].isSelected = false // radioButton.backgroundColor = UIColor.clear // // } // radioButtonCell.collectionView.reloadData() // } // // } func deselectOtherButton() { let tableView = self.superview?.superview as! UICollectionView let tappedCellIndexPath = tableView.indexPath(for: self)! let section = tappedCellIndexPath.section let rowCounts = tableView.numberOfItems(inSection: section) for row in 0..<rowCounts { if row != tappedCellIndexPath.row { let cell = tableView.cellForItem(at: IndexPath(row: row, section: section)) as! RadioColorCollectionViewCell //cell.buttonRadio.isSelected = false } } } }
32.810526
124
0.628168
1d4e9ed055056afc25f982823be6bc360ebc27d2
22,024
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// This enumeration defines the prediction modes available in ANTLR 4 along with /// utility methods for analyzing configuration sets for conflicts and/or /// ambiguities. /// public enum PredictionMode { /// /// The SLL(*) prediction mode. This prediction mode ignores the current /// parser context when making predictions. This is the fastest prediction /// mode, and provides correct results for many grammars. This prediction /// mode is more powerful than the prediction mode provided by ANTLR 3, but /// may result in syntax errors for grammar and input combinations which are /// not SLL. /// /// /// When using this prediction mode, the parser will either return a correct /// parse tree (i.e. the same parse tree that would be returned with the /// _#LL_ prediction mode), or it will report a syntax error. If a /// syntax error is encountered when using the _#SLL_ prediction mode, /// it may be due to either an actual syntax error in the input or indicate /// that the particular combination of grammar and input requires the more /// powerful _#LL_ prediction abilities to complete successfully. /// /// /// This prediction mode does not provide any guarantees for prediction /// behavior for syntactically-incorrect inputs. /// case SLL /// /// The LL(*) prediction mode. This prediction mode allows the current parser /// context to be used for resolving SLL conflicts that occur during /// prediction. This is the fastest prediction mode that guarantees correct /// parse results for all combinations of grammars with syntactically correct /// inputs. /// /// /// When using this prediction mode, the parser will make correct decisions /// for all syntactically-correct grammar and input combinations. However, in /// cases where the grammar is truly ambiguous this prediction mode might not /// report a precise answer for __exactly which__ alternatives are /// ambiguous. /// /// /// This prediction mode does not provide any guarantees for prediction /// behavior for syntactically-incorrect inputs. /// case LL /// /// The LL(*) prediction mode with exact ambiguity detection. In addition to /// the correctness guarantees provided by the _#LL_ prediction mode, /// this prediction mode instructs the prediction algorithm to determine the /// complete and exact set of ambiguous alternatives for every ambiguous /// decision encountered while parsing. /// /// /// This prediction mode may be used for diagnosing ambiguities during /// grammar development. Due to the performance overhead of calculating sets /// of ambiguous alternatives, this prediction mode should be avoided when /// the exact results are not necessary. /// /// /// This prediction mode does not provide any guarantees for prediction /// behavior for syntactically-incorrect inputs. /// case LL_EXACT_AMBIG_DETECTION /// /// Computes the SLL prediction termination condition. /// /// /// This method computes the SLL prediction termination condition for both of /// the following cases. /// /// * The usual SLL+LL fallback upon SLL conflict /// * Pure SLL without LL fallback /// /// __COMBINED SLL+LL PARSING__ /// /// When LL-fallback is enabled upon SLL conflict, correct predictions are /// ensured regardless of how the termination condition is computed by this /// method. Due to the substantially higher cost of LL prediction, the /// prediction should only fall back to LL when the additional lookahead /// cannot lead to a unique SLL prediction. /// /// Assuming combined SLL+LL parsing, an SLL configuration set with only /// conflicting subsets should fall back to full LL, even if the /// configuration sets don't resolve to the same alternative (e.g. /// `{1,2`} and `{3,4`}. If there is at least one non-conflicting /// configuration, SLL could continue with the hopes that more lookahead will /// resolve via one of those non-conflicting configurations. /// /// Here's the prediction termination rule them: SLL (for SLL+LL parsing) /// stops when it sees only conflicting configuration subsets. In contrast, /// full LL keeps going when there is uncertainty. /// /// __HEURISTIC__ /// /// As a heuristic, we stop prediction when we see any conflicting subset /// unless we see a state that only has one alternative associated with it. /// The single-alt-state thing lets prediction continue upon rules like /// (otherwise, it would admit defeat too soon): /// /// `[12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;` /// /// When the ATN simulation reaches the state before `';'`, it has a /// DFA state that looks like: `[12|1|[], 6|2|[], 12|2|[]]`. Naturally /// `12|1|[]` and `12|2|[]` conflict, but we cannot stop /// processing this node because alternative to has another way to continue, /// via `[6|2|[]]`. /// /// It also let's us continue for this rule: /// /// `[1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;` /// /// After matching input A, we reach the stop state for rule A, state 1. /// State 8 is the state right before B. Clearly alternatives 1 and 2 /// conflict and no amount of further lookahead will separate the two. /// However, alternative 3 will be able to continue and so we do not stop /// working on this state. In the previous example, we're concerned with /// states associated with the conflicting alternatives. Here alt 3 is not /// associated with the conflicting configs, but since we can continue /// looking for input reasonably, don't declare the state done. /// /// __PURE SLL PARSING__ /// /// To handle pure SLL parsing, all we have to do is make sure that we /// combine stack contexts for configurations that differ only by semantic /// predicate. From there, we can do the usual SLL termination heuristic. /// /// __PREDICATES IN SLL+LL PARSING__ /// /// SLL decisions don't evaluate predicates until after they reach DFA stop /// states because they need to create the DFA cache that works in all /// semantic situations. In contrast, full LL evaluates predicates collected /// during start state computation so it can ignore predicates thereafter. /// This means that SLL termination detection can totally ignore semantic /// predicates. /// /// Implementation-wise, _org.antlr.v4.runtime.atn.ATNConfigSet_ combines stack contexts but not /// semantic predicate contexts so we might see two configurations like the /// following. /// /// `(s, 1, x, {`), (s, 1, x', {p})} /// /// Before testing these configurations against others, we have to merge /// `x` and `x'` (without modifying the existing configurations). /// For example, we test `(x+x')==x''` when looking for conflicts in /// the following configurations. /// /// `(s, 1, x, {`), (s, 1, x', {p}), (s, 2, x'', {})} /// /// If the configuration set has predicates (as indicated by /// _org.antlr.v4.runtime.atn.ATNConfigSet#hasSemanticContext_), this algorithm makes a copy of /// the configurations to strip out all of the predicates so that a standard /// _org.antlr.v4.runtime.atn.ATNConfigSet_ will merge everything ignoring predicates. /// public static func hasSLLConflictTerminatingPrediction(_ mode: PredictionMode,_ configs: ATNConfigSet) -> Bool { var configs = configs /// /// Configs in rule stop states indicate reaching the end of the decision /// rule (local context) or end of start rule (full context). If all /// configs meet this condition, then none of the configurations is able /// to match additional input so we terminate prediction. /// if allConfigsInRuleStopStates(configs) { return true } // pure SLL mode parsing if mode == PredictionMode.SLL { // Don't bother with combining configs from different semantic // contexts if we can fail over to full LL; costs more time // since we'll often fail over anyway. if configs.hasSemanticContext { // dup configs, tossing out semantic predicates configs = configs.dupConfigsWithoutSemanticPredicates() } // now we have combined contexts for configs with dissimilar preds } // pure SLL or combined SLL+LL mode parsing let altsets = getConflictingAltSubsets(configs) let heuristic = hasConflictingAltSet(altsets) && !hasStateAssociatedWithOneAlt(configs) return heuristic } /// /// Checks if any configuration in `configs` is in a /// _org.antlr.v4.runtime.atn.RuleStopState_. Configurations meeting this condition have reached /// the end of the decision rule (local context) or end of start rule (full /// context). /// /// - parameter configs: the configuration set to test /// - returns: `true` if any configuration in `configs` is in a /// _org.antlr.v4.runtime.atn.RuleStopState_, otherwise `false` /// public static func hasConfigInRuleStopState(_ configs: ATNConfigSet) -> Bool { return configs.hasConfigInRuleStopState } /// /// Checks if all configurations in `configs` are in a /// _org.antlr.v4.runtime.atn.RuleStopState_. Configurations meeting this condition have reached /// the end of the decision rule (local context) or end of start rule (full /// context). /// /// - parameter configs: the configuration set to test /// - returns: `true` if all configurations in `configs` are in a /// _org.antlr.v4.runtime.atn.RuleStopState_, otherwise `false` /// public static func allConfigsInRuleStopStates(_ configs: ATNConfigSet) -> Bool { return configs.allConfigsInRuleStopStates } /// /// Full LL prediction termination. /// /// Can we stop looking ahead during ATN simulation or is there some /// uncertainty as to which alternative we will ultimately pick, after /// consuming more input? Even if there are partial conflicts, we might know /// that everything is going to resolve to the same minimum alternative. That /// means we can stop since no more lookahead will change that fact. On the /// other hand, there might be multiple conflicts that resolve to different /// minimums. That means we need more look ahead to decide which of those /// alternatives we should predict. /// /// The basic idea is to split the set of configurations `C`, into /// conflicting subsets `(s, _, ctx, _)` and singleton subsets with /// non-conflicting configurations. Two configurations conflict if they have /// identical _org.antlr.v4.runtime.atn.ATNConfig#state_ and _org.antlr.v4.runtime.atn.ATNConfig#context_ values /// but different _org.antlr.v4.runtime.atn.ATNConfig#alt_ value, e.g. `(s, i, ctx, _)` /// and `(s, j, ctx, _)` for `i!=j`. /// /// Reduce these configuration subsets to the set of possible alternatives. /// You can compute the alternative subsets in one pass as follows: /// /// `A_s,ctx = {i | (s, i, ctx, _)`} for each configuration in /// `C` holding `s` and `ctx` fixed. /// /// Or in pseudo-code, for each configuration `c` in `C`: /// /// /// map[c] U= c._org.antlr.v4.runtime.atn.ATNConfig#alt alt_ # map hash/equals uses s and x, not /// alt and not pred /// /// /// The values in `map` are the set of `A_s,ctx` sets. /// /// If `|A_s,ctx|=1` then there is no conflict associated with /// `s` and `ctx`. /// /// Reduce the subsets to singletons by choosing a minimum of each subset. If /// the union of these alternative subsets is a singleton, then no amount of /// more lookahead will help us. We will always pick that alternative. If, /// however, there is more than one alternative, then we are uncertain which /// alternative to predict and must continue looking for resolution. We may /// or may not discover an ambiguity in the future, even if there are no /// conflicting subsets this round. /// /// The biggest sin is to terminate early because it means we've made a /// decision but were uncertain as to the eventual outcome. We haven't used /// enough lookahead. On the other hand, announcing a conflict too late is no /// big deal; you will still have the conflict. It's just inefficient. It /// might even look until the end of file. /// /// No special consideration for semantic predicates is required because /// predicates are evaluated on-the-fly for full LL prediction, ensuring that /// no configuration contains a semantic context during the termination /// check. /// /// __CONFLICTING CONFIGS__ /// /// Two configurations `(s, i, x)` and `(s, j, x')`, conflict /// when `i!=j` but `x=x'`. Because we merge all /// `(s, i, _)` configurations together, that means that there are at /// most `n` configurations associated with state `s` for /// `n` possible alternatives in the decision. The merged stacks /// complicate the comparison of configuration contexts `x` and /// `x'`. Sam checks to see if one is a subset of the other by calling /// merge and checking to see if the merged result is either `x` or /// `x'`. If the `x` associated with lowest alternative `i` /// is the superset, then `i` is the only possible prediction since the /// others resolve to `min(i)` as well. However, if `x` is /// associated with `j>i` then at least one stack configuration for /// `j` is not in conflict with alternative `i`. The algorithm /// should keep going, looking for more lookahead due to the uncertainty. /// /// For simplicity, I'm doing a equality check between `x` and /// `x'` that lets the algorithm continue to consume lookahead longer /// than necessary. The reason I like the equality is of course the /// simplicity but also because that is the test you need to detect the /// alternatives that are actually in conflict. /// /// __CONTINUE/STOP RULE__ /// /// Continue if union of resolved alternative sets from non-conflicting and /// conflicting alternative subsets has more than one alternative. We are /// uncertain about which alternative to predict. /// /// The complete set of alternatives, `[i for (_,i,_)]`, tells us which /// alternatives are still in the running for the amount of input we've /// consumed at this point. The conflicting sets let us to strip away /// configurations that won't lead to more states because we resolve /// conflicts to the configuration with a minimum alternate for the /// conflicting set. /// /// __CASES__ /// /// * no conflicts and more than 1 alternative in set =&gt; continue /// /// * `(s, 1, x)`, `(s, 2, x)`, `(s, 3, z)`, /// `(s', 1, y)`, `(s', 2, y)` yields non-conflicting set /// `{3`} U conflicting sets `min({1,2`)} U `min({1,2`)} = /// `{1,3`} =&gt; continue /// /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 1, y)`, /// `(s', 2, y)`, `(s'', 1, z)` yields non-conflicting set /// `{1`} U conflicting sets `min({1,2`)} U `min({1,2`)} = /// `{1`} =&gt; stop and predict 1 /// /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 1, y)`, /// `(s', 2, y)` yields conflicting, reduced sets `{1`} U /// `{1`} = `{1`} =&gt; stop and predict 1, can announce /// ambiguity `{1,2`} /// /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 2, y)`, /// `(s', 3, y)` yields conflicting, reduced sets `{1`} U /// `{2`} = `{1,2`} =&gt; continue /// /// * `(s, 1, x)`, `(s, 2, x)`, `(s', 3, y)`, /// `(s', 4, y)` yields conflicting, reduced sets `{1`} U /// `{3`} = `{1,3`} =&gt; continue /// /// /// __EXACT AMBIGUITY DETECTION__ /// /// If all states report the same conflicting set of alternatives, then we /// know we have the exact ambiguity set. /// /// `|A_i__|&gt;1` and /// `A_i = A_j` for all i, j. /// /// In other words, we continue examining lookahead until all `A_i` /// have more than one alternative and all `A_i` are the same. If /// `A={{1,2`, {1,3}}}, then regular LL prediction would terminate /// because the resolved set is `{1`}. To determine what the real /// ambiguity is, we have to know whether the ambiguity is between one and /// two or one and three so we keep going. We can only stop prediction when /// we need exact ambiguity detection when the sets look like /// `A={{1,2`}} or `{{1,2`,{1,2}}}, etc... /// public static func resolvesToJustOneViableAlt(_ altsets: [BitSet]) -> Int { return getSingleViableAlt(altsets) } /// /// Determines if every alternative subset in `altsets` contains more /// than one alternative. /// /// - parameter altsets: a collection of alternative subsets /// - returns: `true` if every _java.util.BitSet_ in `altsets` has /// _java.util.BitSet#cardinality cardinality_ &gt; 1, otherwise `false` /// public static func allSubsetsConflict(_ altsets: [BitSet]) -> Bool { return !hasNonConflictingAltSet(altsets) } /// /// Determines if any single alternative subset in `altsets` contains /// exactly one alternative. /// /// - parameter altsets: a collection of alternative subsets /// - returns: `true` if `altsets` contains a _java.util.BitSet_ with /// _java.util.BitSet#cardinality cardinality_ 1, otherwise `false` /// public static func hasNonConflictingAltSet(_ altsets: [BitSet]) -> Bool { for alts: BitSet in altsets { if alts.cardinality() == 1 { return true } } return false } /// /// Determines if any single alternative subset in `altsets` contains /// more than one alternative. /// /// - parameter altsets: a collection of alternative subsets /// - returns: `true` if `altsets` contains a _java.util.BitSet_ with /// _java.util.BitSet#cardinality cardinality_ &gt; 1, otherwise `false` /// public static func hasConflictingAltSet(_ altsets: [BitSet]) -> Bool { for alts: BitSet in altsets { if alts.cardinality() > 1 { return true } } return false } /// /// Determines if every alternative subset in `altsets` is equivalent. /// /// - parameter altsets: a collection of alternative subsets /// - returns: `true` if every member of `altsets` is equal to the /// others, otherwise `false` /// public static func allSubsetsEqual(_ altsets: [BitSet]) -> Bool { let first: BitSet = altsets[0] for it in altsets { if it != first { return false } } return true } /// /// Returns the unique alternative predicted by all alternative subsets in /// `altsets`. If no such alternative exists, this method returns /// _org.antlr.v4.runtime.atn.ATN#INVALID_ALT_NUMBER_. /// /// - parameter altsets: a collection of alternative subsets /// public static func getUniqueAlt(_ altsets: [BitSet]) -> Int { let all: BitSet = getAlts(altsets) if all.cardinality() == 1 { return all.firstSetBit() } return ATN.INVALID_ALT_NUMBER } /// /// Gets the complete set of represented alternatives for a collection of /// alternative subsets. This method returns the union of each _java.util.BitSet_ /// in `altsets`. /// /// - parameter altsets: a collection of alternative subsets /// - returns: the set of represented alternatives in `altsets` /// public static func getAlts(_ altsets: Array<BitSet>) -> BitSet { let all: BitSet = BitSet() for alts: BitSet in altsets { all.or(alts) } return all } /// /// Get union of all alts from configs. - Since: 4.5.1 /// public static func getAlts(_ configs: ATNConfigSet) -> BitSet { return configs.getAltBitSet() } /// /// This function gets the conflicting alt subsets from a configuration set. /// For each configuration `c` in `configs`: /// /// /// map[c] U= c._org.antlr.v4.runtime.atn.ATNConfig#alt alt_ # map hash/equals uses s and x, not /// alt and not pred /// /// public static func getConflictingAltSubsets(_ configs: ATNConfigSet) -> [BitSet] { return configs.getConflictingAltSubsets() } public static func hasStateAssociatedWithOneAlt(_ configs: ATNConfigSet) -> Bool { let x = configs.getStateToAltMap() for alts in x.values { if alts.cardinality() == 1 { return true } } return false } public static func getSingleViableAlt(_ altsets: [BitSet]) -> Int { let viableAlts = BitSet() for alts in altsets { let minAlt = alts.firstSetBit() try! viableAlts.set(minAlt) if viableAlts.cardinality() > 1 { // more than 1 viable alt return ATN.INVALID_ALT_NUMBER } } return viableAlts.firstSetBit() } }
42.931774
116
0.633082
fb5868c216924fad85d769dfb647ebb80f2bb999
292
// // Timestamp.swift // Observed_Example // // Created by Oleksii Horishnii on 10/24/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation struct Timestamp { // notice how there is no support fields, just what entity actually represents let time: Date }
19.466667
82
0.708904
333a73e058e9d39050ba8c301af88a5f234c3370
2,737
/*  * CreateLDAPObjectsOperation.swift  * OfficeKit  *  * Created by François Lamboley on 19/07/2018.  */ import Foundation import RetryingOperation import COpenLDAP /* Most of this class is adapted from https://github.com/PerfectlySoft/Perfect-LDAP/blob/3ec5155c2a3efa7aa64b66353024ed36ae77349b/Sources/PerfectLDAP/PerfectLDAP.swift */ /** Result is an array of LDAPObject (the objects created). The operation as a whole does not fail from the `HasResult` protocol point of view. If all users failed to be created, the result will simply be an empty array. You should access the errors array to get the errors that happened while creating the objects. There is one optional error per object created. If the error is nil for a given object, it means the object has successfully been created, otherwise the error tells you what went wrong. */ public final class CreateLDAPObjectsOperation : RetryingOperation, HasResult { public typealias ResultType = [Result<LDAPObject, Error>] public let connector: LDAPConnector public let objects: [LDAPObject] public private(set) var errors: [Error?] public var result: Result<[Result<LDAPObject, Error>], Error> { return .success(objects.enumerated().map{ if let e = errors[$0.offset] {return .failure(e)} return .success($0.element) }) } public convenience init(users: [LDAPInetOrgPerson], connector c: LDAPConnector) { self.init(objects: users.map{ $0.ldapObject() }, connector: c) } public init(objects o: [LDAPObject], connector c: LDAPConnector) { objects = o connector = c errors = [Error?](repeating: OperationIsNotFinishedError(), count: o.count) } public override var isAsynchronous: Bool { return false } public override func startBaseOperation(isRetry: Bool) { assert(connector.isConnected) assert(objects.count == errors.count) for (idx, object) in objects.enumerated() { /* TODO: Check we do not leak. We should not, though. */ var ldapModifsRequest = object.attributes.map{ v -> UnsafeMutablePointer<LDAPMod>? in ldapModAlloc(method: LDAP_MOD_ADD | LDAP_MOD_BVALUES, key: v.key, values: v.value) } + [nil] defer {ldap_mods_free(&ldapModifsRequest, 0)} /* We use the synchronous version of the function. See long comment in  * search operation for details. */ let r = connector.performLDAPCommunication{ ldap_add_ext_s($0, object.distinguishedName.stringValue, &ldapModifsRequest, nil /* Server controls */, nil /* Client controls */) } if r == LDAP_SUCCESS {errors[idx] = nil} else {errors[idx] = NSError(domain: "com.happn.officectl.openldap", code: Int(r), userInfo: [NSLocalizedDescriptionKey: String(cString: ldap_err2string(r))])} } baseOperationEnded() } }
35.545455
181
0.736208
264a34da3dff7a6806cfd48d3a451ce091f092c1
14,487
// // CollectionViewPagingLayout.swift // CollectionViewPagingLayout // // Created by Amir Khorsandi on 12/23/19. // Copyright © 2019 Amir Khorsandi. All rights reserved. // import UIKit public protocol CollectionViewPagingLayoutDelegate: AnyObject { /// Calls when the current page changes /// /// - Parameter layout: a reference to the layout class /// - Parameter currentPage: the new current page index func onCurrentPageChanged(layout: CollectionViewPagingLayout, currentPage: Int) } public extension CollectionViewPagingLayoutDelegate { func onCurrentPageChanged(layout: CollectionViewPagingLayout, currentPage: Int) {} } public class CollectionViewPagingLayout: UICollectionViewLayout { // MARK: Properties /// Number of visible items at the same time /// /// nil = no limit public var numberOfVisibleItems: Int? /// Constants that indicate the direction of scrolling for the layout. public var scrollDirection: UICollectionView.ScrollDirection = .horizontal /// See `ZPositionHandler` for details public var zPositionHandler: ZPositionHandler = .both /// Set `alpha` to zero when the cell is not loaded yet by collection view public var transparentAttributeWhenCellNotLoaded: Bool = true /// The animator for setting `contentOffset` /// /// See `ViewAnimator` for details public var defaultAnimator: ViewAnimator? public private(set) var isAnimating: Bool = false public weak var delegate: CollectionViewPagingLayoutDelegate? override public var collectionViewContentSize: CGSize { getContentSize() } /// Current page index /// /// Use `setCurrentPage` to change it public private(set) var currentPage: Int = 0 { didSet { delegate?.onCurrentPageChanged(layout: self, currentPage: currentPage) } } private var currentScrollOffset: CGFloat { let visibleRect = self.visibleRect return scrollDirection == .horizontal ? (visibleRect.minX / max(visibleRect.width, 1)) : (visibleRect.minY / max(visibleRect.height, 1)) } private var visibleRect: CGRect { collectionView.map { CGRect(origin: $0.contentOffset, size: $0.bounds.size) } ?? .zero } private var numberOfItems: Int { guard let numberOfSections = collectionView?.numberOfSections, numberOfSections > 0 else { return 0 } return (0..<numberOfSections) .compactMap { collectionView?.numberOfItems(inSection: $0) } .reduce(0, +) } private var currentPageCache: Int? private var attributesCache: [(page: Int, attributes: UICollectionViewLayoutAttributes)]? private var boundsObservation: NSKeyValueObservation? private var lastBounds: CGRect? private var currentViewAnimatorCancelable: ViewAnimatorCancelable? private var originalIsUserInteractionEnabled: Bool? private var contentOffsetObservation: NSKeyValueObservation? // MARK: Public functions public func setCurrentPage(_ page: Int, animated: Bool = true, animator: ViewAnimator? = nil, completion: (() -> Void)? = nil) { safelySetCurrentPage(page, animated: animated, animator: animator, completion: completion) } public func setCurrentPage(_ page: Int, animated: Bool = true, completion: (() -> Void)? = nil) { safelySetCurrentPage(page, animated: animated, animator: defaultAnimator, completion: completion) } public func goToNextPage(animated: Bool = true, animator: ViewAnimator? = nil, completion: (() -> Void)? = nil) { setCurrentPage(currentPage + 1, animated: animated, animator: animator, completion: completion) } public func goToPreviousPage(animated: Bool = true, animator: ViewAnimator? = nil, completion: (() -> Void)? = nil) { setCurrentPage(currentPage - 1, animated: animated, animator: animator, completion: completion) } /// Calls `invalidateLayout` wrapped in `performBatchUpdates` /// - Parameter invalidateOffset: change offset and revert it immediately /// this fixes the zIndex issue more: https://stackoverflow.com/questions/12659301/uicollectionview-setlayoutanimated-not-preserving-zindex public func invalidateLayoutInBatchUpdate(invalidateOffset: Bool = false) { DispatchQueue.main.async { [weak self] in if invalidateOffset, let collectionView = self?.collectionView, self?.isAnimating == false { let original = collectionView.contentOffset collectionView.contentOffset = .init(x: original.x + 1, y: original.y + 1) collectionView.contentOffset = original } self?.collectionView?.performBatchUpdates({ [weak self] in self?.invalidateLayout() }) } } // MARK: UICollectionViewLayout override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { if newBounds.size != visibleRect.size { currentPageCache = currentPage } return true } override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let currentScrollOffset = self.currentScrollOffset let numberOfItems = self.numberOfItems let attributesCount = numberOfVisibleItems ?? numberOfItems let visibleRangeMid = attributesCount / 2 let currentPageIndex = Int(round(currentScrollOffset)) var initialStartIndex = currentPageIndex - visibleRangeMid var initialEndIndex = currentPageIndex + visibleRangeMid if attributesCount % 2 != 0 { if currentPageIndex < visibleRangeMid { initialStartIndex -= 1 } else { initialEndIndex += 1 } } let startIndexOutOfBounds = max(0, -initialStartIndex) let endIndexOutOfBounds = max(0, initialEndIndex - numberOfItems) let startIndex = max(0, initialStartIndex - endIndexOutOfBounds) let endIndex = min(numberOfItems, initialEndIndex + startIndexOutOfBounds) var attributesArray: [(page: Int, attributes: UICollectionViewLayoutAttributes)] = [] var section = 0 var numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0 var numberOfItemsInPrevSections = 0 for index in startIndex..<endIndex { var item = index - numberOfItemsInPrevSections while item >= numberOfItemsInSection { numberOfItemsInPrevSections += numberOfItemsInSection section += 1 numberOfItemsInSection = collectionView?.numberOfItems(inSection: section) ?? 0 item = index - numberOfItemsInPrevSections } let cellAttributes = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: item, section: section)) let pageIndex = CGFloat(index) let progress = pageIndex - currentScrollOffset var zIndex = Int(-abs(round(progress))) let cell = collectionView?.cellForItem(at: cellAttributes.indexPath) if let cell = cell as? TransformableView { cell.transform(progress: progress) zIndex = cell.zPosition(progress: progress) } if cell == nil || cell is TransformableView { cellAttributes.frame = visibleRect if cell == nil, transparentAttributeWhenCellNotLoaded { cellAttributes.alpha = 0 } } else { cellAttributes.frame = CGRect(origin: CGPoint(x: pageIndex * visibleRect.width, y: 0), size: visibleRect.size) } // In some cases attribute.zIndex doesn't work so this is the work-around if let cell = cell, [ZPositionHandler.both, .cellLayer].contains(zPositionHandler) { cell.layer.zPosition = CGFloat(zIndex) } if [ZPositionHandler.both, .layoutAttribute].contains(zPositionHandler) { cellAttributes.zIndex = zIndex } attributesArray.append((page: Int(pageIndex), attributes: cellAttributes)) } attributesCache = attributesArray addBoundsObserverIfNeeded() return attributesArray.map(\.attributes) } override public func invalidateLayout() { super.invalidateLayout() if let page = currentPageCache { setCurrentPage(page, animated: false) currentPageCache = nil } else { updateCurrentPageIfNeeded() } } // MARK: Private functions private func updateCurrentPageIfNeeded() { var currentPage: Int = 0 if let collectionView = collectionView { let contentOffset = collectionView.contentOffset let pageSize = scrollDirection == .horizontal ? collectionView.frame.width : collectionView.frame.height let offset = scrollDirection == .horizontal ? (contentOffset.x + collectionView.contentInset.left) : (contentOffset.y + collectionView.contentInset.top) if pageSize > 0 { currentPage = Int(round(offset / pageSize)) } } if currentPage != self.currentPage, !isAnimating { self.currentPage = currentPage } } private func getContentSize() -> CGSize { var safeAreaLeftRight: CGFloat = 0 var safeAreaTopBottom: CGFloat = 0 if #available(iOS 11, *) { safeAreaLeftRight = (collectionView?.safeAreaInsets.left ?? 0) + (collectionView?.safeAreaInsets.right ?? 0) safeAreaTopBottom = (collectionView?.safeAreaInsets.top ?? 0) + (collectionView?.safeAreaInsets.bottom ?? 0) } if scrollDirection == .horizontal { return CGSize(width: CGFloat(numberOfItems) * visibleRect.width, height: visibleRect.height - safeAreaTopBottom) } else { return CGSize(width: visibleRect.width - safeAreaLeftRight, height: CGFloat(numberOfItems) * visibleRect.height) } } private func safelySetCurrentPage(_ page: Int, animated: Bool, animator: ViewAnimator?, completion: (() -> Void)? = nil) { if isAnimating { currentViewAnimatorCancelable?.cancel() isAnimating = false if let isEnabled = originalIsUserInteractionEnabled { collectionView?.isUserInteractionEnabled = isEnabled } } let pageSize = scrollDirection == .horizontal ? visibleRect.width : visibleRect.height let contentSize = scrollDirection == .horizontal ? collectionViewContentSize.width : collectionViewContentSize.height let maxPossibleOffset = contentSize - pageSize var offset = Double(pageSize) * Double(page) offset = max(0, offset) offset = min(offset, Double(maxPossibleOffset)) let contentOffset: CGPoint = scrollDirection == .horizontal ? CGPoint(x: offset, y: 0) : CGPoint(x: 0, y: offset) if animated { isAnimating = true } if animated, let animator = animator { setContentOffset(with: animator, offset: contentOffset, completion: completion) } else { contentOffsetObservation = collectionView?.observe(\.contentOffset, options: [.new]) { [weak self] _, _ in if self?.collectionView?.contentOffset == contentOffset { self?.contentOffsetObservation = nil DispatchQueue.main.async { [weak self] in self?.invalidateLayoutInBatchUpdate() self?.collectionView?.setContentOffset(contentOffset, animated: false) self?.isAnimating = false completion?() } } } collectionView?.setContentOffset(contentOffset, animated: animated) } // this is necessary when we want to set the current page without animation if !animated, page != currentPage { invalidateLayoutInBatchUpdate() } } private func setContentOffset(with animator: ViewAnimator, offset: CGPoint, completion: (() -> Void)? = nil) { guard let start = collectionView?.contentOffset else { return } let x = offset.x - start.x let y = offset.y - start.y originalIsUserInteractionEnabled = collectionView?.isUserInteractionEnabled ?? true collectionView?.isUserInteractionEnabled = false currentViewAnimatorCancelable = animator.animate { [weak self] progress, finished in guard let collectionView = self?.collectionView else { return } collectionView.contentOffset = CGPoint(x: start.x + x * CGFloat(progress), y: start.y + y * CGFloat(progress)) if finished { self?.currentViewAnimatorCancelable = nil self?.isAnimating = false self?.collectionView?.isUserInteractionEnabled = self?.originalIsUserInteractionEnabled ?? true self?.originalIsUserInteractionEnabled = nil self?.collectionView?.delegate?.scrollViewDidEndScrollingAnimation?(collectionView) self?.invalidateLayoutInBatchUpdate() completion?() } } } } extension CollectionViewPagingLayout { private func addBoundsObserverIfNeeded() { guard boundsObservation == nil else { return } boundsObservation = collectionView?.observe(\.bounds, options: [.old, .new, .initial, .prior]) { [weak self] collectionView, _ in guard collectionView.bounds.size != self?.lastBounds?.size else { return } self?.lastBounds = collectionView.bounds self?.invalidateLayoutInBatchUpdate(invalidateOffset: true) } } }
42.608824
144
0.626769
899b1b758403e65dceb33576ece0fba3c3953df2
1,789
// // Copyright (C) 2005-2020 Alfresco Software Limited. // // This file is part of the Alfresco Content Mobile iOS App. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit protocol PageFetchableDelegate: AnyObject { func fetchNextContentPage(for collectionView: UICollectionView, itemAtIndexPath: IndexPath) func isPaginationEnabled() -> Bool } class PageFetchableCollectionView: UICollectionView { weak var pageDelegate: PageFetchableDelegate? private var lastItemIndexPath: IndexPath? required init?(coder: NSCoder) { super.init(coder: coder) self.prefetchDataSource = self } override func layoutSubviews() { super.layoutSubviews() lastItemIndexPath = self.lastItemIndexPath() } } extension PageFetchableCollectionView: UICollectionViewDataSourcePrefetching { func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { guard let isPaginationEnabled = pageDelegate?.isPaginationEnabled() else { return } if isPaginationEnabled { for indexPath in indexPaths where indexPath == lastItemIndexPath { pageDelegate?.fetchNextContentPage(for: self, itemAtIndexPath: indexPath) } } } }
33.12963
102
0.726104
fe8a152f1805d534ef28e9433ca488bbe4a66dcd
1,158
// // TinderAppUITests.swift // TinderAppUITests // // Created by paul on 10/19/18. // Copyright © 2018 PoHung Wang. All rights reserved. // import XCTest class TinderAppUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.085714
182
0.689983
ef1cc2a2e6cc48a865c2ba8aace095f756733f53
690
// // LandmarksApp.swift // Landmarks // // Created by Hunter Gai on 2022/3/19. // import SwiftUI @main struct LandmarksApp: App { @StateObject private var modelData = ModelData() var body: some Scene { WindowGroup { ContentView() .environmentObject(modelData) } #if !os(watchOS) .commands { LandmarkCommands() } #endif #if os(watchOS) WKNotificationScene(controller: NotificationController.self, category: "LandmarkNear") #endif #if os(macOS) Settings { LandmarkSettings() } #endif } }
20.294118
98
0.526087
676fb42992282932840adfe0820ab046c3338133
2,181
// // AppDelegate.swift // SKGridTableView // // Created by shengkaiyan on 01/04/2019. // Copyright (c) 2019 shengkaiyan. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.404255
285
0.755617
7aebba7366bb0656eadcea376477e06146cb8d1d
856
//: Playground - noun: a place where people can play import UIKit // generic type let arr = Array<Int>() let dict = Dictionary<String,Int>() let set = Set<Float>() struct Stack<T>{ var items = [T]() func isEmpty() -> Bool{ return items.count == 0 } mutating func push(item: T){ items.append(item) } mutating func pop() -> T?{ guard !self.isEmpty() else{ return nil } return items.removeLast() } } extension Stack{ func top() -> T?{ return items.last } func count() -> Int{ return items.count } } var s = Stack<Int>() s.push(1) s.push(2) s.pop() var ss = Stack<String>() struct Pair<T1,T2>{ var a: T1 var b: T2 } var pair = Pair<Int,String>(a: 0 , b: "Hello") pair
13.375
52
0.509346
2673e1f173dabf58fb43f7874974d863dedd4621
1,131
import UIKit enum Polygon { case triangle, quadrilateral, pentagon, hexagon func description() -> String { switch self { case .triangle: return "A triangle is a polygon with three egdes" case .quadrilateral: return "A quadrilateral is a polygon with four egdes" case .pentagon: return "A pentagon is a polygon with five egdes" case .hexagon: return "An hexagon is a polygon with six egdes" } } } let pentagon = Polygon.pentagon print(pentagon.description()) // Example of mutating methods enum Alarm { case enabled, disabled mutating func newReading(temperature: Double) { if (temperature > 300) { self = .enabled } else { self = .disabled } } func description() -> String { switch self { case .enabled: return "Alarm is enabled" case .disabled: return "Alarm is disabled" } } } var ovenAlarm = Alarm.disabled ovenAlarm.newReading(temperature: 340) print(ovenAlarm.description())
23.5625
65
0.587091
db54bf857cb8c6eb0dff2bf668fb07ea34369a36
4,267
// // Copyright (c) 2018 KxCoding <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class EditModeViewController: UIViewController { var editingSwitch: UISwitch! @IBOutlet weak var listTableView: UITableView! var productList = ["iMac Pro", "iMac 5K", "Macbook Pro", "iPad Pro", "iPhone X", "Mac mini", "Apple TV", "Apple Watch"] var selectedList = [String]() @objc func toggleEditMode(_ sender: UISwitch) { } @objc func emptySelectedList() { } override func viewDidLoad() { super.viewDidLoad() editingSwitch = UISwitch(frame: .zero) editingSwitch.addTarget(self, action: #selector(toggleEditMode(_:)), for: .valueChanged) let deleteButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(emptySelectedList)) deleteButton.tintColor = UIColor.red navigationItem.rightBarButtonItems = [deleteButton, UIBarButtonItem(customView: editingSwitch)] } } extension EditModeViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return selectedList.count case 1: return productList.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) switch indexPath.section { case 0: cell.textLabel?.text = selectedList[indexPath.row] case 1: cell.textLabel?.text = productList[indexPath.row] default: break } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Selected List" case 1: return "Product List" default: return nil } } } extension EditModeViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { let target = productList[indexPath.row] let insertIndexPath = IndexPath(row: selectedList.count, section: 0) selectedList.append(target) productList.remove(at: indexPath.row) if #available(iOS 11.0, *) { listTableView.performBatchUpdates({ [weak self] in self?.listTableView.insertRows(at: [insertIndexPath], with: .automatic) self?.listTableView.deleteRows(at: [indexPath], with: .automatic) }, completion: nil) } else { listTableView.beginUpdates() listTableView.insertRows(at: [insertIndexPath], with: .automatic) listTableView.deleteRows(at: [indexPath], with: .automatic) listTableView.endUpdates() } } }
30.697842
123
0.647528
1d15f55bfe42686496254e797cab10c81d118913
11,160
import CLibMongoC import Foundation import NIO /// Direct wrapper of a `mongoc_change_stream_t`. private struct MongocChangeStream: MongocCursorWrapper { internal let pointer: OpaquePointer internal static var isLazy: Bool { false } fileprivate init(stealing ptr: OpaquePointer) { self.pointer = ptr } internal func errorDocument(bsonError: inout bson_error_t, replyPtr: UnsafeMutablePointer<BSONPointer?>) -> Bool { mongoc_change_stream_error_document(self.pointer, &bsonError, replyPtr) } internal func next(outPtr: UnsafeMutablePointer<BSONPointer?>) -> Bool { mongoc_change_stream_next(self.pointer, outPtr) } internal func more() -> Bool { true } internal func destroy() { mongoc_change_stream_destroy(self.pointer) } } /// A token used for manually resuming a change stream. Pass this to the `resumeAfter` field of /// `ChangeStreamOptions` to resume or start a change stream where a previous one left off. /// - SeeAlso: https://docs.mongodb.com/manual/changeStreams/#resume-a-change-stream public struct ResumeToken: Codable, Equatable { private let resumeToken: Document internal init(_ resumeToken: Document) { self.resumeToken = resumeToken } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(self.resumeToken) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() self.resumeToken = try container.decode(Document.self) } } // sourcery: skipSyncExport /// A MongoDB change stream. /// - SeeAlso: https://docs.mongodb.com/manual/changeStreams/ public class ChangeStream<T: Codable>: CursorProtocol { internal typealias Element = T /// The client this change stream descended from. private let client: MongoClient /// Decoder for decoding documents into type `T`. private let decoder: BSONDecoder /// The cursor this change stream is wrapping. private let wrappedCursor: Cursor<MongocChangeStream> /// Process an event before returning it to the user, or does nothing and returns nil if the provided event is nil. private func processEvent(_ event: Document?) throws -> T? { guard let event = event else { return nil } return try self.processEvent(event) } /// Process an event before returning it to the user. private func processEvent(_ event: Document) throws -> T { // Update the resumeToken with the `_id` field from the document. guard let resumeToken = event["_id"]?.documentValue else { throw InternalError(message: "_id field is missing from the change stream document.") } self.resumeToken = ResumeToken(resumeToken) return try self.decoder.decode(T.self, from: event) } internal init( stealing changeStreamPtr: OpaquePointer, connection: Connection, client: MongoClient, session: ClientSession?, decoder: BSONDecoder, options: ChangeStreamOptions? ) throws { let mongocChangeStream = MongocChangeStream(stealing: changeStreamPtr) self.wrappedCursor = try Cursor( mongocCursor: mongocChangeStream, connection: connection, session: session, type: .tailableAwait ) self.client = client self.decoder = decoder // TODO: SWIFT-519 - Starting 4.2, update resumeToken to startAfter (if set). // startAfter takes precedence over resumeAfter. if let resumeAfter = options?.resumeAfter { self.resumeToken = resumeAfter } } /// Indicates whether this change stream has the potential to return more data. public func isAlive() -> EventLoopFuture<Bool> { self.client.operationExecutor.execute { self.wrappedCursor.isAlive } } /// The `ResumeToken` associated with the most recent event seen by the change stream. public internal(set) var resumeToken: ResumeToken? /** * Get the next `T` from this change stream. * * This method will continue polling until an event is returned from the server, an error occurs, * or the change stream is killed. Each attempt to retrieve results will wait for a maximum of `maxAwaitTimeMS` * (specified on the `ChangeStreamOptions` passed to the method that created this change stream) before trying * again. * * A thread from the driver's internal thread pool will be occupied until the returned future is completed, so * performance degradation is possible if the number of polling change streams is too close to the total number of * threads in the thread pool. To configure the total number of threads in the pool, set the * `ClientOptions.threadPoolSize` option during client creation. * * Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from * this method is unresolved. Doing so will result in undefined behavior. * * - Returns: * An `EventLoopFuture<T?>` evaluating to the next `T` in this change stream, `nil` if the change stream is * exhausted, or an error if one occurred. The returned future will not resolve until one of those conditions is * met, potentially after multiple requests to the server. * * If the future evaluates to an error, it is likely one of the following: * - `CommandError` if an error occurs while fetching more results from the server. * - `LogicError` if this function is called after the change stream has died. * - `LogicError` if this function is called and the session associated with this change stream is inactive. * - `DecodingError` if an error occurs decoding the server's response. */ public func next() -> EventLoopFuture<T?> { self.client.operationExecutor.execute { try self.processEvent(self.wrappedCursor.next()) } } /** * Attempt to get the next `T` from this change stream, returning `nil` if there are no results. * * The change stream will wait server-side for a maximum of `maxAwaitTimeMS` (specified on the `ChangeStreamOptions` * passed to the method that created this change stream) before returning `nil`. * * This method may be called repeatedly while `isAlive` is true to retrieve new data. * * Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from * this method is unresolved. Doing so will result in undefined behavior. * * - Returns: * An `EventLoopFuture<T?>` containing the next `T` in this change stream, an error if one occurred, or `nil` if * there was no data. * * If the future evaluates to an error, it is likely one of the following: * - `CommandError` if an error occurs while fetching more results from the server. * - `LogicError` if this function is called after the change stream has died. * - `LogicError` if this function is called and the session associated with this change stream is inactive. * - `DecodingError` if an error occurs decoding the server's response. */ public func tryNext() -> EventLoopFuture<T?> { self.client.operationExecutor.execute { try self.processEvent(self.wrappedCursor.tryNext()) } } /** * Consolidate the currently available results of the change stream into an array of type `T`. * * Since `toArray` will only fetch the currently available results, it may return more data if it is called again * while the change stream is still alive. * * Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from * this method is unresolved. Doing so will result in undefined behavior. * * - Returns: * An `EventLoopFuture<[T]>` evaluating to the results currently available in this change stream, or an error. * * If the future evaluates to an error, that error is likely one of the following: * - `CommandError` if an error occurs while fetching more results from the server. * - `LogicError` if this function is called after the change stream has died. * - `LogicError` if this function is called and the session associated with this change stream is inactive. * - `DecodingError` if an error occurs decoding the server's responses. */ public func toArray() -> EventLoopFuture<[T]> { self.client.operationExecutor.execute { try self.wrappedCursor.toArray().map(self.processEvent) } } /** * Calls the provided closure with each event in the change stream as it arrives. * * A thread from the driver's internal thread pool will be occupied until the returned future is completed, so * performance degradation is possible if the number of polling change streams is too close to the total number of * threads in the thread pool. To configure the total number of threads in the pool, set the * `ClientOptions.threadPoolSize` option during client creation. * * Note: You *must not* call any change stream methods besides `kill` and `isAlive` while the future returned from * this method is unresolved. Doing so will result in undefined behavior. * * - Returns: * An `EventLoopFuture<Void>` which will complete once the change stream is closed or once an error is * encountered. * * If the future evaluates to an error, that error is likely one of the following: * - `CommandError` if an error occurs while fetching more results from the server. * - `LogicError` if this function is called after the change stream has died. * - `LogicError` if this function is called and the session associated with this change stream is inactive. * - `DecodingError` if an error occurs decoding the server's responses. */ public func forEach(_ body: @escaping (T) throws -> Void) -> EventLoopFuture<Void> { self.client.operationExecutor.execute { while let next = try self.processEvent(self.wrappedCursor.next()) { try body(next) } } } /** * Kill this change stream. * * This method MUST be called before this change stream goes out of scope to prevent leaking resources. * This method may be called even if there are unresolved futures created from other `ChangeStream` methods. * This method will have no effect if the change stream is already dead. * * - Returns: * An `EventLoopFuture` that evaluates when the change stream has completed closing. This future should not fail. */ public func kill() -> EventLoopFuture<Void> { self.client.operationExecutor.execute { self.wrappedCursor.kill() } } }
44.64
120
0.677509
e56ea32fdea24ced804f9e0b93cf6a3b756d3d4f
698
import UIKit class NoteDetailViewController: UIViewController { var theNote = Note() @IBOutlet weak var noteTitleLabel: UITextField! @IBOutlet weak var noteTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() self.noteTitleLabel.text = theNote.noteTitle self.noteTextView.text = theNote.noteText self.noteTextView.becomeFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { theNote.noteTitle = self.noteTitleLabel.text theNote.noteText = self.noteTextView.text } }
21.8125
81
0.618911