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
67f70f7c2ca4d8880d6b5713d04307f6e7d6a265
1,539
// // MenuDataSource.swift // ExampleOfiOSLiDAR // // Created by TokyoYoshida on 2021/01/31. // import UIKit struct MenuItem { let title: String let description: String let prefix: String func viewController() -> UIViewController { let storyboard = UIStoryboard(name: prefix, bundle: nil) let vc = storyboard.instantiateInitialViewController()! vc.title = title return vc } } class MenuViewModel { private let dataSource = [ MenuItem ( title: "Depth Map", description: "Display the depth map on the screen.", prefix: "DepthMap" ), MenuItem ( title: "Confidence Map", description: "Display the confidence on the screen.", prefix: "ConfidenceMap" ), MenuItem ( title: "Collision", description: "Collision detection of objects using LiDAR.", prefix: "Collision" ), MenuItem ( title: "Export", description: "Export scaned object to .obj file.", prefix: "Export" ), MenuItem ( title: "Scan with Texture", description: "Scan object with color texture.", prefix: "Scan" ) ] var count: Int { dataSource.count } func item(row: Int) -> MenuItem { dataSource[row] } func viewController(row: Int) -> UIViewController { dataSource[row].viewController() } }
23.676923
71
0.547758
ccdc02693851e57f1a33e9b249730d34aa452b7d
16,248
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: MinMaxType /** Types of properties which can be used with the minimum and maximum value APIs. - see: `min(ofProperty:)`, `max(ofProperty:)` */ public protocol MinMaxType {} extension NSNumber: MinMaxType {} extension Double: MinMaxType {} extension Float: MinMaxType {} extension Int: MinMaxType {} extension Int8: MinMaxType {} extension Int16: MinMaxType {} extension Int32: MinMaxType {} extension Int64: MinMaxType {} extension Date: MinMaxType {} extension NSDate: MinMaxType {} extension Decimal128: MinMaxType {} // MARK: AddableType /** Types of properties which can be used with the sum and average value APIs. - see: `sum(ofProperty:)`, `average(ofProperty:)` */ public protocol AddableType { /// :nodoc: init() } extension NSNumber: AddableType {} extension Double: AddableType {} extension Float: AddableType {} extension Int: AddableType {} extension Int8: AddableType {} extension Int16: AddableType {} extension Int32: AddableType {} extension Int64: AddableType {} extension Decimal128: AddableType {} /** `Results` is an auto-updating container type in Realm returned from object queries. `Results` can be queried with the same predicates as `List<Element>`, and you can chain queries to further filter query results. `Results` always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration. `Results` are lazily evaluated the first time they are accessed; they only run queries when the result of the query is requested. This means that chaining several temporary `Results` to sort and filter your data does not perform any unnecessary work processing the intermediate state. Once the results have been evaluated or a notification block has been added, the results are eagerly kept up-to-date, with the work done to keep them up-to-date done on a background thread whenever possible. Results instances cannot be directly instantiated. */ public struct Results<Element: RealmCollectionValue>: Equatable { internal let rlmResults: RLMResults<AnyObject> /// A human-readable description of the objects represented by the results. public var description: String { return RLMDescriptionWithMaxDepth("Results", rlmResults, RLMDescriptionMaxDepth) } /// The type of the objects described by the results. public typealias ElementType = Element // MARK: Properties /// The Realm which manages this results. Note that this property will never return `nil`. public var realm: Realm? { return Realm(rlmResults.realm) } /** Indicates if the results are no longer valid. The results becomes invalid if `invalidate()` is called on the containing `realm`. An invalidated results can be accessed, but will always be empty. */ public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of objects in the results. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers internal init(_ rlmResults: RLMResults<AnyObject>) { self.rlmResults = rlmResults } internal init(objc rlmResults: RLMResults<AnyObject>) { self.rlmResults = rlmResults } // MARK: Index Retrieval /** Returns the index of the given object in the results, or `nil` if the object is not present. */ public func index(of object: Element) -> Int? { return notFoundToNil(index: rlmResults.index(of: object as AnyObject)) } /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> Element { throwForNegativeIndex(position) return dynamicBridgeCast(fromObjectiveC: rlmResults.object(at: UInt(position))) } /// Returns the first object in the results, or `nil` if the results are empty. public var first: Element? { return rlmResults.firstObject().map(dynamicBridgeCast) } /// Returns the last object in the results, or `nil` if the results are empty. public var last: Element? { return rlmResults.lastObject().map(dynamicBridgeCast) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the results. - parameter key: The name of the property whose values are desired. */ public func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the results. - parameter keyPath: The key path to the property whose values are desired. */ public func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the objects represented by the results using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return Results<Element>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects represented by the results, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects represented by the results, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return Results<Element>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } /** Returns a `Results` containing distinct objects based on the specified key paths - parameter keyPaths: The key paths used produce distinct results */ public func distinct<S: Sequence>(by keyPaths: S) -> Results<Element> where S.Iterator.Element == String { return Results<Element>(rlmResults.distinctResults(usingKeyPaths: Array(keyPaths))) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the results, or `nil` if the results are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<T: MinMaxType>(ofProperty property: String) -> T? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the results. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<T: AddableType>(ofProperty property: String) -> T { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the results, or `nil` if the results are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<T: AddableType>(ofProperty property: String) -> T? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let dogs = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.observe { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `invalidate()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter queue: The serial dispatch queue to receive notification on. If `nil`, notifications are delivered to the current thread. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func observe(on queue: DispatchQueue? = nil, _ block: @escaping (RealmCollectionChange<Results>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock(wrapObserveBlock(block), queue: queue) } // MARK: Frozen Objects public var isFrozen: Bool { return rlmResults.isFrozen } public func freeze() -> Results { return Results(rlmResults.freeze()) } } extension Results: RealmCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the results. public func makeIterator() -> RLMIterator<Element> { return RLMIterator(collection: rlmResults) } /// :nodoc: // swiftlint:disable:next identifier_name public func _asNSFastEnumerator() -> Any { return rlmResults } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: // swiftlint:disable:next identifier_name public func _observe(_ queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock(wrapObserveBlock(block), queue: queue) } } // MARK: AssistedObjectiveCBridgeable extension Results: AssistedObjectiveCBridgeable { internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Results { return Results(objectiveCValue as! RLMResults) } internal var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: rlmResults, metadata: nil) } } // MARK: - Codable extension Results: Encodable where Element: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for value in self { try container.encode(value) } } }
38.140845
120
0.689377
569356fc1426a0a9547c43c290e18e084116c3ea
1,058
extension NatTag { /** Style represents styles values for the NatTag component. These are all allowed styles for a NatTag: - default (centered) - left - right */ public struct Style { let applyStyle: (NatTag) -> Void public static var defaultAlert: NatTag.Style { .init { tag in NatTagStyle.applyAlert(position: .default, on: tag) } } public static var leftAlert: NatTag.Style { .init { tag in NatTagStyle.applyAlert(position: .left, on: tag) } } public static var rightAlert: NatTag.Style { .init { tag in NatTagStyle.applyAlert(position: .right, on: tag) } } } } enum NatTagStyle { static func applyAlert(position: NatTag.Position, on tag: NatTag) { tag.configure(path: getUIColorFromTokens(\.colorPrimary), position: position) tag.configure(textColor: getUIColorFromTokens(\.colorOnPrimary)) } }
26.45
85
0.568998
c1fc4e1c47fc21fbae69ce6319456c658efb5c2c
1,468
// // LightWeightAlert.swift // breadwallet // // Created by Adrian Corscadden on 2017-06-20. // Copyright © 2017 breadwallet LLC. All rights reserved. // import UIKit class LightWeightAlert : UIView { init(message: String) { super.init(frame: .zero) self.label.text = message setup() } let effect = UIBlurEffect(style: .dark) let background = UIVisualEffectView() let container = UIView() private let label = UILabel(font: .customMedium(size: 16.0)) private func setup() { addSubview(background) background.constrain(toSuperviewEdges: nil) background.contentView.addSubview(container) container.addSubview(label) container.constrain(toSuperviewEdges: nil) label.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[2], left: C.padding[2], bottom: -C.padding[2], right: -C.padding[2])) container.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 1.0).isActive = true label.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.8).isActive = true label.textAlignment = .center label.numberOfLines = 0 layer.cornerRadius = 4.0 layer.masksToBounds = true label.textColor = C.Colors.text backgroundColor = C.Colors.blue } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
30.583333
139
0.660763
28f6d046a1c6a23738bc01847dd3d9e514e32e06
1,572
//import GenythingTest //import XCTest //@testable import Genything // //final class Generator_ScanTests: XCTestCase { // /// Test that scan works as Combine users should expect // /// - SeeAlso: https://developer.apple.com/documentation/combine/publisher/scan(_:_:) // func test_scan_matches_combine_example() { // let range = 0 ... 5 // // let result = Exhaustive.Loop(range) // .scan(0) { $0 + $1 } // .take(range.count, randomSource: .predetermined()) // // XCTAssertEqual([0, 1, 3, 6, 10, 15], result) // } // // func test_abusing_scan_to_create_iterator() { // let range = 0 ... 5 // // let result = Generators.constant(0) // .scan(0) { acc, _ in acc + 1 } // .take(range.count, randomSource: .predetermined()) // // XCTAssertEqual([1, 2, 3, 4, 5, 6], result) // } // // func test_abusing_scan_to_create_iterator_of_even_values() { // let range = 0 ... 5 // // let result = Generators.constant(0) // .scan(0) { acc, _ in acc + 2 } // .take(range.count, randomSource: .predetermined()) // // XCTAssertEqual([2, 4, 6, 8, 10, 12], result) // } // // func SKIP_test_modeling_a_moving_average() { // (0 ... 1) // .arbitrary // .debug("value") // .scan(0.0) { average, newValue in // average * 0.5 + Double(newValue) * 0.5 // } // .debug("average") // .sequence(100, randomSource: .predetermined()).forEach { _ in } // } //}
32.081633
91
0.53944
db0a848415aad5927a160544c9987eeb5e2493df
1,492
// RUN: rm -rf %t && mkdir -p %t // RUN: cp -R %S/Inputs/mixed-target %t // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %clang-importer-sdk-path/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %clang-importer-sdk-path/swift-modules/Foundation.swift // FIXME: END -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/../Inputs/custom-modules -import-objc-header %t/mixed-target/header.h -emit-module-path %t/MixedWithHeader.swiftmodule %S/Inputs/mixed-with-header.swift %S/../../Inputs/empty.swift -module-name MixedWithHeader -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/../Inputs/custom-modules -typecheck %s -verify // RUN: rm -rf %t/mixed-target/ // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/../Inputs/custom-modules -typecheck %s -verify // XFAIL: linux import MixedWithHeader func testReexportedClangModules(_ foo : FooProto) { _ = foo.bar as CInt _ = ExternIntX.x as CInt } func testCrossReferences(_ derived: Derived) { let obj: Base = derived _ = obj.safeOverride(ForwardClass()) as NSObject _ = obj.safeOverrideProto(ForwardProtoAdopter()) as NSObject testProtocolWrapper(ProtoConformer()) _ = testStruct(Point2D(x: 2,y: 3)) }
46.625
338
0.729893
e022d09d758a8fd31a2ea4fd8b340076bffb79b2
1,636
// // UIViewController+Ext.swift // DiscourseApp // // Created by Rodrigo Candido on 20/1/21. // import UIKit extension UIViewController { /** Show a basic AlertController(Ok Opition) - Parameters: - alertMessage: Alert Message - alertTitle: Alert Title - alertActionTitle: Action Title This extension helps to implement a Alert much faster ## Example Being at some ViewController or a Class that has a implementation of UIViewController, call this method ~~~ class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.showAlert("This is the Alert message", "This is Alert Title", "Alert Button Text") } } ~~~ - Attention: This class was first created by Roberto Garrido. At the time this project was created he teach me how to user this type of class to improve my habilities with networking. **Thank you very much Roberto Garrido** - Author: Roberto Garrido - Version: v1.0 */ func showAlert(_ alertMessage: String, _ alertTitle: String = NSLocalizedString("Error", comment: ""), _ alertActionTitle: String = NSLocalizedString("OK", comment: "")) { let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: alertActionTitle, style: .default, handler: nil)) present(alertController, animated: true, completion: nil) } }
33.387755
228
0.638142
e87b8cec184b97aae3fb8960a87532974c4c1011
1,712
// // ServiceProfile.swift // BlueCap // // Created by Troy Stribling on 6/21/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation import CoreBluetooth // MARK: - ServiceProfile - public class ServiceProfile { internal var characteristicProfiles = [CBUUID: CharacteristicProfile]() public let uuid: CBUUID public let name: String public let tag: String public var characteristics: [CharacteristicProfile] { return Array(self.characteristicProfiles.values) } public var characteristic: [CBUUID: CharacteristicProfile] { return self.characteristicProfiles } public init(uuid: String, name: String, tag: String = "Miscellaneous") { self.name = name self.uuid = CBUUID(string: uuid) self.tag = tag } public convenience init(uuid: String) { self.init(uuid: uuid, name:"Unknown") } public func addCharacteristic(_ characteristicProfile: CharacteristicProfile) { Logger.debug("name=\(characteristicProfile.name), uuid=\(characteristicProfile.uuid.uuidString)") self.characteristicProfiles[characteristicProfile.uuid] = characteristicProfile } public func characteristicProfile(withUUID uuid: CBUUID) -> CharacteristicProfile { guard let characteristicProfile = self.characteristicProfiles[uuid] else { return CharacteristicProfile(uuid: uuid.uuidString) } return characteristicProfile } } public class ConfiguredServiceProfile<Config: ServiceConfigurable>: ServiceProfile { public init() { super.init(uuid: Config.uuid, name: Config.name, tag: Config.tag) } }
28.533333
105
0.6875
23c0974aad0fe6452e43e52b08e0e5d27d48bc0f
1,782
// // ViewController.swift // Calculator-AutoLayout // // Created by Eric Golovin on 07.06.2020. // Copyright © 2020 com.ericgolovin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var deleteKeypadButton: KeypadButton! @IBOutlet var keypadButtons: [KeypadButton]! @IBOutlet var keypadOperationButtons: [KeypadButton]! @IBOutlet weak var historyTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() longPressed(UILongPressGestureRecognizer()) } var operation: Performer! @IBAction func deleteKeypadTapped(_ sender: KeypadButton) { resultLabel.text = "0" operation = Performer() } @IBAction func keypadTapped(_ sender: KeypadButton) { if resultLabel.text!.contains("Result") || resultLabel.text! == "0" { resultLabel.text = "" operation = Performer() } keypadOperationButtons.forEach { $0.isEnabled = !operation.isOperator(sender.titleLabel!.text!) } resultLabel.text! += sender.titleLabel!.text! operation.passSymbol(sender.titleLabel!.text!) switch sender.titleLabel?.text { case "=": historyTextView.text += "\n" + resultLabel.text! + operation.result resultLabel.text = "Result: " + operation.result operation.clear() default: break } } @IBAction func longPressed(_ sender: UILongPressGestureRecognizer) { historyTextView.text = "Calculation History\n" for _ in historyTextView.text { historyTextView.text += "-" } } }
27.84375
105
0.6156
037de84aa339ead0b54ac8055c3b697871a7c69f
2,790
// // FretBoardTests.swift // Fret Notes Tests // // Created by luca strazzullo on 15/7/20. // Copyright © 2020 Luca Strazzullo. All rights reserved. // import XCTest @testable import Fret_Notes class FretBoardTests: XCTestCase { private let fretboard = Fretboard(.standard) func testNoteAtFretZero() { XCTAssertEqual(fretboard.note(on: 0, string: 1), .e) XCTAssertEqual(fretboard.note(on: 0, string: 2), .b) XCTAssertEqual(fretboard.note(on: 0, string: 3), .g) XCTAssertEqual(fretboard.note(on: 0, string: 4), .d) XCTAssertEqual(fretboard.note(on: 0, string: 5), .a) XCTAssertEqual(fretboard.note(on: 0, string: 6), .e) } func testNoteAtFirstFret() { XCTAssertEqual(fretboard.note(on: 1, string: 1), .f) XCTAssertEqual(fretboard.note(on: 1, string: 2), .c) XCTAssertEqual(fretboard.note(on: 1, string: 3), .gSharp) XCTAssertEqual(fretboard.note(on: 1, string: 4), .dSharp) XCTAssertEqual(fretboard.note(on: 1, string: 5), .aSharp) XCTAssertEqual(fretboard.note(on: 1, string: 6), .f) } func testNoteAtFiftFret() { XCTAssertEqual(fretboard.note(on: 5, string: 1), .a) XCTAssertEqual(fretboard.note(on: 5, string: 2), .e) XCTAssertEqual(fretboard.note(on: 5, string: 3), .c) XCTAssertEqual(fretboard.note(on: 5, string: 4), .g) XCTAssertEqual(fretboard.note(on: 5, string: 5), .d) XCTAssertEqual(fretboard.note(on: 5, string: 6), .a) } func testNoteAtSeventhFret() { XCTAssertEqual(fretboard.note(on: 7, string: 1), .b) XCTAssertEqual(fretboard.note(on: 7, string: 2), .fSharp) XCTAssertEqual(fretboard.note(on: 7, string: 3), .d) XCTAssertEqual(fretboard.note(on: 7, string: 4), .a) XCTAssertEqual(fretboard.note(on: 7, string: 5), .e) XCTAssertEqual(fretboard.note(on: 7, string: 6), .b) } func testNoteAtTwelvethFret() { XCTAssertEqual(fretboard.note(on: 12, string: 1), .e) XCTAssertEqual(fretboard.note(on: 12, string: 2), .b) XCTAssertEqual(fretboard.note(on: 12, string: 3), .g) XCTAssertEqual(fretboard.note(on: 12, string: 4), .d) XCTAssertEqual(fretboard.note(on: 12, string: 5), .a) XCTAssertEqual(fretboard.note(on: 12, string: 6), .e) } func testNoteAtTwentyFirstFret() { XCTAssertEqual(fretboard.note(on: 21, string: 1), .cSharp) XCTAssertEqual(fretboard.note(on: 21, string: 2), .gSharp) XCTAssertEqual(fretboard.note(on: 21, string: 3), .e) XCTAssertEqual(fretboard.note(on: 21, string: 4), .b) XCTAssertEqual(fretboard.note(on: 21, string: 5), .fSharp) XCTAssertEqual(fretboard.note(on: 21, string: 6), .cSharp) } }
37.2
66
0.636201
48c61e62398680d9540ec2f0518283609d242edb
3,416
// // TodayViewModel.swift // Peanut // // Created by Adam on 9/3/21. // import Foundation import CoreData extension TodayView { class ViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate { private let projectsController: NSFetchedResultsController<Project> private let itemsController: NSFetchedResultsController<Item> var persistenceController: PersistenceController @Published var projects: [Project] = [] @Published var items: [Item] = [] @Published var selectedItem: Item? @Published var selectedProject: Project? @Published var upNext = ArraySlice<Item>() @Published var moreToExplore = ArraySlice<Item>() init(persistenceController: PersistenceController) { self.persistenceController = persistenceController /// Construct a fetch request to show all open projects let projectRequest: NSFetchRequest<Project> = Project.fetchRequest() projectRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.title, ascending: true)] projectRequest.predicate = NSPredicate(format: "closed = false") projectsController = NSFetchedResultsController( fetchRequest: projectRequest, managedObjectContext: persistenceController.container.viewContext, sectionNameKeyPath: nil, cacheName: nil ) /// Construct a fetch request to show the 10 highest-priority, incomplete items from open projects let itemRequest = persistenceController.fetchRequestForTopItems(count: 10) itemsController = NSFetchedResultsController( fetchRequest: itemRequest, managedObjectContext: persistenceController.container.viewContext, sectionNameKeyPath: nil, cacheName: nil ) /// Initialize parent object before assigning ourself as controller delegate super.init() projectsController.delegate = self itemsController.delegate = self /// Fetch initial data do { try projectsController.performFetch() try itemsController.performFetch() projects = projectsController.fetchedObjects ?? [] items = itemsController.fetchedObjects ?? [] upNext = items.prefix(3) moreToExplore = items.dropFirst(3) } catch { print("Failed to fetch initial data.") } } func addSampleData() { persistenceController.deleteAll() try? persistenceController.createSampleData() } func selectItem(with identifier: String) { selectedItem = persistenceController.item(with: identifier) } func selectedProject(with identifier: String) { selectedProject = persistenceController.project(with: identifier) } // MARK: - NSFetchedResultsControllerDelegate func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { items = itemsController.fetchedObjects ?? [] upNext = items.prefix(3) moreToExplore = items.dropFirst(3) projects = projectsController.fetchedObjects ?? [] } } }
37.130435
110
0.635246
ac354c43ce7620d2d39c30597b1ee53651c05d43
1,011
// // UINavigationViewController.swift // Pods // // Created by Rasmus Kildevæld on 18/10/2015. // // import Foundation public extension UINavigationController { public func pushViewController(viewController: UIViewController, withData: AnyObject, animated: Bool) { self.visibleViewController?.setDidPush(true) viewController.setDidPush(false) let vc = viewController as? DataRepresentation if viewController.viewIsLoaded { if let v = viewController as? DataReuseRepresentation { v.prepare() } vc?.arrangeWithData(withData) } else { viewController.onViewDidLoadBlock = onTimeout(0.5, handler: { vc?.arrangeWithData(withData) viewController.onViewDidLoadBlock = nil }) } self.pushViewController(viewController, animated: animated) } }
22.977273
107
0.581602
5d300dde98ed1ca960d77bf5a615cb5b57032b1f
4,212
// // CalendarCollectionViewLayout.swift // Sundial // // Created by Sergei Mikhan on 3/18/20. // import UIKit open class CalendarCollectionViewLayout: EmptyViewCollectionViewLayout { public struct Settings { public enum Alignment { case fill case center } public let alignment: Alignment public let insets: UIEdgeInsets public let horizontalMargin: CGFloat public let verticalMargin: CGFloat public init(alignment: Alignment, insets: UIEdgeInsets = .zero, horizontalMargin: CGFloat = 0.0, verticalMargin: CGFloat = 0.0) { self.alignment = alignment self.insets = insets self.horizontalMargin = horizontalMargin self.verticalMargin = verticalMargin } } open var settings = Settings(alignment: .fill) { didSet { invalidateLayout() } } public struct MonthLayout { let startDayIndex: Int public init(startDayIndex: Int) { self.startDayIndex = startDayIndex } } public var monthLayoutClosure: ((Int) -> MonthLayout)? = nil typealias Attributes = UICollectionViewLayoutAttributes private var itemsAttributes: [IndexPath: Attributes] = [:] private var contentSize = CGSize.zero public override init() { super.init() scrollDirection = .horizontal minimumLineSpacing = 0.0 minimumInteritemSpacing = 0.0 sectionInset = .zero } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func prepare() { super.prepare() guard let collectionView = collectionView, !collectionView.bounds.isEmpty, itemsAttributes.isEmpty else { return } reload() } override open var collectionViewContentSize: CGSize { return contentSize } override open func invalidateLayout(with context: UICollectionViewLayoutInvalidationContext) { super.invalidateLayout(with: context) itemsAttributes.removeAll() contentSize = .zero } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return itemsAttributes .filter { $0.value.frame.intersects(rect) } .map { $0.value } } override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return itemsAttributes[indexPath] } } private extension CalendarCollectionViewLayout { private func reload() { guard let collectionView = collectionView else { return } let daysAWeek = 7 let width = collectionView.frame.width let height = collectionView.frame.height let sections = collectionView.numberOfSections (0..<sections).forEach { section in let totalDays = collectionView.numberOfItems(inSection: section) let month = monthLayoutClosure?(section) ?? MonthLayout(startDayIndex: 0) let numberOfRows = Int(ceil(Double(month.startDayIndex + totalDays) / Double(daysAWeek))) let dayCellWidth = (width - settings.insets.left - settings.insets.right - CGFloat(daysAWeek - 1) * settings.horizontalMargin) / CGFloat(daysAWeek) let dayCellHeight = (height - settings.insets.top - settings.insets.bottom - CGFloat(numberOfRows - 1) * settings.verticalMargin) / CGFloat(numberOfRows) let dayWidthWithMargin = dayCellWidth + settings.horizontalMargin let dayHeightWithMargin = dayCellHeight + settings.verticalMargin let originX = CGFloat(section) * width + settings.insets.left var x = originX + CGFloat(month.startDayIndex) * dayWidthWithMargin var y = settings.insets.top (0..<totalDays).forEach { day in let indexPath = IndexPath(item: day, section: section) let cellAttribute = Attributes(forCellWith: indexPath) cellAttribute.frame = CGRect(x: x, y: y, width: dayCellWidth, height: dayCellHeight) itemsAttributes[indexPath] = cellAttribute x += dayWidthWithMargin if (day + 1 + month.startDayIndex) % daysAWeek == 0 { x = originX y += dayHeightWithMargin } } } contentSize = CGSize(width: CGFloat(sections) * width, height: height) } }
29.454545
118
0.689696
bf0aed87d3bffb11d12b870c2c44ba8e5a7a7ede
519
// // AppDelegate.swift // THTiledImageView // // Created by 홍창남 on 2017. 12. 28.. // Copyright © 2017년 홍창남. 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 } }
23.590909
114
0.693642
226ee2479fcc1f022555a3ddc1186c8437badc82
2,697
// // SceneDelegate.swift // PharmacyFinder // // Created by Felipe Vergara on 22-04-20. // Copyright © 2020 Felipe Vergara. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let windowScene = (scene as? UIWindowScene) else { return } window = UIWindow(frame: windowScene.coordinateSpace.bounds) window?.windowScene = windowScene let navigationVC = UINavigationController() window?.rootViewController = navigationVC navigationVC.pushViewController(LoginViewController(), animated: false) window?.makeKeyAndVisible() } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
44.95
147
0.716352
e642d2065c54ac7cf4306fa79f91d323fd06bfcb
1,571
import Combine import ComposableArchitecture import SwiftUI import XCTest @testable import SwiftUICaseStudies class AlertsAndActionSheetsTests: XCTestCase { func testAlert() { let store = TestStore( initialState: AlertAndSheetState(), reducer: alertAndSheetReducer, environment: AlertAndSheetEnvironment() ) store.send(.alertButtonTapped) { $0.alert = .init( title: .init("Alert!"), message: .init("This is an alert"), primaryButton: .cancel(), secondaryButton: .default(.init("Increment"), action: .send(.incrementButtonTapped)) ) } store.send(.incrementButtonTapped) { $0.alert = .init(title: .init("Incremented!")) $0.count = 1 } store.send(.alertDismissed) { $0.alert = nil } } func testActionSheet() { let store = TestStore( initialState: AlertAndSheetState(), reducer: alertAndSheetReducer, environment: AlertAndSheetEnvironment() ) store.send(.actionSheetButtonTapped) { $0.actionSheet = .init( title: .init("Action sheet"), message: .init("This is an action sheet."), buttons: [ .cancel(), .default(.init("Increment"), action: .send(.incrementButtonTapped)), .default(.init("Decrement"), action: .send(.decrementButtonTapped)), ] ) } store.send(.incrementButtonTapped) { $0.alert = .init(title: .init("Incremented!")) $0.count = 1 } store.send(.actionSheetDismissed) { $0.actionSheet = nil } } }
26.183333
92
0.618078
e621cfc5efb6cab5fcfa0043b48bfb7e13009c80
4,242
// // SarCircuitView.swift // analog // // Created by Philip Kronawetter on 2020-05-08. // Copyright © 2020 Philip Kronawetter. All rights reserved. // import UIKit class SarCircuitView: UIView { class DacInputLineView: UIView { let line: UIView let label: UILabel var isActive: Bool = false { didSet { label.text = isActive ? "1" : "0" let color = isActive ? UIColor.systemRed : UIColor.label line.backgroundColor = color label.textColor = color } } override init(frame: CGRect) { line = UIView(frame: CGRect(x: 20.0, y: 0.0, width: 2.0, height: 30.0)) line.backgroundColor = .label label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 15.0, height: 30.0)) label.text = "0" label.textAlignment = .right label.textColor = .label label.font = .systemFont(ofSize: 13.0) super.init(frame: CGRect(x: frame.minX, y: frame.minY, width: 22.0, height: 30.0)) addSubview(line) addSubview(label) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private let baseImage = UIImage(named: "SARCircuitBase")! private let baseView: UIImageView private let logicLabel: UILabel private let dacLabel: UILabel private let inputVoltageLabel: UILabel private let referenceVoltageLabel: UILabel private var dacInputLineViews: [DacInputLineView] var dacResolution: Int { willSet { dacInputLineViews.forEach { $0.removeFromSuperview() } dacInputLineViews = [] } didSet { baseView.frame.size.width = 70.0 + 144.0 + CGFloat(dacResolution) * 22.0 logicLabel.frame.size.width = 20.0 + CGFloat(dacResolution) * 22.0 - 4.0 dacLabel.frame.size.width = 20.0 + CGFloat(dacResolution) * 22.0 - 4.0 inputVoltageLabel.frame.size.width = 20.0 + CGFloat(dacResolution) * 22.0 + 30.0 dacInputLineViews = (0..<dacResolution).reversed().map { DacInputLineView(frame: CGRect(x: 70.0 + CGFloat($0) * 22.0, y: 44.0, width: 2.0, height: 30.0)) } dacInputLineViews.forEach { addSubview($0) } invalidateIntrinsicContentSize() } } init(dacResolution: Int) { precondition(dacResolution > 0) baseView = UIImageView(image: baseImage.withTintColor(.label)) baseView.frame.size.width = 70.0 + 144.0 + CGFloat(dacResolution) * 22.0 logicLabel = UILabel(frame: CGRect(x: 70.0 + 2.0, y: 2.0, width: 20.0 + CGFloat(dacResolution) * 22.0 - 4.0, height: 40.0)) logicLabel.text = "Logic" logicLabel.textAlignment = .center logicLabel.font = .systemFont(ofSize: 13.0) logicLabel.textColor = .label dacLabel = UILabel(frame: CGRect(x: 70.0 + 2.0, y: 76.0, width: 20.0 + CGFloat(dacResolution) * 22.0 - 4.0, height: 40.0)) dacLabel.text = "D/A Converter" dacLabel.textAlignment = .center dacLabel.font = .systemFont(ofSize: 13.0) dacLabel.textColor = .label inputVoltageLabel = UILabel(frame: CGRect(x: 70.0 + 0.0, y: 145.0, width: 20.0 + CGFloat(dacResolution) * 22.0 + 30.0, height: 20.0)) inputVoltageLabel.text = "Input Voltage" inputVoltageLabel.font = .systemFont(ofSize: 13.0) inputVoltageLabel.textColor = .label referenceVoltageLabel = UILabel(frame: CGRect(x: 0.0, y: 101.0, width: 65.0, height: 37.0)) referenceVoltageLabel.text = "Maximum Voltage" referenceVoltageLabel.font = .systemFont(ofSize: 13.0) referenceVoltageLabel.numberOfLines = 0 referenceVoltageLabel.textColor = .label dacInputLineViews = (0..<dacResolution).reversed().map { DacInputLineView(frame: CGRect(x: 70.0 + CGFloat($0) * 22.0, y: 44.0, width: 2.0, height: 30.0)) } self.dacResolution = dacResolution super.init(frame: CGRect(origin: .zero, size: baseView.frame.size)) addSubview(baseView) addSubview(logicLabel) addSubview(dacLabel) addSubview(inputVoltageLabel) addSubview(referenceVoltageLabel) dacInputLineViews.forEach { addSubview($0) } } override var intrinsicContentSize: CGSize { CGSize(width: 70.0 + 144.0 + CGFloat(dacResolution) * 22.0, height: baseImage.size.height) } override func sizeThatFits(_ size: CGSize) -> CGSize { intrinsicContentSize } func setValueOfDacInputLine(at index: Int, value: Bool) { dacInputLineViews[index].isActive = value } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
32.136364
158
0.702735
ed0ed3beda93f9d2fc138e559515912b62627841
767
// // RecordScreen.swift // SmartWalletUITests // // Created by Renato Santana on 25/05/21. // Copyright © 2021 Soheil Novinfard. All rights reserved. // import Foundation import XCTest enum RecordScreen: String { case btnAdd = "Add" case btnSubmit = "Submit" case tabRecord = "Records" case txtTypeTransaction = "Foods & Drinks" var element: XCUIElement { switch self { case .btnAdd, .btnSubmit: return XCUIApplication().buttons[self.rawValue] case .tabRecord: return XCUIApplication().navigationBars[self.rawValue] case .txtTypeTransaction: return XCUIApplication().textFields[self.rawValue] } } }
26.448276
70
0.599739
3a497265c1c5cf0db06a8c74a89a2c1ac533d7a3
1,574
// // ScheduledItem.swift // RxSwift // // Created by 野村 憲男 on 4/20/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation public protocol IScheduledItem: class { typealias AbsoluteTime var dueTime: AbsoluteTime {get} func invoke() } public class ScheduledItemBase<TAbsolute: Comparable>: IScheduledItem { // MARK: IScheduledItem typealias AbsoluteTime = TAbsolute public let dueTime: AbsoluteTime public func invoke() { if !_disposable.isDisposed { _disposable.disposable = invokeCore() } } // MARK: public public func cancel() { _disposable.dispose() } public var isCanceled: Bool { return _disposable.isDisposed } // MARK: internal init(dueTime: AbsoluteTime) { self.dueTime = dueTime } func invokeCore() -> IDisposable? { fatalError("Abstract method \(__FUNCTION__)") } // MARK: private let _disposable = SingleAssignmentDisposable() } public final class ScheduledItem<TAbsolute: Comparable>: ScheduledItemBase<TAbsolute> { public init(scheduler: IScheduler, action: IScheduler -> IDisposable?, dueTime: TAbsolute) { self.scheduler = scheduler self.action = action super.init(dueTime: dueTime) } // MARK: internal override func invokeCore() -> IDisposable? { return action(scheduler) } // MARK: private private let scheduler: IScheduler private let action: IScheduler -> IDisposable? }
23.492537
96
0.640407
ebb2274c00aafce4498981d6a68bc2e4ebc18559
3,310
// // QuickZip.swift // Zip // // Created by Roy Marmelstein on 16/01/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation extension Zip { //MARK: Quick Unzip /** Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name. - parameter path: Path of zipped file. NSURL. - throws: Error if unzipping fails or if file is not found. Can be printed with a description variable. - returns: NSURL of the destination folder. */ public class func quickUnzipFile(path: NSURL) throws -> NSURL { return try quickUnzipFile(path, progress: nil) } /** Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name. - parameter path: Path of zipped file. NSURL. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if unzipping fails or if file is not found. Can be printed with a description variable. - returns: NSURL of the destination folder. */ public class func quickUnzipFile(path: NSURL, progress: ((progress: Double) -> ())?) throws -> NSURL { let fileManager = NSFileManager.defaultManager() guard let fileExtension = path.pathExtension, let fileName = path.lastPathComponent else { throw ZipError.UnzipFail } let directoryName = fileName.stringByReplacingOccurrencesOfString(".\(fileExtension)", withString: "") let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let destinationUrl = documentsUrl.URLByAppendingPathComponent(directoryName, isDirectory: true) try self.unzipFile(path, destination: destinationUrl, overwrite: true, password: nil, progress: progress) return destinationUrl } //MARK: Quick Zip /** Quick zip files. - parameter paths: Array of NSURL filepaths. - parameter fileName: File name for the resulting zip file. - throws: Error if zipping fails. - returns: NSURL of the destination folder. */ public class func quickZipFiles(paths: [NSURL], fileName: String) throws -> NSURL { return try quickZipFiles(paths, fileName: fileName, progress: nil) } /** Quick zip files. - parameter paths: Array of NSURL filepaths. - parameter fileName: File name for the resulting zip file. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - returns: NSURL of the destination folder. */ public class func quickZipFiles(paths: [NSURL], fileName: String, progress: ((progress: Double) -> ())?) throws -> NSURL { let fileManager = NSFileManager.defaultManager() let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let destinationUrl = documentsUrl.URLByAppendingPathComponent("\(fileName).zip") try self.zipFiles(paths, zipFilePath: destinationUrl, password: nil, progress: progress) return destinationUrl } }
38.488372
126
0.680967
ddd3ee1facbc5909ac6e22fe0d062a6c927619cf
1,421
// // LogServiceOS.swift // ZamzamCore // // Created by Basem Emara on 2019-11-01. // Copyright © 2019 Zamzam Inc. All rights reserved. // import os /// Sends a message to the logging system, optionally specifying a custom log object, log level, and any message format arguments. public struct LogServiceOS: LogService { public let minLevel: LogAPI.Level private let subsystem: String private let category: String private let log: OSLog public init(minLevel: LogAPI.Level, subsystem: String, category: String) { self.minLevel = minLevel self.subsystem = subsystem self.category = category self.log = OSLog(subsystem: subsystem, category: category) } } public extension LogServiceOS { func write( _ level: LogAPI.Level, with message: String, file: String, function: String, line: Int, error: Error?, context: [String: CustomStringConvertible] ) { let type: OSLogType switch level { case .verbose: type = .debug case .debug: type = .debug case .info: type = .info case .warning: type = .default case .error: type = .error case .none: return } os_log("%@", log: log, type: type, format(message, file, function, line, error, context)) } }
25.375
130
0.593948
ef1373a5dc53ff1ce35cc310c6b0c0441b218dd3
677
// // ViewController.swift // yanzhengma // // Created by zetafin on 2018/6/20. // Copyright © 2018年 赵宏亚. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let codeView = CodeView.init(frame: .init(x: 0, y: 60, width: 87, height: 42)) self.view.addSubview(codeView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
19.911765
86
0.604136
6413932729c4b0ee846e64dbfc0006370ee5a878
248
// // MovieViewCell.swift // MovieViewer // // Created by Lin Zhou on 2/5/17. // Copyright © 2017 Lin Zhou. All rights reserved. // import UIKit class MovieViewCell: UICollectionViewCell { @IBOutlet weak var posterView: UIImageView! }
15.5
51
0.697581
e65b5db54a555007604c9eb2a4f07dfc2ed9256e
1,580
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // import Foundation @_silgen_name("playground_log_scope_entry") public func playground_log_scope_entry(_ startline: Int, _ endline: Int, _ startcolumn: Int, _ endcolumn: Int) -> NSData { let range = (begin: (line: UInt64(startline), col: UInt64(startcolumn)), end: (line: UInt64(endline), col: UInt64(endcolumn))) let encoder = PlaygroundScopeWriter() encoder.encode(scope: .ScopeEntry, range: range) return encoder.stream.data } @_silgen_name("playground_log_scope_exit") public func playground_log_scope_exit(_ startline: Int, _ endline: Int, _ startcolumn: Int, _ endcolumn: Int) -> NSData { let range = (begin: (line: UInt64(startline), col: UInt64(startcolumn)), end: (line: UInt64(endline), col: UInt64(endcolumn))) let encoder = PlaygroundScopeWriter() encoder.encode(scope: .ScopeExit, range: range) return encoder.stream.data }
41.578947
130
0.572785
b994315abff83834fdf62cbf455a5a68ef60bb6e
8,155
// // SwifterOAuthClient.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Accounts internal class SwifterOAuthClient: SwifterClientProtocol { struct OAuth { static let version = "1.0" static let signatureMethod = "HMAC-SHA1" } var consumerKey: String var consumerSecret: String var credential: SwifterCredential? var dataEncoding: NSStringEncoding init(consumerKey: String, consumerSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret self.dataEncoding = NSUTF8StringEncoding } init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) { self.consumerKey = consumerKey self.consumerSecret = consumerSecret let credentialAccessToken = SwifterCredential.OAuthAccessToken(key: accessToken, secret: accessTokenSecret) self.credential = SwifterCredential(accessToken: credentialAccessToken) self.dataEncoding = NSUTF8StringEncoding } func get(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { let url = NSURL(string: path, relativeToURL: baseURL)! let method = "GET" let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters) request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: false)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.start() return request } func post(path: String, baseURL: NSURL, var parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { let url = NSURL(string: path, relativeToURL: baseURL)! let method = "POST" var postData: NSData? var postDataKey: String? if let key: Any = parameters[Swifter.DataParameters.dataKey] { if let keyString = key as? String { postDataKey = keyString postData = parameters[postDataKey!] as? NSData parameters.removeValueForKey(Swifter.DataParameters.dataKey) parameters.removeValueForKey(postDataKey!) } } var postDataFileName: String? if let fileName: Any = parameters[Swifter.DataParameters.fileNameKey] { if let fileNameString = fileName as? String { postDataFileName = fileNameString parameters.removeValueForKey(fileNameString) } } let request = SwifterHTTPRequest(URL: url, method: method, parameters: parameters) request.headers = ["Authorization": self.authorizationHeaderForMethod(method, url: url, parameters: parameters, isMediaUpload: postData != nil)] request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.dataEncoding = self.dataEncoding request.encodeParameters = postData == nil if postData != nil { let fileName = postDataFileName ?? "media.jpg" request.addMultipartData(postData!, parameterName: postDataKey!, mimeType: "application/octet-stream", fileName: fileName) } request.start() return request } func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, isMediaUpload: Bool) -> String { var authorizationParameters = Dictionary<String, Any>() authorizationParameters["oauth_version"] = OAuth.version authorizationParameters["oauth_signature_method"] = OAuth.signatureMethod authorizationParameters["oauth_consumer_key"] = self.consumerKey authorizationParameters["oauth_timestamp"] = String(Int(NSDate().timeIntervalSince1970)) authorizationParameters["oauth_nonce"] = NSUUID().UUIDString if self.credential?.accessToken != nil { authorizationParameters["oauth_token"] = self.credential!.accessToken!.key } for (key, value): (String, Any) in parameters { if key.hasPrefix("oauth_") { authorizationParameters.updateValue(value, forKey: key) } } let combinedParameters = authorizationParameters +| parameters let finalParameters = isMediaUpload ? authorizationParameters : combinedParameters authorizationParameters["oauth_signature"] = self.oauthSignatureForMethod(method, url: url, parameters: finalParameters, accessToken: self.credential?.accessToken) var authorizationParameterComponents = authorizationParameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] authorizationParameterComponents.sortInPlace { $0 < $1 } var headerComponents = [String]() for component in authorizationParameterComponents { let subcomponent = component.componentsSeparatedByString("=") as [String] if subcomponent.count == 2 { headerComponents.append("\(subcomponent[0])=\"\(subcomponent[1])\"") } } return "OAuth " + headerComponents.joinWithSeparator(", ") } func oauthSignatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, Any>, accessToken token: SwifterCredential.OAuthAccessToken?) -> String { var tokenSecret: NSString = "" if token != nil { tokenSecret = token!.secret.urlEncodedStringWithEncoding(self.dataEncoding) } let encodedConsumerSecret = self.consumerSecret.urlEncodedStringWithEncoding(self.dataEncoding) let signingKey = "\(encodedConsumerSecret)&\(tokenSecret)" var parameterComponents = parameters.urlEncodedQueryStringWithEncoding(self.dataEncoding).componentsSeparatedByString("&") as [String] parameterComponents.sortInPlace { $0 < $1 } let parameterString = parameterComponents.joinWithSeparator("&") let encodedParameterString = parameterString.urlEncodedStringWithEncoding(self.dataEncoding) let encodedURL = url.absoluteString.urlEncodedStringWithEncoding(self.dataEncoding) let signatureBaseString = "\(method)&\(encodedURL)&\(encodedParameterString)" // let signature = signatureBaseString.SHA1DigestWithKey(signingKey) return signatureBaseString.SHA1DigestWithKey(signingKey).base64EncodedStringWithOptions([]) } }
45.305556
320
0.710607
87ea4b2029a4cd593b7da1dd845293c0f2a7cb3f
10,969
/* THIS FILE WAS AUTOGENERATED! DO NOT EDIT! file to edit: 04_callbacks.ipynb */ import Path import TensorFlow public struct BasicModel: Layer { public var layer1, layer2: FADense<Float> public init(nIn: Int, nHid: Int, nOut: Int){ layer1 = FADense(nIn, nHid, activation: relu) layer2 = FADense(nHid, nOut) } @differentiable public func call(_ input: Tensor<Float>) -> Tensor<Float> { return layer2(layer1(input)) } } public struct FADataset<Element> where Element: TensorGroup { public var innerDs: Dataset<Element> public var shuffle = false public var bs = 64 public var dsCount: Int public var count: Int { return dsCount%bs == 0 ? dsCount/bs : dsCount/bs+1 } public var ds: Dataset<Element> { if !shuffle { return innerDs.batched(bs)} let seed = Int64.random(in: Int64.min..<Int64.max) return innerDs.shuffled(sampleCount: dsCount, randomSeed: seed).batched(bs) } public init(_ ds: Dataset<Element>, len: Int, shuffle: Bool = false, bs: Int = 64) { (self.innerDs,self.dsCount,self.shuffle,self.bs) = (ds, len, shuffle, bs) } } public struct DataBunch<Element> where Element: TensorGroup{ public var train, valid: FADataset<Element> public init(train: Dataset<Element>, valid: Dataset<Element>, trainLen: Int, validLen: Int, bs: Int = 64) { self.train = FADataset(train, len: trainLen, shuffle: true, bs: bs) self.valid = FADataset(valid, len: validLen, shuffle: false, bs: 2*bs) } } public func mnistDataBunch(path: Path = mnistPath, flat: Bool = false, bs: Int = 64) -> DataBunch<DataBatch<TF, TI>> { let (xTrain,yTrain,xValid,yValid) = loadMNIST(path: path, flat: flat) return DataBunch(train: Dataset(elements: DataBatch(xb:xTrain, yb: yTrain)), valid: Dataset(elements: DataBatch(xb:xValid, yb: yValid)), trainLen: xTrain.shape[0], validLen: xValid.shape[0], bs: bs) } public enum LearnerAction: Error { case skipEpoch(reason: String) case skipBatch(reason: String) case stop(reason: String) } /// Initializes and trains a model on a given dataset. public final class Learner<Label: TensorGroup, Opt: TensorFlow.Optimizer & AnyObject> where Opt.Scalar: Differentiable, Opt.Model: Layer, // Constrain model input to Tensor<Float>, to work around // https://forums.fast.ai/t/fix-ad-crash-in-learner/42970. Opt.Model.Input == Tensor<Float> { public typealias Model = Opt.Model public typealias Input = Model.Input public typealias Output = Model.Output public typealias Data = DataBunch<DataBatch<Input, Label>> public typealias Loss = TF public typealias Optimizer = Opt public typealias Variables = Model.AllDifferentiableVariables public typealias EventHandler = (Learner) throws -> Void /// A wrapper class to hold the loss function, to work around // https://forums.fast.ai/t/fix-ad-crash-in-learner/42970. public final class LossFunction { public typealias F = @differentiable (Model.Output, @nondiff Label) -> Loss public var f: F init(_ f: @escaping F) { self.f = f } } public var data: Data public var opt: Optimizer public var lossFunc: LossFunction public var model: Model public var currentInput: Input! public var currentTarget: Label! public var currentOutput: Output! public private(set) var epochCount = 0 public private(set) var currentEpoch = 0 public private(set) var currentGradient = Model.CotangentVector.zero public private(set) var currentLoss = Loss.zero public private(set) var inTrain = false public private(set) var pctEpochs = Float.zero public private(set) var currentIter = 0 public private(set) var iterCount = 0 open class Delegate { open var order: Int { return 0 } public init () {} open func trainingWillStart(learner: Learner) throws {} open func trainingDidFinish(learner: Learner) throws {} open func epochWillStart(learner: Learner) throws {} open func epochDidFinish(learner: Learner) throws {} open func validationWillStart(learner: Learner) throws {} open func batchWillStart(learner: Learner) throws {} open func batchDidFinish(learner: Learner) throws {} open func didProduceNewGradient(learner: Learner) throws {} open func optimizerDidUpdate(learner: Learner) throws {} open func batchSkipped(learner: Learner, reason:String) throws {} open func epochSkipped(learner: Learner, reason:String) throws {} open func trainingStopped(learner: Learner, reason:String) throws {} /// /// TODO: learnerDidProduceNewOutput and learnerDidProduceNewLoss need to /// be differentiable once we can have the loss function inside the Learner } public var delegates: [Delegate] = [] { didSet { delegates.sort { $0.order < $1.order } } } public init(data: Data, lossFunc: @escaping LossFunction.F, optFunc: (Model) -> Optimizer, modelInit: ()->Model) { (self.data,self.lossFunc) = (data,LossFunction(lossFunc)) model = modelInit() opt = optFunc(self.model) } } extension Learner { private func evaluate(onBatch batch: DataBatch<Input, Label>) throws { currentOutput = model(currentInput) currentLoss = lossFunc.f(currentOutput, currentTarget) } private func train(onBatch batch: DataBatch<Input, Label>) throws { let (xb,yb) = (currentInput!,currentTarget!) //We still have to force-unwrap those for AD... (currentLoss, currentGradient) = model.valueWithGradient { model -> Loss in let y = model(xb) currentOutput = y return lossFunc.f(y, yb) } for d in delegates { try d.didProduceNewGradient(learner: self) } opt.update(&model.variables, along: self.currentGradient) } private func train(onDataset ds: FADataset<DataBatch<Input, Label>>) throws { iterCount = ds.count for batch in ds.ds { (currentInput, currentTarget) = (batch.xb, batch.yb) do { for d in delegates { try d.batchWillStart(learner: self) } if inTrain { try train(onBatch: batch) } else { try evaluate(onBatch: batch) } } catch LearnerAction.skipBatch(let reason) { for d in delegates {try d.batchSkipped(learner: self, reason:reason)} } for d in delegates { try d.batchDidFinish(learner: self) } } } } extension Learner { /// Starts fitting. /// - Parameter epochCount: The number of epochs that will be run. public func fit(_ epochCount: Int) throws { self.epochCount = epochCount do { for d in delegates { try d.trainingWillStart(learner: self) } for i in 0..<epochCount { self.currentEpoch = i do { for d in delegates { try d.epochWillStart(learner: self) } try train(onDataset: data.train) for d in delegates { try d.validationWillStart(learner: self) } try train(onDataset: data.valid) } catch LearnerAction.skipEpoch(let reason) { for d in delegates {try d.epochSkipped(learner: self, reason:reason)} } for d in delegates { try d.epochDidFinish(learner: self) } } } catch LearnerAction.stop(let reason) { for d in delegates {try d.trainingStopped(learner: self, reason:reason)} } for d in delegates { try d.trainingDidFinish(learner: self) } } } public extension Learner { func addDelegate (_ delegate : Learner.Delegate ) { delegates.append(delegate) } func addDelegates(_ delegates: [Learner.Delegate]) { self.delegates += delegates } } extension Learner { public class TrainEvalDelegate: Delegate { public override func trainingWillStart(learner: Learner) { learner.pctEpochs = 0.0 } public override func epochWillStart(learner: Learner) { Context.local.learningPhase = .training (learner.pctEpochs,learner.inTrain,learner.currentIter) = (Float(learner.currentEpoch),true,0) } public override func batchDidFinish(learner: Learner) { learner.currentIter += 1 if learner.inTrain{ learner.pctEpochs += 1.0 / Float(learner.iterCount) } } public override func validationWillStart(learner: Learner) { Context.local.learningPhase = .inference learner.inTrain = false learner.currentIter = 0 } } public func makeTrainEvalDelegate() -> TrainEvalDelegate { return TrainEvalDelegate() } } extension Learner { public class AvgMetric: Delegate { public let metrics: [(Output, Label) -> TF] var total: Int = 0 var partials = [TF]() public init(metrics: [(Output, Label) -> TF]) { self.metrics = metrics} public override func epochWillStart(learner: Learner) { total = 0 partials = Array(repeating: Tensor(0), count: metrics.count + 1) } public override func batchDidFinish(learner: Learner) { if !learner.inTrain{ let bs = learner.currentInput!.shape[0] //Possible because Input is TF for now total += bs partials[0] += Float(bs) * learner.currentLoss for i in 1...metrics.count{ partials[i] += Float(bs) * metrics[i-1](learner.currentOutput!, learner.currentTarget!) } } } public override func epochDidFinish(learner: Learner) { for i in 0...metrics.count {partials[i] = partials[i] / Float(total)} print("Epoch \(learner.currentEpoch): \(partials)") } } public func makeAvgMetric(metrics: [(Output, Label) -> TF]) -> AvgMetric{ return AvgMetric(metrics: metrics) } } extension Learner { public class Normalize: Delegate { public let mean, std: TF public init(mean: TF, std: TF) { (self.mean,self.std) = (mean,std) } public override func batchWillStart(learner: Learner) { learner.currentInput = (learner.currentInput! - mean) / std } } public func makeNormalize(mean: TF, std: TF) -> Normalize{ return Normalize(mean: mean, std: std) } } public let mnistStats = (mean: TF(0.13066047), std: TF(0.3081079))
37.955017
111
0.617741
288849fc72833e55b44d7a96c07b9c69f79a705f
2,288
// // SceneDelegate.swift // KVOMVVM // // Created by akio0911 on 2020/12/20. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.169811
147
0.71285
469ffa4eae306410228c1f6bfeeaea490888140a
2,259
// // SceneDelegate.swift // AutoLayout_Homework // // Created by 윤병일 on 2020/05/17. // Copyright © 2020 Byoungil Youn. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
41.833333
143
0.744135
39ecbe181ccce0eb298a95dba1bd081a57caca93
1,236
// // weiBoSwiftUITests.swift // weiBoSwiftUITests // // Created by MAC on 15/11/25. // Copyright © 2015年 MAC. All rights reserved. // import XCTest class weiBoSwiftUITests: 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. } }
33.405405
182
0.661812
d6f6337c8d405cab4da617b46ac9320496fef270
14,137
// Copyright 2016 The Tulsi 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 XCTest @testable import TulsiGenerator // End to end tests that generate xcodeproj bundles and validate them against golden versions. class EndToEndGenerationTests: EndToEndIntegrationTestCase { func test_SimpleProject() { let testDir = "tulsi_e2e_simple" installBUILDFile("Simple", intoSubdirectory: testDir) makeTestXCDataModel("SimpleDataModelsTestv1", inSubdirectory: "\(testDir)/SimpleTest.xcdatamodeld") makeTestXCDataModel("SimpleDataModelsTestv2", inSubdirectory: "\(testDir)/SimpleTest.xcdatamodeld") makePlistFileNamed(".xccurrentversion", withContent: ["_XCCurrentVersionName": "SimpleDataModelsTestv1.xcdatamodel"], inSubdirectory: "\(testDir)/SimpleTest.xcdatamodeld") let appLabel = BuildLabel("//\(testDir):Application") let targetLabel = BuildLabel("//\(testDir):TargetApplication") let hostLabels = Set<BuildLabel>([appLabel]) let buildTargets = [RuleInfo(label: appLabel, type: "ios_application", linkedTargetLabels: Set<BuildLabel>()), RuleInfo(label: targetLabel, type: "ios_application", linkedTargetLabels: Set<BuildLabel>()), RuleInfo(label: BuildLabel("//\(testDir):XCTest"), type: "ios_test", linkedTargetLabels: hostLabels)] let additionalFilePaths = ["\(testDir)/BUILD"] let projectName = "SimpleProject" let options = TulsiOptionSet() options.options[.BazelContinueBuildingAfterError]?.projectValue = "YES" options.options[.CommandlineArguments]?.projectValue = "--project-flag" options.options[.CommandlineArguments]?.targetValues?[targetLabel.value] = "--target-specific-test-flag" options.options[.EnvironmentVariables]?.projectValue = "projectKey=projectValue" options.options[.EnvironmentVariables]?.targetValues?[targetLabel.value] = "targetKey1=targetValue1\ntargetKey2=targetValue2=\ntargetKey3=" options.options[.BuildActionPreActionScript]?.projectValue = "This is a build pre action script" options.options[.BuildActionPreActionScript]?.targetValues?[targetLabel.value] = "This is a target specific build pre action script" options.options[.BuildActionPostActionScript]?.projectValue = "This is a build post action script" options.options[.BuildActionPostActionScript]?.targetValues?[targetLabel.value] = "This is a target specific build post action script" options.options[.LaunchActionPreActionScript]?.projectValue = "This is a lauch pre action script" options.options[.LaunchActionPreActionScript]?.targetValues?[targetLabel.value] = "This is a target specific launch pre action script" options.options[.LaunchActionPostActionScript]?.projectValue = "This is a launch post action script" options.options[.LaunchActionPostActionScript]?.targetValues?[targetLabel.value] = "This is a target specific launch post action script" options.options[.TestActionPreActionScript]?.projectValue = "This is a test pre action script" options.options[.TestActionPreActionScript]?.targetValues?[targetLabel.value] = "This is a target specific test pre action script" options.options[.TestActionPostActionScript]?.projectValue = "This is a test post action script" options.options[.TestActionPostActionScript]?.targetValues?[targetLabel.value] = "This is a target specific test post action script" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/..."], additionalFilePaths: additionalFilePaths, outputDir: "tulsi_e2e_output/", options: options) else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_ComplexSingleProject() { let testDir = "tulsi_e2e_complex" installBUILDFile("ComplexSingle", intoSubdirectory: testDir) makeTestXCDataModel("DataModelsTestv1", inSubdirectory: "\(testDir)/Test.xcdatamodeld") makeTestXCDataModel("DataModelsTestv2", inSubdirectory: "\(testDir)/Test.xcdatamodeld") makePlistFileNamed(".xccurrentversion", withContent: ["_XCCurrentVersionName": "DataModelsTestv2.xcdatamodel"], inSubdirectory: "\(testDir)/Test.xcdatamodeld") let appLabel = BuildLabel("//\(testDir):Application") let hostLabels = Set<BuildLabel>([appLabel]) let buildTargets = [RuleInfo(label: appLabel, type: "ios_application", linkedTargetLabels: Set<BuildLabel>()), RuleInfo(label: BuildLabel("//\(testDir):XCTest"), type: "ios_test", linkedTargetLabels: hostLabels)] let additionalFilePaths = ["\(testDir)/BUILD"] let projectName = "ComplexSingleProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/...", "blaze-bin/...", "blaze-genfiles/..."], additionalFilePaths: additionalFilePaths, outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_SwiftProject() { let testDir = "tulsi_e2e_swift" installBUILDFile("Swift", intoSubdirectory: testDir) let appLabel = BuildLabel("//\(testDir):Application") let buildTargets = [RuleInfo(label: appLabel, type: "ios_application", linkedTargetLabels: Set<BuildLabel>())] let additionalFilePaths = ["\(testDir)/BUILD"] let projectName = "SwiftProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/...", "blaze-bin/...", "blaze-genfiles/..."], additionalFilePaths: additionalFilePaths, outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_watchProject() { let testDir = "tulsi_e2e_watch" installBUILDFile("Watch", intoSubdirectory: testDir) let appLabel = BuildLabel("//\(testDir):Application") let buildTargets = [RuleInfo(label: appLabel, type: "ios_application", linkedTargetLabels: Set<BuildLabel>())] let additionalFilePaths = ["\(testDir)/BUILD"] let projectName = "WatchProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/...", "blaze-bin/...", "blaze-genfiles/..."], additionalFilePaths: additionalFilePaths, outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_macProject() { let testDir = "tulsi_e2e_mac" installBUILDFile("Mac", intoSubdirectory: testDir) let appLabel = BuildLabel("//\(testDir):MyMacOSApp") let commandLineAppLabel = BuildLabel("//\(testDir):MyCommandLineApp") let buildTargets = [RuleInfo(label: appLabel, type: "macos_application", linkedTargetLabels: Set<BuildLabel>()), RuleInfo(label: commandLineAppLabel, type: "macos_command_line_application", linkedTargetLabels: Set<BuildLabel>())] let additionalFilePaths = ["\(testDir)/BUILD"] let projectName = "MacOSProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/...", "blaze-bin/...", "blaze-genfiles/..."], additionalFilePaths: additionalFilePaths, outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } } // End to end tests that generate xcodeproj bundles and validate them against golden versions. class TestSuiteEndToEndGenerationTests: EndToEndIntegrationTestCase { let testDir = "TestSuite" let appRule = RuleInfo(label: BuildLabel("//TestSuite:TestApplication"), type: "ios_application", linkedTargetLabels: Set<BuildLabel>()) override func setUp() { super.setUp() installBUILDFile("TestSuiteRoot", intoSubdirectory: testDir, fromResourceDirectory: "TestSuite") installBUILDFile("TestOne", intoSubdirectory: "\(testDir)/One", fromResourceDirectory: "TestSuite/One") installBUILDFile("TestTwo", intoSubdirectory: "\(testDir)/Two", fromResourceDirectory: "TestSuite/Two") installBUILDFile("TestThree", intoSubdirectory: "\(testDir)/Three", fromResourceDirectory: "TestSuite/Three") } func test_ExplicitXCTestsProject() { let buildTargets = [ appRule, RuleInfo(label: BuildLabel("//\(testDir):explicit_XCTests"), type: "test_suite", linkedTargetLabels: Set<BuildLabel>()), ] let projectName = "TestSuiteExplicitXCTestsProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/..."], outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_TestSuiteLocalTaggedTestsProject() { let buildTargets = [ appRule, RuleInfo(label: BuildLabel("//\(testDir):local_tagged_tests"), type: "test_suite", linkedTargetLabels: Set<BuildLabel>()), ] let projectName = "TestSuiteLocalTaggedTestsProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/..."], outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } func test_TestSuiteRecursiveTestSuiteProject() { let buildTargets = [ appRule, RuleInfo(label: BuildLabel("//\(testDir):recursive_test_suite"), type: "test_suite", linkedTargetLabels: Set<BuildLabel>()), ] let projectName = "TestSuiteRecursiveTestSuiteProject" guard let projectURL = generateProjectNamed(projectName, buildTargets: buildTargets, pathFilters: ["\(testDir)/..."], outputDir: "tulsi_e2e_output/") else { // The test has already been marked as failed. return } let diffLines = diffProjectAt(projectURL, againstGoldenProject: projectName) validateDiff(diffLines) } }
47.922034
140
0.577209
72fb1868550f3cf1bf4b89f7593cacc00f5e98f1
1,088
// // EzsignbulksendCreateObjectV1ResponseMPayload.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif /** Payload for POST /1/object/ezsignbulksend */ public struct EzsignbulksendCreateObjectV1ResponseMPayload: Codable, JSONEncodable, Hashable { /** An array of unique IDs representing the object that were requested to be created. They are returned in the same order as the array containing the objects to be created that was sent in the request. */ public var aPkiEzsignbulksendID: [Int] public init(aPkiEzsignbulksendID: [Int]) { self.aPkiEzsignbulksendID = aPkiEzsignbulksendID } public enum CodingKeys: String, CodingKey, CaseIterable { case aPkiEzsignbulksendID = "a_pkiEzsignbulksendID" } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(aPkiEzsignbulksendID, forKey: .aPkiEzsignbulksendID) } }
31.085714
209
0.748162
1c1c5c805bc27ca8b79fdc283c0a81dde2d40666
999
import Foundation enum SCSpotEndpoint { case all case forecast(spotId: Int) case nearby(lat: Float, lon: Float) case neighbors(spotId: Int) } extension SCSpotEndpoint: Endpoint { var baseUrl: URL { return URL(string: "http://api.spitcast.com/api/spot/")! } var path: String { switch self { case .all: return "all" case let .forecast(spotId): return "forecast/\(spotId)" case .nearby: return "nearby" case let .neighbors(spotId): return "neighbors/\(spotId)" } } func url() -> URL? { let url = URL(string: path, relativeTo: baseUrl)! switch self { case .all, .forecast, .neighbors: return url case let .nearby(lat, lon): var components = URLComponents(string: url.absoluteString) components?.queryItems = [URLQueryItem(name: "latitude", value: String(lat)), URLQueryItem(name: "longitude", value: String(lon))] return components?.url ?? url } } }
23.785714
84
0.615616
f7ba55f0b0446cc13c62e8c38365bc01d76bd5b9
723
import UIKit import Render class Example1ViewController: UIViewController { let component = HelloWorldComponentView() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = Color.white self.view.addSubview(component) self.title = "EXAMPLE 1" generateRandomStates() } func generateRandomStates() { component.state = HelloWorldState(name: "Alex") component.render(in: self.view.bounds.size) component.center = self.view.center } override func viewDidLayoutSubviews() { component.render(in: self.view.bounds.size) component.center = self.view.center } }
22.59375
58
0.728907
697e4a423626fbdfeb71e891b1907b0c448fd2dc
350
import Foundation /** Class represents the GetBlockTransfersResult */ public class GetBlockTransfersResult { ///the Casper api version public var api_version:ProtocolVersion=ProtocolVersion() //the block hash of the block public var block_hash:String = "" //the transfer list of the block public var transfers:[Transfer]? }
26.923077
60
0.737143
7ac175df545485500120f28998f7338fbbdf639a
1,536
// // pinky.swift // quiz // // Created by IOSLevel01 on 24/10/19. // Copyright © 2019 Sjbit. All rights reserved. // import UIKit class pinky: UIViewController { var gameMode = "hahaha" override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "one"{ let destinationVC = segue.destination as! chihuaha destinationVC.gm = gameMode } } //var diff = 1 @IBAction func Symbole(_ sender: Any) { gameMode = "sym" self.performSegue(withIdentifier: "one", sender: self) } @IBAction func Name(_ sender: Any) { gameMode = "name" self.performSegue(withIdentifier: "one", sender: self) } @IBAction func AtNo(_ sender: Any) { gameMode = "atn" self.performSegue(withIdentifier: "one", sender: self) } //we have established the game mode at this point and now we need to know what level of difficulty they're going to select override func viewDidLoad() { super.viewDidLoad() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
20.756757
126
0.58138
213bc5eacd8dba262adf4dfd24ed8a042e566cbd
2,108
// 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 VirtualMachineScaleSetSkuData : VirtualMachineScaleSetSkuProtocol { public var resourceType: String? public var sku: SkuProtocol? public var capacity: VirtualMachineScaleSetSkuCapacityProtocol? enum CodingKeys: String, CodingKey {case resourceType = "resourceType" case sku = "sku" case capacity = "capacity" } public init() { } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) if container.contains(.resourceType) { self.resourceType = try container.decode(String?.self, forKey: .resourceType) } if container.contains(.sku) { self.sku = try container.decode(SkuData?.self, forKey: .sku) } if container.contains(.capacity) { self.capacity = try container.decode(VirtualMachineScaleSetSkuCapacityData?.self, forKey: .capacity) } 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) if self.resourceType != nil {try container.encode(self.resourceType, forKey: .resourceType)} if self.sku != nil {try container.encode(self.sku as! SkuData?, forKey: .sku)} if self.capacity != nil {try container.encode(self.capacity as! VirtualMachineScaleSetSkuCapacityData?, forKey: .capacity)} } } extension DataFactory { public static func createVirtualMachineScaleSetSkuProtocol() -> VirtualMachineScaleSetSkuProtocol { return VirtualMachineScaleSetSkuData() } }
40.538462
128
0.710152
f9ef15e18972986d0c4379d75fc7911d0eb53f16
4,687
//: [Previous](@previous) //: ### Manipulation import SION //: a blank JSON Array is as simple as: var sion = SION([]) //: and you can assign elements like an ordinary array sion[0] = nil sion[1] = true sion[2] = 1 sion[3] = 1.0 //: note RHS literals are NOT `nil`, `true` and `1` but `.Null`, `.Bool(true)`, `.Int(1)` and `.Double(1.0)`. //: so this does NOT work let one = "one" //sion[4] = one // error: cannot assign value of type 'String' to type 'JSON' //: in which case you can do the following: sion[4].string = one //: they are all getters and setters. sion[1].bool = true sion[2].int = 1 sion[3].double = 1.0 sion[4].string = "one" sion[5].array = [1] sion[6].dictionary = ["one":1] //: As a getter they are optional which returns `nil` when the type mismaches. sion[1].bool // Optional(true) sion[1].int // nil //: Therefore, you can mutate like so: sion[2].int! += 1 // now 2 sion[3].double! *= 0.5 // now 0.5 sion[4].string!.removeLast() // now "on" sion[5].array!.append(2) // now [1, 2] sion[6].dictionary!["two"] = 2 // now ["one":1,"two":2] //: when you assign values to JSON array with an out-of-bound index, it is automatically streched with unassigned elements set to `null`, just like an ECMAScript `Array` sion[10] = false sion[9] sion //: As you may have guessed by now, a blank JSON object(dictionary) is: sion = SION([:]) //: and manipulate intuitively sion["nil"] = nil sion["bool"] = false sion["int"] = 0 sion["double"] = 0.0 sion["string"] = "" sion["array"] = [] sion["dictionary"] = [:] //: #### deep traversal //: `JSON` is a recursive data type. For recursive data types, you need a recursive method that traverses the data deep down. For that purpuse, `JSON` offers `.pick` and `.walk`. //: `.pick` is a "`.deepFilter`" that filters recursively. You've already seen it above. It takes a filter function of type `(JSON)->Bool`. That function is applied to all leaf values of the tree and leaves that do not meet the predicate are pruned. // because property list does not accept nil let sion4plist = sion.pick{ !$0.isNil } //: `.walk` is a `deepMap` that transforms recursively. This one is a little harder because you have to consider what to do on node and leaves separately. To make your life easier three different forms of `.walk` are provided. The first one just takes a leaf. SION([0,[1,[2,3,[4,5,6]]], true]).walk { guard let n = $0.int else { return $0 } return SION(n * n) } //: The second forms just takes a node. Instead of explaining it, let me show you how `.pick` is implemented by extending `JSON` with `.select` that does exactly the same as `.pick`. extension SION { func select(picker:(SION)->Bool)->SION { return self.walk{ node, pairs, depth in switch node.type { case .array: return .Array(pairs.map{ $0.1 }.filter{ picker($0) } ) case .dictionary: var o = [Key:Value]() pairs.filter{ picker($0.1) }.forEach{ o[$0.0] = $0.1 } return .Dictionary(o) default: return .Error(.notIterable(node.type)) } } } } //: And the last form takes both. Unlike the previous ones this one can return other than `JSON`. Here is a quick and dirty `.yaml` that emits a YAML. extension SION { public var yaml:String { return self.walk(depth:0, collect:{ node, pairs, depth in let indent = Swift.String(repeating:" ", count:depth) var result = "" switch node.type { case .array: guard !pairs.isEmpty else { return "[]"} result = pairs.map{ "- " + $0.1}.map{indent + $0}.joined(separator: "\n") case .dictionary: guard !pairs.isEmpty else { return "{}"} result = pairs.sorted{ $0.0.description < $1.0.description }.map{ let k = $0.0.string ?? $0.0.description let q = k.rangeOfCharacter(from: .newlines) != nil return (q ? k.debugDescription : k) + ": " + $0.1 }.map{indent + $0}.joined(separator: "\n") default: break // never reaches here } return "\n" + result },visit:{ if $0.isNil { return "~" } if let s = $0.string { return s.rangeOfCharacter(from: .newlines) == nil ? s : s.debugDescription } return $0.description }) } } //: and the second one just takes a node. //: //: [Next](@next)
38.735537
262
0.577768
e0d5a94f25b31b7f61bd267da9464e462a566b39
20,283
// // BlockTests.swift // // // Created by Mathieu Barnachon on 13/07/2019. // import XCTest import Nimble import SwiftyJSON @testable import SwiftySlack // Test values are coming from the Slack documentation: // https://api.slack.com/reference/messaging/payload final class SectionBlockTests: XCTestCase { func testSimple() { let section = SectionBlock(text: Text("A message *with some bold text* and _some italicized text_.")) let expectedJSON = JSON(parseJSON: """ { "type": "section", "text": { "type": "mrkdwn", "text": "A message *with some bold text* and _some italicized text_." } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testTextFields() { let section = SectionBlock( text: MarkdownText("A message *with some bold text* and _some italicized text_."), fields: [ MarkdownText("High"), PlainText(text: "String", emoji: true) ]) let expectedJSON = JSON(parseJSON: """ { "type": "section", "text": { "text": "A message *with some bold text* and _some italicized text_.", "type": "mrkdwn" }, "fields": [ { "type": "mrkdwn", "text": "High" }, { "type": "plain_text", "emoji": true, "text": "String" } ] } """) expect{ jsonEncode(object: section) } == expectedJSON } func testImage() { // Manual escape of URL due to JSONEncoder. let section = SectionBlock( text: MarkdownText("This is a section block with an accessory image."), block_id: "section567", accessory: ImageElement( image_url: URL(string: "https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg")!, alt_text: "cute cat") ) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section567", "text": { "type": "mrkdwn", "text": "This is a section block with an accessory image." }, "accessory": { "type": "image", "image_url": "https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg", "alt_text": "cute cat" } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testStaticSelect() { let select = StaticSelect( placeholder: PlainText("Select an item"), action_id: "text1234", options: [ Option(text: PlainText("*this is plain_text text*"), value: "value-0"), Option(text: PlainText("*this is plain_text text*"), value: "value-1"), Option(text: PlainText("*this is plain_text text*"), value: "value-2") ] ) let section = SectionBlock( text: MarkdownText("Pick an item from the dropdown list"), block_id: "section678", fields: [], accessory: select) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section678", "text": { "type": "mrkdwn", "text": "Pick an item from the dropdown list" }, "accessory": { "action_id": "text1234", "type": "static_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "options": [ { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-0" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-1" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-2" } ] } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testExternalSelect() { let select = ExternalSelect( placeholder: PlainText("Select an item"), action_id: "text1234", min_query_length: 3) let section = SectionBlock( text: MarkdownText("Pick an item from the dropdown list"), block_id: "section678", fields: [], accessory: select) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section678", "text": { "type": "mrkdwn", "text": "Pick an item from the dropdown list" }, "accessory": { "action_id": "text1234", "type": "external_select", "placeholder": { "type": "plain_text", "text": "Select an item" }, "min_query_length": 3 } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testUserSelect() { let select = UsersSelect( placeholder: PlainText("Select an item"), action_id: "text1234") let section = SectionBlock( text: MarkdownText("Pick a user from the dropdown list"), block_id: "section678", fields: [], accessory: select) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section678", "text": { "type": "mrkdwn", "text": "Pick a user from the dropdown list" }, "accessory": { "action_id": "text1234", "type": "users_select", "placeholder": { "type": "plain_text", "text": "Select an item" } } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testConversationSelect() { let select = ConversationSelect( placeholder: PlainText("Select an item"), action_id: "text1234") let section = SectionBlock( text: MarkdownText("Pick a conversation from the dropdown list"), block_id: "section678", fields: [], accessory: select) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section678", "text": { "type": "mrkdwn", "text": "Pick a conversation from the dropdown list" }, "accessory": { "action_id": "text1234", "type": "conversations_select", "placeholder": { "type": "plain_text", "text": "Select an item" } } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testChannelSelect() { let select = ChannelSelect( placeholder: PlainText("Select an item"), action_id: "text1234") let section = SectionBlock( text: MarkdownText("Pick a channel from the dropdown list"), block_id: "section678", fields: [], accessory: select) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section678", "text": { "type": "mrkdwn", "text": "Pick a channel from the dropdown list" }, "accessory": { "action_id": "text1234", "type": "channels_select", "placeholder": { "type": "plain_text", "text": "Select an item" } } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testOverflow() { let section = SectionBlock( text: MarkdownText("Dependencies of SwiftySlack:"), block_id: "section 890", accessory: OverflowElement( action_id: "overflow", options: [ Option(text: PlainText("SwiftyRequest"), value: "swiftyrequest", url: URL(string: "https://github.com/IBM-Swift/SwiftyRequest")!), Option(text: PlainText("SwiftyJSON"), value: "swiftyjson", url: URL(string: "https://github.com/SwiftyJSON/SwiftyJSON")!), Option(text: PlainText("Promises"), value: "promises", url: URL(string: "https://github.com/google/promises")!), Option(text: PlainText("Nimble"), value: "nimble", url: URL(string: "https://github.com/Quick/Nimble")!) ] ) ) let expectedJSON = JSON(parseJSON: """ { "type": "section", "block_id": "section 890", "text": { "type": "mrkdwn", "text": "Dependencies of SwiftySlack:" }, "accessory": { "type": "overflow", "options": [ { "text": { "type": "plain_text", "text": "SwiftyRequest" }, "value": "swiftyrequest", "url": "https://github.com/IBM-Swift/SwiftyRequest" }, { "text": { "type": "plain_text", "text": "SwiftyJSON" }, "value": "swiftyjson", "url": "https://github.com/SwiftyJSON/SwiftyJSON" }, { "text": { "type": "plain_text", "text": "Promises" }, "value": "promises", "url": "https://github.com/google/promises" }, { "text": { "type": "plain_text", "text": "Nimble" }, "value": "nimble", "url": "https://github.com/Quick/Nimble" } ], "action_id": "overflow" } } """) expect{ jsonEncode(object: section) } == expectedJSON } func testDatepicker() { let section = SectionBlock( text: MarkdownText("*Sally* has requested you set the deadline for the Nano launch project"), accessory: DatePickerElement( placeholder: PlainText("Select a date"), action_id: "datepicker123", initial_date: DatePickerElement.date(from: "1990-04-28")!) ) let expectedJSON = JSON(parseJSON: """ { "type": "section", "text": { "text": "*Sally* has requested you set the deadline for the Nano launch project", "type": "mrkdwn" }, "accessory": { "type": "datepicker", "action_id": "datepicker123", "initial_date": "1990-04-28", "placeholder": { "type": "plain_text", "text": "Select a date" } } } """) expect{ jsonEncode(object: section) } == expectedJSON } static var allTests = [ ("testSimple", testSimple), ("testTextFields", testTextFields), ("testImage", testImage), ("testOverflow", testOverflow), ("testDatepicker", testDatepicker), ] } final class DividerBlockTests: XCTestCase { func testSimple() { let divider = DividerBlock() let expectedJSON = JSON(parseJSON: """ { "type": "divider" } """) expect{ jsonEncode(object: divider) } == expectedJSON } static var allTests = [ ("testSimple", testSimple), ] } final class ImageBlockTests: XCTestCase { func testSimple() { let image = ImageBlock( image_url: URL(string: "http://placekitten.com/500/500")!, alt_text: "An incredibly cute kitten.", title: PlainText("Please enjoy this photo of a kitten"), block_id: "image4") let expectedJSON = JSON(parseJSON: """ { "type": "image", "title": { "type": "plain_text", "text": "Please enjoy this photo of a kitten" }, "block_id": "image4", "image_url": "http://placekitten.com/500/500", "alt_text": "An incredibly cute kitten." } """) expect{ jsonEncode(object: image) } == expectedJSON } static var allTests = [ ("testSimple", testSimple), ] } final class ActionBlockTests: XCTestCase { func testSelectAndButton() { let actions = ActionsBlock( elements: [ StaticSelect( placeholder: PlainText("Which witch is the witchiest witch?"), action_id: "select_2", options: [ Option(text: PlainText("Matilda"), value: "matilda"), Option(text: PlainText("Glinda"), value: "glinda"), Option(text: PlainText("Granny Weatherwax"), value: "grannyWeatherwax"), Option(text: PlainText("Hermione"), value: "hermione") ] ), ButtonElement( text: PlainText("Cancel"), action_id: "button_1", value: "cancel") ], block_id: "actions1") let expectedJSON = JSON(parseJSON: """ { "type": "actions", "block_id": "actions1", "elements": [ { "type": "static_select", "placeholder":{ "type": "plain_text", "text": "Which witch is the witchiest witch?" }, "action_id": "select_2", "options": [ { "text": { "type": "plain_text", "text": "Matilda" }, "value": "matilda" }, { "text": { "type": "plain_text", "text": "Glinda" }, "value": "glinda" }, { "text": { "type": "plain_text", "text": "Granny Weatherwax" }, "value": "grannyWeatherwax" }, { "text": { "type": "plain_text", "text": "Hermione" }, "value": "hermione" } ] }, { "type": "button", "text": { "type": "plain_text", "text": "Cancel" }, "value": "cancel", "action_id": "button_1" } ] } """) expect{ jsonEncode(object: actions) } == expectedJSON } func testDatePickerAndOverflow() { let actions = ActionsBlock( elements: [ DatePickerElement( placeholder: PlainText("Select a date"), action_id: "datepicker123", initial_date: DatePickerElement.date(from: "1990-04-28")! ), OverflowElement( action_id: "overflow", options: [ Option(text: PlainText("*this is plain_text text*"), value: "value-0"), Option(text: PlainText("*this is plain_text text*"), value: "value-1"), Option(text: PlainText("*this is plain_text text*"), value: "value-2"), Option(text: PlainText("*this is plain_text text*"), value: "value-3"), Option(text: PlainText("*this is plain_text text*"), value: "value-4"), ] ), ButtonElement( text: PlainText("Click Me"), action_id: "button", value: "click_me_123" ) ], block_id: "actionblock789") let expectedJSON = JSON(parseJSON: """ { "type": "actions", "block_id": "actionblock789", "elements": [ { "type": "datepicker", "action_id": "datepicker123", "initial_date": "1990-04-28", "placeholder": { "type": "plain_text", "text": "Select a date" } }, { "type": "overflow", "options": [ { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-0" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-1" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-2" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-3" }, { "text": { "type": "plain_text", "text": "*this is plain_text text*" }, "value": "value-4" } ], "action_id": "overflow" }, { "type": "button", "text": { "type": "plain_text", "text": "Click Me" }, "value": "click_me_123", "action_id": "button" } ] } """) expect{ jsonEncode(object: actions) } == expectedJSON } static var allTests = [ ("testSelectAndButton", testSelectAndButton), ("testDatePickerAndOverflow", testDatePickerAndOverflow), ] } final class ContextBlockTests: XCTestCase { func testSimple() { let context = ContextBlock(elements: [ ContextBlock.ContextElement(image: ImageElement( image_url: URL(string: "https://image.freepik.com/free-photo/red-drawing-pin_1156-445.jpg")!, alt_text: "images")), ContextBlock.ContextElement(text: MarkdownText("Location: **Dogpatch**")) ] ) let expectedJSON = JSON(parseJSON: """ { "type": "context", "elements": [ { "type": "image", "image_url": "https://image.freepik.com/free-photo/red-drawing-pin_1156-445.jpg", "alt_text": "images" }, { "type": "mrkdwn", "text": "Location: **Dogpatch**" }, ] } """) expect{ jsonEncode(object: context) } == expectedJSON } func testComplete() { let context = ContextBlock(elements: [ ContextBlock.ContextElement(text: MarkdownText(text: "*Author:* T. M. Schwartz", verbatim: true)), ContextBlock.ContextElement(text: PlainText(text: "*Author:* T. M. Schwartz", emoji: true)), ContextBlock.ContextElement(image: ImageElement( image_url: URL(string: "https://api.slack.com/img/blocks/bkb_template_images/goldengate.png")!, alt_text: "Example Image")), ] ) let expectedJSON = JSON(parseJSON: """ { "type": "context", "elements": [ { "type": "mrkdwn", "text": "*Author:* T. M. Schwartz", "verbatim": true }, { "type": "plain_text", "text": "*Author:* T. M. Schwartz", "emoji": true }, { "type": "image", "image_url": "https://api.slack.com/img/blocks/bkb_template_images/goldengate.png", "alt_text": "Example Image" } ] } """) expect{ jsonEncode(object: context) } == expectedJSON } static var allTests = [ ("testSimple", testSimple), ("testComplete", testComplete), ] } final class FileBlockTests: XCTestCase { func testSimple() { let file = FileBlock(external_id: "ABCD1") let expectedJSON = JSON(parseJSON: """ { "type": "file", "external_id": "ABCD1", "source": "remote", } """) expect{ jsonEncode(object: file) } == expectedJSON } static var allTests = [ ("testSimple", testSimple), ] }
29.353111
112
0.471922
094ad41032d4342a9871c3c76964fba4257f6400
1,066
import UIKit enum AuthAssembly { static func buildAuthScreenModule(_ completion: (UIViewController?, AuthModuleInput?) -> Void) { // Creating module components guard let moduleViewController = R.storyboard.auth.authViewController() else { completion(nil, nil) return } let presenter = AuthPresenter() let authService = AppDelegate.serviceProvider.makeAuthService() let router = AuthRouter() let windowService = AppDelegate.serviceProvider.makeWindowService() let moduleService = AppDelegate.serviceProvider.makeModuleService() // Inject properties moduleViewController.output = presenter moduleViewController.windowService = windowService presenter.view = moduleViewController presenter.router = router presenter.authService = authService router.viewController = moduleViewController router.moduleService = moduleService completion(moduleViewController, presenter) } }
35.533333
100
0.680113
b900f870aaef58b6fd0cf0e1084831ce7e56ac71
759
// // ZSMineViewModel.swift // zhuishushenqi // // Created by yung on 2019/7/7. // Copyright © 2019 QS. All rights reserved. // import UIKit class ZSMineViewModel { var viewDidLoad: ()->() = {} var reloadBlock: ()->() = {} var service:ZSMyService = ZSMyService() var account:ZSAccount? init() { viewDidLoad = { [weak self] in self?.requestAccount() } } func requestAccount() { requestAccount { [weak self] in self?.reloadBlock() } } func requestAccount(completion:@escaping()->Void) { service.fetchAccount(token: ZSLogin.share.token) { (account) in self.account = account completion() } } }
19.461538
71
0.545455
21f3c260e8a6c1c1f18e7d2f8fd114775fff7b8d
1,795
import Pilot import Foundation public struct SongViewModel: ViewModel { public init(model: Model, context: Context) { self.song = model.typedModel() self.context = context } // MARK: Public public var name: String { return song.trackName } public var description: String { if let number = song.trackNumber { if let count = song.trackCount { return "Track \(number)/\(count) · \(collectionName)" } else { return "Track \(number) · \(collectionName)" } } else { return collectionName } } public var collectionName: String { return song.collectionName } public var duration: String { let totalSeconds = song.trackTimeMillis / 1000 let hours = totalSeconds / 3600 let minutes = (totalSeconds % 3600) / 60 let seconds = (totalSeconds % 60) if hours > 0 { return String(format: "%02d:%02d:%02d", hours, minutes, seconds) } else if minutes > 0 { return String(format: "%02d:%02d", minutes, seconds) } else { return String(format: "%02d", seconds) } } public var artwork: URL? { return song.artworkUrl100 } // MARK: ViewModel public let context: Context public func actionForUserEvent(_ event: ViewModelUserEvent) -> Action? { if case .select = event { return ViewMediaAction(url: song.previewUrl) } return nil } // MARK: Private private let song: Song } extension Song: ViewModelConvertible { public func viewModelWithContext(_ context: Context) -> ViewModel { return SongViewModel(model: self, context: context) } }
25.28169
76
0.579944
0a7a3bb7175f0846f266e4ddc43fcabd6f7f0cd7
329
// // Lyric.swift // LyricFetcher // // Created by CaptainYukinoshitaHachiman on 22/05/2019. // import Foundation struct Lyric: Codable { struct Lrc: Codable { let version: Int let lyric: String? } let lrc: Lrc struct Tlyric: Codable { let version: Int let lyric: String? } let tlyric: Tlyric let code: Int }
14.304348
56
0.680851
f9be53043273d4bc77048c7a167968d5d538d397
22,606
// RUN: %target-swift-emit-silgen -module-name protocols %s | %FileCheck %s //===----------------------------------------------------------------------===// // Calling Existential Subscripts //===----------------------------------------------------------------------===// protocol SubscriptableGet { subscript(a : Int) -> Int { get } } protocol SubscriptableGetSet { subscript(a : Int) -> Int { get set } } var subscriptableGet : SubscriptableGet var subscriptableGetSet : SubscriptableGetSet func use_subscript_rvalue_get(_ i : Int) -> Int { return subscriptableGet[i] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_rvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols16subscriptableGetAA013SubscriptableC0_pvp : $*SubscriptableGet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*SubscriptableGet // CHECK-NEXT: [[TMP:%.*]] = alloc_stack // CHECK-NEXT: copy_addr [[ALLOCSTACK]] to [initialization] [[TMP]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[TMP]]) // CHECK-NEXT: destroy_addr [[TMP]] // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] // CHECK-NEXT: dealloc_stack [[TMP]] // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_get(_ i : Int) -> Int { return subscriptableGetSet[i] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_get // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter // CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]]) // CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*SubscriptableGetSet // CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]] // CHECK-NEXT: return [[RESULT]] func use_subscript_lvalue_set(_ i : Int) { subscriptableGetSet[i] = i } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols19subscriptableGetSetAA013SubscriptablecD0_pvp : $*SubscriptableGetSet // CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*SubscriptableGetSet // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Subscripts //===----------------------------------------------------------------------===// func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_rvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter // CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK: } // end sil function '${{.*}}use_subscript_archetype_rvalue_get func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int { return generic[idx] } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_get // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T // CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr [[READ]] to [initialization] [[GUARANTEEDSTACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter // CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]]) // CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T // CHECK-NEXT: end_access [[READ]] // CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T // CHECK: return [[APPLYRESULT]] func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) { generic[idx] = idx } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_subscript_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter // CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[WRITE]]) //===----------------------------------------------------------------------===// // Calling Existential Properties //===----------------------------------------------------------------------===// protocol PropertyWithGetter { var a : Int { get } } protocol PropertyWithGetterSetter { var b : Int { get set } } var propertyGet : PropertyWithGetter var propertyGetSet : PropertyWithGetterSetter func use_property_rvalue_get() -> Int { return propertyGet.a } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_rvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols11propertyGetAA18PropertyWithGetter_pvp : $*PropertyWithGetter // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]] // CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]] // CHECK-NEXT: end_access [[READ]] : $*PropertyWithGetter // CHECK: [[BORROW:%.*]] = alloc_stack $[[OPENED]] // CHECK-NEXT: copy_addr [[COPY]] to [initialization] [[BORROW]] : $*[[OPENED]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[BORROW]]) func use_property_lvalue_get() -> Int { return propertyGetSet.b } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_get // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr immutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]] // CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]]) func use_property_lvalue_set(_ x : Int) { propertyGetSet.b = x } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_lvalue_set // CHECK: bb0(%0 : $Int): // CHECK: [[GLOB:%[0-9]+]] = global_addr @$s9protocols14propertyGetSetAA24PropertyWithGetterSetter_pvp : $*PropertyWithGetterSetter // CHECK: [[READ:%.*]] = begin_access [modify] [dynamic] [[GLOB]] : $*PropertyWithGetterSetter // CHECK: [[PROJ:%[0-9]+]] = open_existential_addr mutable_access [[READ]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter // CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]]) //===----------------------------------------------------------------------===// // Calling Archetype Properties //===----------------------------------------------------------------------===// func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int { return generic.a } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_rvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] // CHECK-NEXT: dealloc_stack [[STACK]] // CHECK: } // end sil function '{{.*}}use_property_archetype_rvalue_get func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int { return generic.b } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_get // CHECK: bb0(%0 : $*T): // CHECK: [[STACK:%[0-9]+]] = alloc_stack $T // CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[METH]]<T>([[STACK]]) // CHECK-NEXT: destroy_addr [[STACK]] : $*T // CHECK-NEXT: dealloc_stack [[STACK]] : $*T // CHECK: } // end sil function '${{.*}}use_property_archetype_lvalue_get func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) { generic.b = v } // CHECK-LABEL: sil hidden [ossa] @{{.*}}use_property_archetype_lvalue_set // CHECK: bb0(%0 : $*T, %1 : $Int): // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter // CHECK-NEXT: apply [[METH]]<T>(%1, [[WRITE]]) //===----------------------------------------------------------------------===// // Calling Initializers //===----------------------------------------------------------------------===// protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden [ossa] @$s9protocols27use_initializable_archetype{{[_0-9a-zA-Z]*}}F func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) { // CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T // CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator : {{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[T_RESULT]] : $*T // CHECK: dealloc_stack [[T_RESULT]] : $*T // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() T(int: i) } // CHECK: sil hidden [ossa] @$s9protocols29use_initializable_existential{{[_0-9a-zA-Z]*}}F func use_initializable_existential(_ im: Initializable.Type, i: Int) { // CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable // CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method: Initializable) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0 // CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable // CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable im.init(int: i) // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } //===----------------------------------------------------------------------===// // Protocol conformance and witness table generation //===----------------------------------------------------------------------===// class ClassWithGetter : PropertyWithGetter { var a: Int { get { return 42 } } } // Make sure we are generating a protocol witness that calls the class method on // ClassWithGetter. // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*ClassWithGetter): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0 // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter : (ClassWithGetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter { var a: Int { get { return 1 } set {} } var b: Int { get { return 2 } set {} } } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW : // CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow %0 // CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter : (ClassWithGetterSetter) -> () -> Int, $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return // Stored variables fulfilling property requirements // class ClassWithStoredProperty : PropertyWithGetter { var a : Int = 0 // Make sure that accesses go through the generated accessors for classes. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols23ClassWithStoredPropertyC011methodUsingE0SiyF // CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassWithStoredProperty): // CHECK-NEXT: debug_value [[ARG]] // CHECK-NOT: copy_value // CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter : (ClassWithStoredProperty) -> () -> Int, $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]]) // CHECK-NOT: destroy_value // CHECK-NEXT: return [[RESULT]] : $Int } struct StructWithStoredProperty : PropertyWithGetter { var a : Int // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols24StructWithStoredPropertyV011methodUsingE0SiyF // CHECK: bb0(%0 : $StructWithStoredProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a // CHECK-NEXT: return %2 : $Int } // Make sure that we generate direct function calls for out struct protocol // witness since structs don't do virtual calls for methods. // // *NOTE* Even though at first glance the copy_addr looks like a leak // here, StructWithStoredProperty is a trivial struct implying that no // leak is occurring. See the test with StructWithStoredClassProperty // that makes sure in such a case we don't leak. This is due to the // thunking code being too dumb but it is harmless to program // correctness. // // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [trivial] [[C]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols24StructWithStoredPropertyV1aSivg : $@convention(method) (StructWithStoredProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: return class C {} // Make sure that if the getter has a class property, we pass it in // in_guaranteed and don't leak. struct StructWithStoredClassProperty : PropertyWithGetter { var a : Int var c: C = C() // Make sure that accesses aren't going through the generated accessors. func methodUsingProperty() -> Int { return a } // CHECK-LABEL: sil hidden [ossa] @$s9protocols29StructWithStoredClassPropertyV011methodUsingF0SiyF // CHECK: bb0(%0 : @guaranteed $StructWithStoredClassProperty): // CHECK-NEXT: debug_value %0 // CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a // CHECK-NEXT: return %2 : $Int } // CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW : // CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty): // CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load_borrow [[C]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[FUN:%.*]] = function_ref @$s9protocols29StructWithStoredClassPropertyV1aSivg : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int // CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]]) // CHECK-NEXT: end_borrow [[CCOPY_LOADED]] // CHECK-NEXT: return // rdar://22676810 protocol ExistentialProperty { var p: PropertyWithGetterSetter { get set } } func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) { let b = t.p.b } // CHECK-LABEL: sil hidden [ossa] @$s9protocols27testExistentialPropertyRead{{[_0-9a-zA-Z]*}}F // CHECK: [[READ:%.*]] = begin_access [read] [unknown] %0 : $*T // CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter // CHECK: [[T_TEMP:%.*]] = alloc_stack $T // CHECK: copy_addr [[READ]] to [initialization] [[T_TEMP]] : $*T // CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter : // CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]]) // CHECK-NEXT: destroy_addr [[T_TEMP]] // CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr immutable_access [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]] // CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]] // CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]] // CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter // CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]]) // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_addr [[T0]] // CHECK-NOT: witness_method // CHECK: return func modify(_ x: inout Int) {} func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) { modify(&x.b) } // CHECK-LABEL: sil hidden [ossa] @$s9protocols14modifyPropertyyyxzAA0C16WithGetterSetterRzlF // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*T // CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!modify // CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[WITNESS_FN]]<T> // CHECK: [[MODIFY_FN:%.*]] = function_ref @$s9protocols6modifyyySizF // CHECK: apply [[MODIFY_FN]]([[ADDR]]) // CHECK: end_apply [[TOKEN]] public struct Val { public var x: Int = 0 } public protocol Proto { var val: Val { get nonmutating set} } public func test(_ p: Proto) { p.val.x += 1 } // CHECK-LABEL: sil [ossa] @$s9protocols4testyyAA5Proto_pF : $@convention(thin) (@in_guaranteed Proto) -> () // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access // CHECK: [[MAT:%.*]] = witness_method $@opened("{{.*}}") Proto, #Proto.val!modify // CHECK: ([[BUF:%.*]], [[TOKEN:%.*]]) = begin_apply [[MAT]] // CHECK: end_apply [[TOKEN]] // CHECK: return // SR-11748 protocol SelfReturningSubscript { subscript(b: Int) -> Self { get } } public func testSelfReturningSubscript() { // CHECK-LABEL: sil private [ossa] @$s9protocols26testSelfReturningSubscriptyyFAA0cdE0_pAaC_pXEfU_ // CHECK: [[OPEN:%.*]] = open_existential_addr immutable_access // CHECK: [[OPEN_ADDR:%.*]] = alloc_stack $@opened("{{.*}}") SelfReturningSubscript // CHECK: copy_addr [[OPEN]] to [initialization] [[OPEN_ADDR]] : $*@opened("{{.*}}") SelfReturningSubscript // CHECK: [[WIT_M:%.*]] = witness_method $@opened("{{.*}}") SelfReturningSubscript, #SelfReturningSubscript.subscript!getter // CHECK: apply [[WIT_M]]<@opened("{{.*}}") SelfReturningSubscript>({{%.*}}, {{%.*}}, [[OPEN_ADDR]]) _ = [String: SelfReturningSubscript]().mapValues { $0[2] } } // CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols15ClassWithGetterCAA08PropertycD0A2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols { // CHECK-NEXT: method #PropertyWithGetterSetter.b!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivgTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!setter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivsTW // CHECK-NEXT: method #PropertyWithGetterSetter.b!modify: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycdE0A2aDP1bSivMTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols21ClassWithGetterSetterCAA08PropertycD0A2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols24StructWithStoredPropertyVAA0eC6GetterA2aDP1aSivgTW // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols { // CHECK-NEXT: method #PropertyWithGetter.a!getter: {{.*}} : @$s9protocols29StructWithStoredClassPropertyVAA0fC6GetterA2aDP1aSivgTW // CHECK-NEXT: }
48.200426
270
0.654826
d54e781730e78f5d7e657c1a1169f75f7ed78f6b
1,923
// // OtherFunc.swift // OnionMobileClientDSL // // Created by XIANG KUILIN on 2022/1/13. // import Foundation import UIKit //16进制颜色 kRGBColorFromHexString("#F6F7F9") func kRGBColorFromHexString(_ colorStr:String) -> UIColor { var color = UIColor.red var cStr : String = colorStr.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() if cStr.hasPrefix("#") { let index = cStr.index(after: cStr.startIndex) cStr = cStr.substring(from: index) } if cStr.count != 6 && cStr.count != 8 { return UIColor.black } //是否是带透明度的8位16进制 var isAlphaValue:Bool = false var baseRGBIndex:Int = 0 if cStr.count == 8 { isAlphaValue = true baseRGBIndex = 2 } let rRange = cStr.index(cStr.startIndex, offsetBy: baseRGBIndex) ..< cStr.index(cStr.startIndex, offsetBy: baseRGBIndex+2) let rStr = cStr.substring(with: rRange) let gRange = cStr.index(cStr.startIndex, offsetBy: baseRGBIndex+2) ..< cStr.index(cStr.startIndex, offsetBy: baseRGBIndex+4) let gStr = cStr.substring(with: gRange) let bIndex = cStr.index(cStr.endIndex, offsetBy: -2) let bStr = cStr.substring(from: bIndex) var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0; Scanner(string: rStr).scanHexInt32(&r) Scanner(string: gStr).scanHexInt32(&g) Scanner(string: bStr).scanHexInt32(&b) //透明度提取支持 var a:CUnsignedInt = 0 var alpha:CGFloat = 1.0 if isAlphaValue { //透明度 let aRange = cStr.startIndex ..< cStr.index(cStr.startIndex, offsetBy: baseRGBIndex) let aStr = cStr.substring(with: aRange) Scanner(string: aStr).scanHexInt32(&a) alpha = CGFloat(a) / 255.0 } color = UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(alpha)) return color }
30.046875
128
0.642746
22373fb1288b6c48d094178fcd6e02ead4667f1f
1,070
// // SignInProtocols.swift // Duyog // // Created by Mounir Ybanez on 12/07/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit protocol SignInInteractorInputProtocol: class { func sigIn(email: String, password: String) } protocol SignInInteractorOutputProtocol: class { func onSignIn(_ result: SignInResult) } protocol SignInPresenterOutputProtocol: class { func onSignInError(_ title: String, message: String) func onSignInOk() } protocol SignInModuleOutputProtocol: class { } protocol SignInAssemblyProtocol: class { var generator: SignInViewControllerGeneratorProtocol! { get } func assemble(moduleOutput: SignInModuleOutputProtocol?) -> UIViewController } protocol SignInViewControllerProtocol: class { var interactor: SignInInteractorInputProtocol! { set get } var moduleOutput: SignInModuleOutputProtocol? { set get } } protocol SignInViewControllerGeneratorProtocol: class { func generate() -> SignInViewControllerProtocol & SignInPresenterOutputProtocol }
22.291667
83
0.742991
1c5688d42a5f90ee7ccb8490aae9b1fa5fe35735
3,106
import Foundation import Security public struct SessionStore { private static let serviceName = "com.proxpero.TMDbApi.SecureSessionStore.ServiceName" private let serviceName: String public init() { self.serviceName = SessionStore.serviceName } public init(serviceName: String) { self.serviceName = serviceName } func retrievalQuery(serviceName: String) -> [String : AnyObject] { var query = [String : AnyObject]() query[kSecClass as String] = kSecClassGenericPassword query[kSecAttrService as String] = serviceName as AnyObject query[kSecMatchLimit as String] = kSecMatchLimitOne query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecReturnData as String] = kCFBooleanTrue return query } func retrieveSessionId(status: OSStatus, queryResult: AnyObject?) -> String? { guard status != errSecItemNotFound, status == noErr, let existingItem = queryResult as? [String : AnyObject], let data = existingItem[kSecValueData as String] as? Data, let result = String(data: data, encoding: String.Encoding.utf8) else { return nil } return result } func setSessionId(encodedData: Data) -> Bool { let query = setterQuery(encodedSessionId: encodedData) let status = SecItemAdd(query as CFDictionary, nil) guard status == noErr else { print("Could not set session id. Removing secret.") return removeSessionId() } return true } func removalQuery() -> [String : AnyObject] { var query = [String : AnyObject]() query[kSecClass as String] = kSecClassGenericPassword query[kSecAttrService as String] = serviceName as AnyObject return query } func setterQuery(encodedSessionId: Data) -> [String : AnyObject] { var query = [String : AnyObject]() query[kSecClass as String] = kSecClassGenericPassword query[kSecAttrService as String] = serviceName as AnyObject query[kSecValueData as String] = encodedSessionId as AnyObject? return query } public var sessionId: String? { let query = retrievalQuery(serviceName: serviceName) var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } return retrieveSessionId(status: status, queryResult: queryResult) } public func setSessionId(_ newValue: String) -> Bool { return setSessionId(encodedData: newValue.data(using: .utf8)!) } public func removeSessionId() -> Bool { let query = removalQuery() let status = SecItemDelete(query as CFDictionary) guard status == noErr || status == errSecItemNotFound else { print("ERROR: Tried to remove a keychain item from the secure session store but it does not exist.") return false } return true } }
34.898876
112
0.648744
ff54a301ff0fc12f0a444512faa957063295e8dd
661
// // PostCell.swift // Insta // // Created by Melissa Phuong Nguyen on 2/26/18. // Copyright © 2018 Melissa Phuong Nguyen. All rights reserved. // import UIKit import Parse class PostCell: UITableViewCell { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var imageCaptureLabel: UILabel! @IBOutlet weak var postImage: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
21.322581
65
0.670197
ff9877d65ec583114b5124c387b9ed42152ed135
1,163
// // ZFBannerKitUITests.swift // ZFBannerKitUITests // // Created by  monstar on 2019/5/17. // Copyright © 2019 zhany. All rights reserved. // import XCTest class ZFBannerKitUITests: 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.228571
182
0.691316
293357977a9a0d0e67e009852d44b266fdc54a55
586
// // UpdateExcludedRoutes.swift // FilterRoutes // // Created by Tyler Madonna on 12/18/21. // Copyright © 2021 Tyler Madonna. All rights reserved. // import Foundation import Combine public final class UpdateExcludedRoutes { private let routeRepository: RouteRepositoryRepresentable public init(routeRepository: RouteRepositoryRepresentable) { self.routeRepository = routeRepository } func execute(routeIds: [String], stopId: String) -> AnyPublisher<Void, Error> { return routeRepository.updateExcludedRoutes(routeIds, stopId: stopId) } }
24.416667
83
0.737201
e0511d8ad7b9a9f377699c2f76d7960192847a77
284
// RUN: not --crash %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class d<T where T:c{class s{ var e=Swift. c var:{ var:T.E=.h
23.666667
87
0.725352
64856e0f19406bae9381b75a69d883f94646f61e
1,146
// // StorageType.swift // Secretly // // Created by Luis Ezcurdia on 29/05/21. // Copyright © 2021 3zcurdia. All rights reserved. // import Foundation enum StorageType { case cache case permanent var searchPathDirectory: FileManager.SearchPathDirectory { switch self { case .cache: return .cachesDirectory default: return .documentDirectory } } var url: URL { var url = FileManager.default.urls(for: searchPathDirectory, in: .userDomainMask).first! let applicationPath = "mx.unam.ioslab.secretly.storage" url.appendPathComponent(applicationPath) return url } var path: String { return url.path } func clear() { try? FileManager.default.removeItem(at: url) } func ensureExists() { var isDir: ObjCBool = false if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) { if isDir.boolValue { return } clear() } try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: nil) } }
23.875
110
0.623037
6a0afc914fa185e23c56de503cb9527469ad0317
1,310
// // URLCache.swift // ParseSwift // // Created by Corey Baker on 7/17/21. // Copyright © 2021 Parse Community. All rights reserved. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif internal extension URLCache { static let parse: URLCache = { guard let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return URLCache(memoryCapacity: ParseSwift.configuration.cacheMemoryCapacity, diskCapacity: ParseSwift.configuration.cacheDiskCapacity, diskPath: nil) } let parseCacheDirectory = "ParseCache" let diskURL = cacheURL.appendingPathComponent(parseCacheDirectory, isDirectory: true) #if !os(Linux) && !os(Android) && !os(Windows) return URLCache(memoryCapacity: ParseSwift.configuration.cacheMemoryCapacity, diskCapacity: ParseSwift.configuration.cacheDiskCapacity, directory: diskURL) #else return URLCache(memoryCapacity: ParseSwift.configuration.cacheMemoryCapacity, diskCapacity: ParseSwift.configuration.cacheDiskCapacity, diskPath: diskURL.absoluteString) #endif }() }
38.529412
110
0.658779
08caccfe5c41ba34a0a428f620b509f09cb33ed7
13,278
// // ViewController.swift // castleGIS // // Created by Nikita Semenov on 03.03.2021. // import UIKit import ArcGIS final class MapViewController: UIViewController { let DISTRICTS_REGIONS_KEY = "districtRegion" let DISTRICTS_CENTERS_KEY = "districtPoint" var graphicsOverlays: [String: [String: AGSGraphic]] = [:] // TODO: Make your own data struct private let graphicsOverlay = AGSGraphicsOverlay() var basemapPickerViewController : BasemapPickerViewController! var settingsViewController : SettingsViewController! var sceneViewController : SceneViewController! var detailWebViewController : DetailWebViewController! var mapView: AGSMapView = { MapView().map }() private var settingsButton : ButtonView = { let button = ButtonView(bgColor: ColorPicker.getMainColor(), tintColor: ColorPicker.getSubAccentColor(), image: "gear", isShadow: true) button.layer.cornerRadius = Measurements.getCornerRaduis() return button }() var basemapPickerButton : ButtonView = { let imageConfig = UIImage.SymbolConfiguration(pointSize: 20, weight: .regular, scale: .large) let button = ButtonView(bgColor: ColorPicker.getMainColor(), tintColor: ColorPicker.getSubAccentColor(), image: "square.stack.3d.down.forward.fill", imageConfiguration: imageConfig) button.layer.cornerRadius = Measurements.getCornerRaduis() return button }() private var minusScaleButton: ButtonView = { let imageConfig = UIImage.SymbolConfiguration(pointSize: 15, weight: .bold) let button = ButtonView(image: "minus", imageConfiguration: imageConfig, isShadow: true) button.layer.cornerRadius = Measurements.getCornerRaduis() - 5 return button }() private var plusScaleButton: ButtonView = { let imageConfig = UIImage.SymbolConfiguration(pointSize: 15, weight: .bold) let button = ButtonView(image: "plus", imageConfiguration: imageConfig, isShadow: true) button.layer.cornerRadius = Measurements.getCornerRaduis() - 5 return button }() private var compassButton : CompassButton = { let button = CompassButton() button.translatesAutoresizingMaskIntoConstraints = false button.setShadow(Shadow()) return button }() // MARK:- Public methods /// Adds and removes AGSGraphics from graphicsOverlay, depending on availability of graphics in overlay /// - Parameters: /// - graphics: Dictionary, where key is name or description of graphic, value is graphic itself /// - key: Key in graphicsOverlays func addAndRemoveGraphics(_ graphics: [String: AGSGraphic], withKey key: String) { // Add graphics if they weren't deleted (e.i. they aren't in dictionary) if !removeGraphics(forKey: key) { addGraphicsToDictionary(graphics, withKey: key) } addGraphics() } private func removeGraphics(forKey key: String) -> Bool { if let _ = self.graphicsOverlays[key] { self.graphicsOverlays.removeValue(forKey: key) graphicsOverlay.graphics.removeAllObjects() return true } else { return false } } private func addGraphicsToDictionary(_ graphics: [String: AGSGraphic], withKey key: String) { self.graphicsOverlays[key] = graphics } private func addGraphics() { graphicsOverlay.graphics.removeAllObjects() if let points = graphicsOverlays[DISTRICTS_CENTERS_KEY] { graphicsOverlays.removeValue(forKey: DISTRICTS_CENTERS_KEY) iterateAndAddGraphics() iterateAndAdd(graphics: points) graphicsOverlays[DISTRICTS_CENTERS_KEY] = points } else { iterateAndAddGraphics() } } private func iterateAndAddGraphics() { for (_, overlays) in self.graphicsOverlays { for (_, overlay) in overlays { graphicsOverlay.graphics.add(overlay) } } } private func iterateAndAdd(graphics: [String: AGSGraphic]) { for (_, overlay) in graphics { graphicsOverlay.graphics.add(overlay) } } // MARK:- viewWillAppear() override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) } // MARK:- viewDidLoad() override func viewDidLoad() { super.viewDidLoad() setupViewControllers() setupGraphicsOverlay() setupViews() placeSubviews() viewpointChangeHandler() setConstraints() } private func setupViewControllers() { setupSettingsVC() setupSceneVC() setupPickerSettingsVC() } private func setupSettingsVC() { settingsViewController = SettingsViewController() settingsViewController.mapViewController = self } private func setupSceneVC() { sceneViewController = SceneViewController() sceneViewController?.mapViewController = self } private func setupPickerSettingsVC() { basemapPickerViewController = BasemapPickerViewController() basemapPickerViewController.mapViewController = self } private func setupGraphicsOverlay() { graphicsOverlay.opacity = 0.55 mapView.graphicsOverlays.add(graphicsOverlay) } private func setupViews() { setupMapView() setupButtonsTargets() assignDelegates() } private func setupMapView() { view = mapView } private func setupButtonsTargets() { settingsButton.addTarget(self, action: #selector(moveToSettingsVC), for: .touchUpInside) basemapPickerButton.addTarget(self, action: #selector(presentBasemapPickerVC), for: .touchUpInside) compassButton.addTarget(self, action: #selector(setRotationAngelToDefault), for: .touchUpInside) plusScaleButton.addTarget(self, action: #selector(scaleMapViewUp), for: .touchUpInside) minusScaleButton.addTarget(self, action: #selector(scaleMapViewDown), for: .touchUpInside) } @objc private func moveToSettingsVC(_ sender: UIButton) { navigationController?.pushViewController(settingsViewController, animated: true) } @objc private func presentBasemapPickerVC() { let showCaseHeight = ShowcaseView().totalHeight * 10 let paddings = Measurements.getPadding() * 10 let buttonHeight = Measurements.getStandardButtonHeight() let offset = view.frame.height - showCaseHeight - paddings - buttonHeight let transitionDelegate = InteractiveTransitionDelegate(from: self, to: basemapPickerViewController, withOffset: offset) basemapPickerViewController.modalPresentationStyle = .custom basemapPickerViewController.transitioningDelegate = transitionDelegate present(basemapPickerViewController, animated: true) } @objc private func setRotationAngelToDefault() { compassButton.transform = CGAffineTransform(rotationAngle: 0) mapView.setViewpointRotation(0) } @objc private func scaleMapViewUp(_ sender: UIButton) { DispatchQueue.main.async { self.mapView.setViewpointScale(self.mapView.mapScale - 150000) } } @objc private func scaleMapViewDown(_ sender: UIButton) { DispatchQueue.main.async { self.mapView.setViewpointScale(self.mapView.mapScale + 150000) } } private func assignDelegates() { mapView.touchDelegate = self } private func placeSubviews() { view.addSubviews( settingsButton, minusScaleButton, plusScaleButton, compassButton, basemapPickerButton ) } private func viewpointChangeHandler() { self.mapView.viewpointChangedHandler = { [weak self] in DispatchQueue.main.async { self?.mapViewPointDidChange() } } } private func mapViewPointDidChange() { let rotationAngle = CGFloat(Double(-mapView.rotation) * Double.pi / 180) compassButton.transform = CGAffineTransform(rotationAngle: rotationAngle) } private func setConstraints() { let margins = view.layoutMarginsGuide NSLayoutConstraint.activate([ settingsButton.topAnchor.constraint(equalTo: margins.topAnchor, constant: 15), settingsButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor), minusScaleButton.heightAnchor.constraint(equalToConstant: Measurements.getStandardButtonHeight()), minusScaleButton.widthAnchor.constraint(equalToConstant: Measurements.getStandardButtonHeight()), minusScaleButton.trailingAnchor.constraint(equalTo: compassButton.leadingAnchor, constant: -Measurements.getPadding()), minusScaleButton.centerYAnchor.constraint(equalTo: compassButton.centerYAnchor), plusScaleButton.heightAnchor.constraint(equalToConstant: Measurements.getStandardButtonHeight()), plusScaleButton.widthAnchor.constraint(equalToConstant: Measurements.getStandardButtonHeight()), plusScaleButton.trailingAnchor.constraint(equalTo: minusScaleButton.leadingAnchor, constant: -Measurements.getPadding()), plusScaleButton.centerYAnchor.constraint(equalTo: compassButton.centerYAnchor), compassButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor), compassButton.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: Measurements.getPaddingFromBottomMargin()), compassButton.widthAnchor.constraint(equalToConstant: Measurements.getStandardButtonWidth()), compassButton.heightAnchor.constraint(equalToConstant: Measurements.getStandardButtonWidth()), basemapPickerButton.centerYAnchor.constraint(equalTo: settingsButton.centerYAnchor), basemapPickerButton.leadingAnchor.constraint(equalTo: margins.leadingAnchor), basemapPickerButton.heightAnchor.constraint(equalTo: settingsButton.heightAnchor), basemapPickerButton.widthAnchor.constraint(equalTo: settingsButton.widthAnchor) ]) } } // MARK:- Delegats extension MapViewController: AGSGeoViewTouchDelegate { func geoView(_ geoView: AGSGeoView, didDoubleTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint, completion: @escaping (Bool) -> Void) { showLocationCalloutFor(geoView: geoView, mapPoint: mapPoint) } private func showLocationCalloutFor(geoView: AGSGeoView, mapPoint: AGSPoint) { if geoView.callout.isHidden { geoView.showLocationCallout(at: mapPoint) } else { geoView.callout.dismiss() } } func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { let tolerance : Double = 20 showDistrictsInfoCallout(geoView, screenPoint: screenPoint, mapPoint: mapPoint, tolerance: tolerance) } private func showDistrictsInfoCallout(_ geoView: AGSGeoView, screenPoint: CGPoint, mapPoint: AGSPoint, tolerance: Double) { mapView.identify(graphicsOverlay, screenPoint: screenPoint, tolerance: tolerance, returnPopupsOnly: false) { (result: AGSIdentifyGraphicsOverlayResult) in if let districtsName = self.identifyGraphicsOverlay(result: result) { self.showCalloutFor(geoView: geoView, graphic: result.graphics[0], mapPoint: mapPoint, withTitle: districtsName) } } } private func identifyGraphicsOverlay(result: AGSIdentifyGraphicsOverlayResult) -> String? { if let _ = result.error { return nil } else { if !result.graphics.isEmpty { let graphic = result.graphics[0] if let districtsName = self.findDistrictsName(forGraphic: graphic) { return districtsName } } } return nil } private func findDistrictsName(forGraphic g: AGSGraphic) -> String? { if let districtsNames = graphicsOverlays[DISTRICTS_CENTERS_KEY] { for (name, graphic) in districtsNames { if graphic === g { return name } } } return nil } private func showCalloutFor(geoView: AGSGeoView, graphic: AGSGraphic, mapPoint: AGSPoint, withTitle title: String) { if geoView.callout.isHidden { let url = getURLForName(forName: title) geoView.showCallout(withTitle: title, withGraphics: graphic, at: mapPoint, withInfoButton: setupInfoButtonWithURL(url)) } else { geoView.callout.dismiss() } } private func getURLForName(forName name: String) -> URL? { let districtModel = settingsViewController.districtModel if let url = districtModel.getDistrictsWikiLinkBy(name: name) { return url } else { return nil } } private func setupInfoButtonWithURL(_ url: URL?) -> UIButton { let infoButton = UIButton() infoButton.tintColor = ColorPicker.getSubAccentColor() infoButton.setImage(setupInfoButtonImage(), for: .normal) infoButton.translatesAutoresizingMaskIntoConstraints = false initialSetupDetailWebVC(with: url) infoButton.addTarget(nil, action: #selector(showDetailWebVC), for: .touchUpInside) return infoButton } private func initialSetupDetailWebVC(with url: URL?) { if let url = url { setupDetailWebVC(with: url) } else { let defaultUrl = URL(string: "https://wikipedia.com")! setupDetailWebVC(with: defaultUrl) } } private func setupInfoButtonImage() -> UIImage { let imageConfig = UIImage.SymbolConfiguration(pointSize: 20, weight: .heavy) let image = UIImage(systemName: "info.circle.fill", withConfiguration: imageConfig) return image! } @objc private func showDetailWebVC(_ sender: UIButton) { navigationController?.pushViewController(detailWebViewController, animated: true) navigationController?.setNavigationBarHidden(false, animated: true) navigationController?.navigationBar.backgroundColor = ColorPicker.getMainColor() navigationController?.navigationBar.tintColor = ColorPicker.getSubAccentColor() navigationController?.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.close, target: self, action: nil) } private func setupDetailWebVC(with url: URL) { detailWebViewController = DetailWebViewController() detailWebViewController.urlToLoad = url } }
33.278195
183
0.766456
f9b94eede32614a1acdd73e4e46bfb5d76ce2afe
320
import Vapor import Crypto public protocol PasswordHasher: Service { func hash(_ plaintext: LosslessDataConvertible) throws -> String } extension BCryptDigest: PasswordHasher { public func hash(_ plaintext: LosslessDataConvertible) throws -> String { return try self.hash(plaintext, salt: nil) } }
24.615385
77
0.74375
081e4efcf0a2fe335029879b638af94bed611a2c
523
// // CharacterListRouter.swift // MountTracker // // Created by Christopher Matsumoto on 2/22/18. // Copyright © 2018 Christopher Matsumoto. All rights reserved. // import UIKit class CharacterListRouter: Router<LoginFlowModel> { override func present(from presenter: UIViewController, with injectables: LoginFlowModel) { let controller = CharacterListViewController(injectables, router: self) self.controller = controller presenter.navigationController?.pushViewController(controller, animated: true) } }
26.15
92
0.780115
204544f158021580f0a51aa78cba1df1557a1916
15,011
/* * Copyright 2020, gRPC 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. */ @testable import GRPC import EchoModel import NIO import NIOHTTP2 import XCTest class ChannelTransportTests: GRPCTestCase { typealias Request = Echo_EchoRequest typealias RequestPart = _GRPCClientRequestPart<Request> typealias Response = Echo_EchoResponse typealias ResponsePart = _GRPCClientResponsePart<Response> private func makeEmbeddedTransport( channel: EmbeddedChannel, container: ResponsePartContainer<Response>, deadline: NIODeadline = .distantFuture ) -> ChannelTransport<Request, Response> { let transport = ChannelTransport<Request, Response>( eventLoop: channel.eventLoop, responseContainer: container, timeLimit: .deadline(deadline), errorDelegate: nil, logger: self.logger ) { call, promise in channel.pipeline.addHandler(GRPCClientCallHandler(call: call)).whenComplete { result in switch result { case .success: promise.succeed(channel) case .failure(let error): promise.fail(error) } } } return transport } private func makeRequestHead() -> _GRPCRequestHead { return _GRPCRequestHead( method: "POST", scheme: "http", path: "/foo/bar", host: "localhost", deadline: .distantFuture, customMetadata: [:], encoding: .disabled ) } private func makeRequest(_ text: String) -> _MessageContext<Request> { return _MessageContext(Request.with { $0.text = text }, compressed: false) } private func makeResponse(_ text: String) -> _MessageContext<Response> { return _MessageContext(Response.with { $0.text = text }, compressed: false) } // MARK: - Happy path func testUnaryHappyPath() throws { let channel = EmbeddedChannel() let responsePromise = channel.eventLoop.makePromise(of: Response.self) let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop, unaryResponsePromise: responsePromise) let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Okay, let's send a unary request. transport.sendUnary(self.makeRequestHead(), request: .with { $0.text = "hello" }, compressed: false) // We haven't activated yet so the transport should buffer the message. XCTAssertNil(try channel.readOutbound(as: _GRPCClientRequestPart<Request>.self)) // Activate the channel. channel.pipeline.fireChannelActive() XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.requestHead) XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.message) XCTAssertTrue(try channel.readOutbound(as: RequestPart.self)?.isEnd ?? false) transport.receiveResponse(.initialMetadata([:])) transport.receiveResponse(.message(.init(.with { $0.text = "Hello!" }, compressed: false))) transport.receiveResponse(.trailingMetadata([:])) transport.receiveResponse(.status(.ok)) XCTAssertNoThrow(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertNoThrow(try responsePromise.futureResult.wait()) XCTAssertNoThrow(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) XCTAssertNoThrow(try transport.responseContainer.lazyStatusPromise.getFutureResult().wait()) } func testBidirectionalHappyPath() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Okay, send the request. We'll do it before activating. transport.sendRequests([ .head(self.makeRequestHead()), .message(self.makeRequest("1")), .message(self.makeRequest("2")), .message(self.makeRequest("3")), .end ], promise: nil) // We haven't activated yet so the transport should buffer the messages. XCTAssertNil(try channel.readOutbound(as: _GRPCClientRequestPart<Request>.self)) // Activate the channel. channel.pipeline.fireChannelActive() // Read the parts. XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.requestHead) XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.message) XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.message) XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.message) XCTAssertTrue(try channel.readOutbound(as: RequestPart.self)?.isEnd ?? false) // Write some responses. XCTAssertNoThrow(try channel.writeInbound(ResponsePart.initialMetadata([:]))) XCTAssertNoThrow(try channel.writeInbound(ResponsePart.trailingMetadata([:]))) XCTAssertNoThrow(try channel.writeInbound(ResponsePart.status(.ok))) // Check the responses. XCTAssertNoThrow(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertNoThrow(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) XCTAssertNoThrow(try transport.responseContainer.lazyStatusPromise.getFutureResult().wait()) } // MARK: - Timeout func testTimeoutBeforeActivating() throws { let deadline = NIODeadline.uptimeNanoseconds(0) + .minutes(42) let channel = EmbeddedChannel() let responsePromise = channel.eventLoop.makePromise(of: Response.self) let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop, unaryResponsePromise: responsePromise) let transport = self.makeEmbeddedTransport(channel: channel, container: container, deadline: deadline) // Advance time beyond the timeout. channel.embeddedEventLoop.advanceTime(by: .minutes(42)) XCTAssertThrowsError(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertThrowsError(try responsePromise.futureResult.wait()) XCTAssertThrowsError(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) XCTAssertEqual(try transport.responseContainer.lazyStatusPromise.getFutureResult().map { $0.code }.wait(), .deadlineExceeded) // Writing should fail. let sendPromise = channel.eventLoop.makePromise(of: Void.self) transport.sendRequest(.head(self.makeRequestHead()), promise: sendPromise) XCTAssertThrowsError(try sendPromise.futureResult.wait()) } func testTimeoutAfterActivating() throws { let deadline = NIODeadline.uptimeNanoseconds(0) + .minutes(42) let channel = EmbeddedChannel() let responsePromise = channel.eventLoop.makePromise(of: Response.self) let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop, unaryResponsePromise: responsePromise) let transport = self.makeEmbeddedTransport(channel: channel, container: container, deadline: deadline) // Activate the channel. channel.pipeline.fireChannelActive() // Advance time beyond the timeout. channel.embeddedEventLoop.advanceTime(by: .minutes(42)) XCTAssertThrowsError(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertThrowsError(try responsePromise.futureResult.wait()) XCTAssertThrowsError(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) XCTAssertEqual(try transport.responseContainer.lazyStatusPromise.getFutureResult().map { $0.code }.wait(), .deadlineExceeded) // Writing should fail. let sendPromise = channel.eventLoop.makePromise(of: Void.self) transport.sendRequest(.head(self.makeRequestHead()), promise: sendPromise) XCTAssertThrowsError(try sendPromise.futureResult.wait()) } func testTimeoutMidRPC() throws { let deadline = NIODeadline.uptimeNanoseconds(0) + .minutes(42) let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container, deadline: deadline) // Activate the channel. channel.pipeline.fireChannelActive() // Okay, send some requests. transport.sendRequests([ .head(self.makeRequestHead()), .message(self.makeRequest("1")) ], promise: nil) // Read the parts. XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.requestHead) XCTAssertNotNil(try channel.readOutbound(as: RequestPart.self)?.message) // We'll send back the initial metadata. XCTAssertNoThrow(try channel.writeInbound(ResponsePart.initialMetadata([:]))) XCTAssertNoThrow(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) // Advance time beyond the timeout. channel.embeddedEventLoop.advanceTime(by: .minutes(42)) // Check the remaining response parts. XCTAssertThrowsError(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) XCTAssertEqual(try transport.responseContainer.lazyStatusPromise.getFutureResult().map { $0.code }.wait(), .deadlineExceeded) } // MARK: - Channel errors func testChannelBecomesInactive() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Activate and deactivate the channel. channel.pipeline.fireChannelActive() channel.pipeline.fireChannelInactive() // Everything should fail. XCTAssertThrowsError(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertThrowsError(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) // Except the status, that will never fail. XCTAssertNoThrow(try transport.responseContainer.lazyStatusPromise.getFutureResult().wait()) } func testChannelError() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Activate the channel. channel.pipeline.fireChannelActive() // Fire an error. channel.pipeline.fireErrorCaught(GRPCStatus.processingError) // Everything should fail. XCTAssertThrowsError(try transport.responseContainer.lazyInitialMetadataPromise.getFutureResult().wait()) XCTAssertThrowsError(try transport.responseContainer.lazyTrailingMetadataPromise.getFutureResult().wait()) // Except the status, that will never fail. XCTAssertNoThrow(try transport.responseContainer.lazyStatusPromise.getFutureResult().wait()) } // MARK: - Test Transport after Shutdown func testOutboundMethodsAfterShutdown() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Close the channel. XCTAssertNoThrow(try channel.close().wait()) // Sending should fail. let sendRequestPromise = channel.eventLoop.makePromise(of: Void.self) transport.sendRequest(.head(self.makeRequestHead()), promise: sendRequestPromise) XCTAssertThrowsError(try sendRequestPromise.futureResult.wait()) { error in XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) } // Sending many should fail. let sendRequestsPromise = channel.eventLoop.makePromise(of: Void.self) transport.sendRequests([.end], promise: sendRequestsPromise) XCTAssertThrowsError(try sendRequestsPromise.futureResult.wait()) { error in XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) } // Cancelling should fail. let cancelPromise = channel.eventLoop.makePromise(of: Void.self) transport.cancel(promise: cancelPromise) XCTAssertThrowsError(try cancelPromise.futureResult.wait()) { error in XCTAssertEqual(error as? ChannelError, ChannelError.alreadyClosed) } let channelFuture = transport.streamChannel() XCTAssertThrowsError(try channelFuture.wait()) { error in XCTAssertEqual(error as? ChannelError, ChannelError.ioOnClosedChannel) } } func testInboundMethodsAfterShutdown() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) // Close the channel. XCTAssertNoThrow(try channel.close().wait()) // We'll fail the handler in the container if this one is received. transport.receiveResponse(.message(self.makeResponse("ignored!"))) transport.receiveError(GRPCStatus.processingError) } func testBufferedWritesAreFailedOnClose() throws { let channel = EmbeddedChannel() let container = ResponsePartContainer<Response>(eventLoop: channel.eventLoop) { (response: Response) in XCTFail("No response expected but got: \(response)") } let transport = self.makeEmbeddedTransport(channel: channel, container: container) let requestHeadPromise = channel.eventLoop.makePromise(of: Void.self) transport.sendRequest(.head(self.makeRequestHead()), promise: requestHeadPromise) // Close the channel. XCTAssertNoThrow(try channel.close().wait()) // Promise should fail. XCTAssertThrowsError(try requestHeadPromise.futureResult.wait()) } } extension _GRPCClientRequestPart { var requestHead: _GRPCRequestHead? { switch self { case .head(let head): return head case .message, .end: return nil } } var message: Request? { switch self { case .message(let message): return message.message case .head, .end: return nil } } var isEnd: Bool { switch self { case .end: return true case .head, .message: return false } } }
40.243968
129
0.742456
67ca99dffb0008abb30ab21d25015e729cc024f6
520
// // GithubSearch.swift // CocoaLibrary // // Created by tokijh on 2018. 3. 21.. // Copyright © 2018년 tokijh. All rights reserved. // import ObjectMapper class GithubSearch: Mappable { var totalCount: Int = 0 var incompleteResults: Bool = false var items: [Github] = [] required convenience init?(map: Map) { self.init() } func mapping(map: Map) { totalCount <- map["total_count"] incompleteResults <- map["incomplete_results"] items <- map["items"] } }
20.8
56
0.619231
11e8eee1f37a0a79359489df16931a66250bb4f8
225
// // Copyright © 2017 GirAppe Studio. All rights reserved. // import Foundation import CoreLocation public protocol Trackable { var trackedBy: TrackType { get } func matches(any identifier: Identifier) -> Bool }
17.307692
57
0.72
dd2535caa9462de56833a0ca65a469f6a18082c4
4,146
import ClockKit import SwiftUI extension CLKComplicationTemplate { enum CountdownGraphicRectangularStyle { case timer, stopwatch } static func graphicRectangular( _ countdown: Countdown, _ date: Date, _ style: CountdownGraphicRectangularStyle ) -> CLKComplicationTemplate { CLKComplicationTemplateGraphicRectangularFullView( VStack(alignment: .leading) { Group { Label { Text(countdown.label.nilIfEmpty ?? NSLocalizedString("Countdown", comment: "")) .font(.system(.title3, design: .rounded).weight(.bold).monospacedDigit()) // .font(.system(size: 18, weight: .bold, design: .rounded).monospacedDigit()) // .kerning(-0.1) .complicationForeground() } icon: { Image(decorative: "countdown") .font(.body.weight(.semibold)) .imageScale(.small) .padding(.leading, -2) // .padding(.horizontal, -2) .padding(.top, -2) } .foregroundColor(.accentColor) switch style { case .timer: Group { Text(CountdownFormatter.string(for: countdown, relativeTo: date)) .font(.system(size: 17.5, weight: .medium, design: .rounded).monospacedDigit()) Gauge(value: countdown.progress(relativeTo: date)) { Text("Time Remaining") } .tint(.orange) .gaugeStyle(.fill) .padding(.bottom, 10) } case .stopwatch: Text(CountdownFormatter.string(for: countdown, relativeTo: date)) .font(.system(size: 42.5, weight: .semibold, design: .rounded).monospacedDigit()) .padding(.horizontal, -1) .minimumScaleFactor(0.5) } } .frame(maxWidth: .infinity, alignment: .leading) .multilineTextAlignment(.leading) } ) } } struct GraphicRectangular_Previews: PreviewProvider { static var previews: some View { ForEach(previewDevices) { device in Group { CLKComplicationTemplate.graphicRectangular(.complicationPreview, previewDate, .timer).previewContext() CLKComplicationTemplate.graphicRectangular(.complicationPreview, previewDate, .stopwatch).previewContext() } .previewDevice(device) .previewLayout(.sizeThatFits) } } } // case .graphicRectangular: // return .init(date: date, complicationTemplate: CLKComplicationTemplateGraphicRectangularTextGaugeView( // headerLabel: Label { // Text("ddddddd") //// Text(countdown.label.nilIfEmpty ?? NSLocalizedString("Countdown", comment: "")) //// .monospacedDigit() //// .fontWeight(.semibold) //// .foregroundColor(.accentColor) // .complicationForeground() // } icon: { // Image(decorative: "countdown") // .font(.body.weight(.semibold)) // .imageScale(.small) // .symbolRenderingMode(.multicolor) // } // .foregroundColor(.accentColor), // headerTextProvider: CLKSimpleTextProvider(text: countdown.label.nilIfEmpty ?? NSLocalizedString("Countdown", comment: "")), // bodyTextProvider: CLKSimpleTextProvider(text: CountdownFormatter.string(for: countdown, relativeTo: date)), // gaugeProvider: CLKSimpleGaugeProvider( // style: .fill, // gaugeColor: .orange, // fillFraction: 1 - Float(countdown.progress(relativeTo: date)) // ) // )) // return .init(date: date, complicationTemplate: CLKComplicationTemplateGraphicExtraLargeCircularClosedGaugeText( // gaugeProvider: CLKSimpleGaugeProvider( // style: .fill, // gaugeColor: .orange, // fillFraction: 1 - Float(countdown.progress(relativeTo: date)) // ), // centerTextProvider: CLKSimpleTextProvider(text: NumberFormatter.localizedString( // from: countdown.progress(relativeTo: date) * 100 as NSNumber, // number: .none // )) // ))
38.747664
133
0.600096
507da7ba6f3807276f7c5631681f801092efaa86
1,072
/* Copyright (c) 2012-2016 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. */ // // BaseTest.swift // Antlr4 // // Created by janyou on 15/10/13. // import XCTest @testable import Antlr4 class BaseTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.146341
111
0.650187
46f55c710a6e2ecb8dac567abe0a3fc07634a8c1
29,881
// // UserInteractionFunctions.swift // Pods // // Created by JayT on 2016-05-12. // // extension JTAppleCalendarView { /// Returns the cellStatus of a date that is visible on the screen. /// If the row and column for the date cannot be found, /// then nil is returned /// - Paramater row: Int row of the date to find /// - Paramater column: Int column of the date to find /// - returns: /// - CellState: The state of the found cell public func cellStatusForDate(at row: Int, column: Int) -> CellState? { guard let section = currentSection() else { return nil } let convertedRow = (row * maxNumberOfDaysInWeek) + column let indexPathToFind = IndexPath(item: convertedRow, section: section) if let date = dateOwnerInfoFromPath(indexPathToFind) { let stateOfCell = cellStateFromIndexPath(indexPathToFind, withDateInfo: date) return stateOfCell } return nil } /// Returns the cell status for a given date /// - Parameter: date Date of the cell you want to find /// - returns: /// - CellState: The state of the found cell public func cellStatus(for date: Date) -> CellState? { // validate the path let paths = pathsFromDates([date]) // Jt101 change this function to also return // information like the dateInfoFromPath function if paths.count < 1 { return nil } let cell = calendarView.cellForItem(at: paths[0]) as? JTAppleDayCell let stateOfCell = cellStateFromIndexPath(paths[0], cell: cell) return stateOfCell } /// Returns the cell status for a given point /// - Parameter: point of the cell you want to find /// - returns: /// - CellState: The state of the found cell public func cellStatus(at point: CGPoint) -> CellState? { if let indexPath = calendarView.indexPathForItem(at: point) { return cellStateFromIndexPath(indexPath) } return nil } /// Deselect all selected dates public func deselectAllDates(triggerSelectionDelegate: Bool = true) { selectDates(selectedDates, triggerSelectionDelegate: triggerSelectionDelegate) } /// Generates a range of dates from from a startDate to an /// endDate you provide /// Parameter startDate: Start date to generate dates from /// Parameter endDate: End date to generate dates to /// returns: /// - An array of the successfully generated dates public func generateDateRange(from startDate: Date, to endDate: Date) -> [Date] { if startDate > endDate { return [] } var returnDates: [Date] = [] var currentDate = startDate repeat { returnDates.append(currentDate) currentDate = calendar.startOfDay(for: calendar.date( byAdding: .day, value: 1, to: currentDate)!) } while currentDate <= endDate return returnDates } /// Let's the calendar know which cell xib to /// use for the displaying of it's date-cells. /// - Parameter name: The name of the xib of your cell design /// - Parameter bundle: The bundle where the xib can be found. /// If left nil, the library will search the /// main bundle public func registerCellViewXib(file name: String, bundle: Bundle? = nil) { cellViewSource = JTAppleCalendarViewSource.fromXib(name, bundle) } /// Let's the calendar know which cell class to use /// for the displaying of it's date-cells. /// - Parameter name: The class name of your cell design /// - Parameter bundle: The bundle where the xib can be found. /// If left nil, the library will search the /// main bundle public func registerCellViewClass(file name: String, bundle: Bundle? = nil) { cellViewSource = JTAppleCalendarViewSource.fromClassName(name, bundle) } /// Let's the calendar know which cell /// class to use for the displaying of it's date-cells. /// - Parameter type: The type of your cell design public func registerCellViewClass(type: AnyClass) { cellViewSource = JTAppleCalendarViewSource.fromType(type) } /// Register header views with the calender. This needs to be done /// before the view can be displayed /// - Parameter xibFileNames: An array of xib file string names /// - Parameter bundle: The bundle where the xibs can be found. /// If left nil, the library will search the /// main bundle public func registerHeaderView(xibFileNames: [String], bundle: Bundle? = nil) { if xibFileNames.count < 1 { return } unregisterHeaders() for headerViewXibName in xibFileNames { registeredHeaderViews.append(JTAppleCalendarViewSource.fromXib(headerViewXibName, bundle)) self.calendarView.register(JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewXibName) } } /// Register header views with the calender. This needs to be /// done before header views can be displayed /// - Parameter classStringNames: An array of class string names /// - Parameter bundle: The bundle where the xibs can be found. If left /// nil, the library will search the main bundle public func registerHeaderView(classStringNames: [String], bundle: Bundle? = nil) { if classStringNames.count < 1 { return } unregisterHeaders() for headerViewClassName in classStringNames { registeredHeaderViews.append(JTAppleCalendarViewSource .fromClassName(headerViewClassName, bundle)) self.calendarView.register( JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerViewClassName ) } } /// Register header views with the calender. This needs to be done /// before header views can be displayed /// - Parameter classTypeNames: An array of class types public func registerHeaderView(classTypeNames: [AnyClass]) { if classTypeNames.count < 1 { return } unregisterHeaders() for aClass in classTypeNames { registeredHeaderViews .append(JTAppleCalendarViewSource.fromType(aClass)) self.calendarView.register( JTAppleCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: aClass.description() ) } } /// Reloads the data on the calendar view. Scroll delegates are not // triggered with this function. /// - Parameter date: An anchordate that the calendar will /// scroll to after reload completes /// - Parameter animation: Scroll is animated if this is set to true /// - Parameter completionHandler: This closure will run after /// the reload is complete public func reloadData(withAnchor date: Date? = nil, animation: Bool = false, completionHandler: (() -> Void)? = nil) { if !calendarIsAlreadyLoaded { if let validCompletionHandler = completionHandler { delayedExecutionClosure.append(validCompletionHandler) } return } reloadData(checkDelegateDataSource: true, withAnchorDate: date, withAnimation: animation, completionHandler: completionHandler) } /// Reload the date of specified date-cells on the calendar-view /// - Parameter dates: Date-cells with these specified /// dates will be reloaded public func reloadDates(_ dates: [Date]) { var paths = [IndexPath]() for date in dates { let aPath = pathsFromDates([date]) if aPath.count > 0 && !paths.contains(aPath[0]) { paths.append(aPath[0]) let cellState = cellStateFromIndexPath(aPath[0]) if let validCounterPartCell = indexPathOfdateCellCounterPart( date, indexPath: aPath[0], dateOwner: cellState.dateBelongsTo) { paths.append(validCounterPartCell) } } } batchReloadIndexPaths(paths) } /// Select a date-cell range /// - Parameter startDate: Date to start the selection from /// - Parameter endDate: Date to end the selection from /// - Parameter triggerDidSelectDelegate: Triggers the delegate /// function only if the value is set to true. /// Sometimes it is necessary to setup some dates without triggereing /// the delegate e.g. For instance, when youre initally setting up data /// in your viewDidLoad /// - Parameter keepSelectionIfMultiSelectionAllowed: This is only /// applicable in allowedMultiSelection = true. /// This overrides the default toggle behavior of selection. /// If true, selected cells will remain selected. public func selectDates(from startDate: Date, to endDate: Date, triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) { selectDates(generateDateRange(from: startDate, to: endDate), triggerSelectionDelegate: triggerSelectionDelegate, keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed) } /// Select a date-cells /// - Parameter date: The date-cell with this date will be selected /// - Parameter triggerDidSelectDelegate: Triggers the delegate function /// only if the value is set to true. /// Sometimes it is necessary to setup some dates without triggereing /// the delegate e.g. For instance, when youre initally setting up data /// in your viewDidLoad public func selectDates(_ dates: [Date], triggerSelectionDelegate: Bool = true, keepSelectionIfMultiSelectionAllowed: Bool = false) { if !calendarIsAlreadyLoaded { // If the calendar is not yet fully loaded. // Add the task to the delayed queue delayedExecutionClosure.append { self.selectDates( dates, triggerSelectionDelegate: triggerSelectionDelegate, keepSelectionIfMultiSelectionAllowed: keepSelectionIfMultiSelectionAllowed ) } return } var allIndexPathsToReload: [IndexPath] = [] var validDatesToSelect = dates // If user is trying to select multiple dates with // multiselection disabled, then only select the last object if !calendarView.allowsMultipleSelection, let dateToSelect = dates.last { validDatesToSelect = [dateToSelect] } let addToIndexSetToReload = { (indexPath: IndexPath) -> Void in if !allIndexPathsToReload.contains(indexPath) { allIndexPathsToReload.append(indexPath) } // To avoid adding the same indexPath twice. } let selectTheDate = { (indexPath: IndexPath, date: Date) -> Void in self.calendarView.selectItem(at: indexPath, animated: false, scrollPosition: []) addToIndexSetToReload(indexPath) // If triggereing is enabled, then let their delegate // handle the reloading of view, else we will reload the data if triggerSelectionDelegate { self.internalCollectionView(self.calendarView, didSelectItemAtIndexPath: indexPath) } else { // Although we do not want the delegate triggered, we // still want counterpart cells to be selected // Because there is no triggering of the delegate, the cell // will not be added to selection and it will not be // reloaded. We need to do this here self.addCellToSelectedSetIfUnselected(indexPath, date: date) let cellState = self.cellStateFromIndexPath(indexPath) // , withDateInfo: date) if let aSelectedCounterPartIndexPath = self.selectCounterPartCellIndexPathIfExists(indexPath, date: date, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then // it will also need to be reloaded addToIndexSetToReload(aSelectedCounterPartIndexPath) } } } let deSelectTheDate = { (oldIndexPath: IndexPath) -> Void in addToIndexSetToReload(oldIndexPath) if let index = self.theSelectedIndexPaths .index(of: oldIndexPath) { let oldDate = self.theSelectedDates[index] self.calendarView.deselectItem(at: oldIndexPath, animated: false) self.theSelectedIndexPaths.remove(at: index) self.theSelectedDates.remove(at: index) // If delegate triggering is enabled, let the // delegate function handle the cell if triggerSelectionDelegate { self.internalCollectionView(self.calendarView, didDeselectItemAtIndexPath: oldIndexPath) } else { // Although we do not want the delegate triggered, // we still want counterpart cells to be deselected let cellState = self.cellStateFromIndexPath(oldIndexPath) // , withDateInfo: oldDate) if let anUnselectedCounterPartIndexPath = self.deselectCounterPartCellIndexPath(oldIndexPath, date: oldDate, dateOwner: cellState.dateBelongsTo) { // If there was a counterpart cell then // it will also need to be reloaded addToIndexSetToReload(anUnselectedCounterPartIndexPath) } } } } for date in validDatesToSelect { let components = calendar.dateComponents([.year, .month, .day], from: date) let firstDayOfDate = calendar.date(from: components)! // If the date is not within valid boundaries, then exit if !(firstDayOfDate >= startOfMonthCache! && firstDayOfDate <= endOfMonthCache!) { continue } let pathFromDates = self.pathsFromDates([date]) // If the date path youre searching for, doesnt exist, return if pathFromDates.count < 0 { continue } let sectionIndexPath = pathFromDates[0] // Remove old selections if self.calendarView.allowsMultipleSelection == false { // If single selection is ON let selectedIndexPaths = self.theSelectedIndexPaths // made a copy because the array is about to be mutated for indexPath in selectedIndexPaths { if indexPath != sectionIndexPath { deSelectTheDate(indexPath) } } // Add new selections // Must be added here. If added in delegate // didSelectItemAtIndexPath selectTheDate(sectionIndexPath, date) } else { // If multiple selection is on. Multiple selection behaves // differently to singleselection. // It behaves like a toggle. unless // keepSelectionIfMultiSelectionAllowed is true. // If user wants to force selection if multiselection // is enabled, then removed the selected dates from // generated dates if keepSelectionIfMultiSelectionAllowed { if selectedDates.contains( calendar.startOfDay(for: date)) { addToIndexSetToReload(sectionIndexPath) continue // Do not deselect or select the cell. // Just add it to be reloaded } } if self.theSelectedIndexPaths.contains(sectionIndexPath) { // If this cell is already selected, then deselect it deSelectTheDate(sectionIndexPath) } else { // Add new selections // Must be added here. If added in delegate // didSelectItemAtIndexPath selectTheDate(sectionIndexPath, date) } } } // If triggering was false, although the selectDelegates weren't // called, we do want the cell refreshed. // Reload to call itemAtIndexPath if triggerSelectionDelegate == false && allIndexPathsToReload.count > 0 { delayRunOnMainThread(0.0) { self.batchReloadIndexPaths(allIndexPathsToReload) } } } /// Scrolls the calendar view to the next section view. It will execute a completion handler at the end of scroll animation if provided. /// - Paramater direction: Indicates a direction to scroll /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Parameter triggerScrollToDateDelegate: trigger delegate if set to true /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToSegment(_ destination: SegmentDestination, triggerScrollToDateDelegate: Bool = true, animateScroll: Bool = true, completionHandler: (() -> Void)? = nil) { if !calendarIsAlreadyLoaded { delayedExecutionClosure.append { self.scrollToSegment(destination, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, completionHandler: completionHandler) } } var xOffset: CGFloat = 0 var yOffset: CGFloat = 0 let fixedScrollSize: CGFloat if direction == .horizontal { if thereAreHeaders || cachedConfiguration.generateOutDates == .tillEndOfGrid { fixedScrollSize = calendarViewLayout.sizeOfContentForSection(0) } else { fixedScrollSize = calendarView.frame.width } xOffset = calendarView.contentOffset.x let section = CGFloat(Int(xOffset / fixedScrollSize)) xOffset = (fixedScrollSize * section) switch destination { case .next: xOffset += fixedScrollSize case .previous: xOffset -= fixedScrollSize case .end: xOffset = calendarView.contentSize.width - calendarView.frame.width case .start: xOffset = 0 } } else { if thereAreHeaders { guard let section = currentSection() else { return } if (destination == .next && section + 1 >= numberOfSections(in: calendarView)) || destination == .previous && section - 1 < 0 || numberOfSections(in: calendarView) < 0 { return } switch destination { case .next: scrollToHeaderInSection(section + 1) case .previous: scrollToHeaderInSection(section - 1) case .start: scrollToHeaderInSection(0) case .end: scrollToHeaderInSection(numberOfSections(in: calendarView) - 1) } return } else { yOffset = calendarView.contentOffset.y fixedScrollSize = calendarView.frame.height let section = CGFloat(Int(yOffset / fixedScrollSize)) yOffset = (fixedScrollSize * section) + fixedScrollSize } } let rect = CGRect(x: xOffset, y: yOffset, width: calendarView.frame.width, height: calendarView.frame.height) scrollTo(rect: rect, triggerScrollToDateDelegate: triggerScrollToDateDelegate, isAnimationEnabled: true, completionHandler: completionHandler) } /// Scrolls the calendar view to the start of a section view containing a specified date. /// - Paramater date: The calendar view will scroll to a date-cell containing this date if it exists /// - Parameter triggerScrollToDateDelegate: Trigger delegate if set to true /// - Paramater animateScroll: Bool indicating if animation should be enabled /// - Paramater preferredScrollPositionIndex: Integer indicating the end scroll position on the screen. /// This value indicates column number for Horizontal scrolling and row number for a vertical scrolling calendar /// - Parameter completionHandler: A completion handler that will be executed at the end of the scroll animation public func scrollToDate(_ date: Date, triggerScrollToDateDelegate: Bool = true, animateScroll: Bool = true, preferredScrollPosition: UICollectionViewScrollPosition? = nil, completionHandler: (() -> Void)? = nil) { if !calendarIsAlreadyLoaded { delayedExecutionClosure.append { self.scrollToDate(date, triggerScrollToDateDelegate: triggerScrollToDateDelegate, animateScroll: animateScroll, preferredScrollPosition: preferredScrollPosition, completionHandler: completionHandler) } return } self.triggerScrollToDateDelegate = triggerScrollToDateDelegate let components = calendar.dateComponents([.year, .month, .day], from: date) let firstDayOfDate = calendar.date(from: components)! func handleScroll(indexPath: IndexPath? = nil, rect: CGRect? = nil, triggerScrollToDateDelegate: Bool = true, isAnimationEnabled: Bool, position: UICollectionViewScrollPosition? = .left, completionHandler: (() -> Void)?) { if scrollInProgress { return } // Rect takes preference if let validRect = rect { scrollInProgress = true scrollTo(rect: validRect, isAnimationEnabled: isAnimationEnabled, completionHandler: completionHandler) } else { guard let validIndexPath = indexPath else { return } if thereAreHeaders && direction == .vertical { scrollToHeaderInSection(validIndexPath.section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: isAnimationEnabled, completionHandler: completionHandler) return } else { let validPosition = position ?? .left scrollInProgress = true self.scrollTo(indexPath: validIndexPath, isAnimationEnabled: isAnimationEnabled, position: validPosition, completionHandler: completionHandler) } } // Jt101 put this into a function to reduce code between // this and the scroll to header function delayRunOnMainThread(0.0, closure: { if !isAnimationEnabled { self.scrollViewDidEndScrollingAnimation(self.calendarView) } self.scrollInProgress = false }) } delayRunOnMainThread(0.0, closure: { // This part should be inside the mainRunLoop if !((firstDayOfDate >= self.startOfMonthCache!) && (firstDayOfDate <= self.endOfMonthCache!)) { return } let retrievedPathsFromDates = self.pathsFromDates([date]) guard retrievedPathsFromDates.count > 0 else { return } let sectionIndexPath = self.pathsFromDates([date])[0] var position: UICollectionViewScrollPosition = self.direction == .horizontal ? .left : .top if !self.scrollingMode.pagingIsEnabled() { if let validPosition = preferredScrollPosition { if self.direction == .horizontal { if validPosition == .left || validPosition == .right || validPosition == .centeredHorizontally { position = validPosition } } else { if validPosition == .top || validPosition == .bottom || validPosition == .centeredVertically { position = validPosition } } } } var rect: CGRect? switch self.scrollingMode { case .stopAtEach, .stopAtEachSection, .stopAtEachCalendarFrameWidth: if self.direction == .horizontal || (self.direction == .vertical && !self.thereAreHeaders) { rect = self.targetRectForItemAt(indexPath: sectionIndexPath) } default: break } handleScroll(indexPath: sectionIndexPath, rect: rect, triggerScrollToDateDelegate: triggerScrollToDateDelegate, isAnimationEnabled: animateScroll, position: position, completionHandler: completionHandler) }) } func scrollTo(rect: CGRect, triggerScrollToDateDelegate: Bool? = nil, isAnimationEnabled: Bool, completionHandler: (() -> Void)?) { if let validCompletionHandler = completionHandler { self.delayedExecutionClosure.append(validCompletionHandler) } self.triggerScrollToDateDelegate = triggerScrollToDateDelegate calendarView.scrollRectToVisible(rect, animated: isAnimationEnabled) scrollInProgress = false } /// Scrolls the calendar view to the start of a section view header. /// If the calendar has no headers registered, then this function does nothing /// - Paramater date: The calendar view will scroll to the header of /// a this provided date public func scrollToHeaderForDate(_ date: Date, triggerScrollToDateDelegate: Bool = false, withAnimation animation: Bool = false, completionHandler: (() -> Void)? = nil) { let path = pathsFromDates([date]) // Return if date was incalid and no path was returned if path.count < 1 { return } scrollToHeaderInSection( path[0].section, triggerScrollToDateDelegate: triggerScrollToDateDelegate, withAnimation: animation, completionHandler: completionHandler ) } /// Unregister previously registered headers public func unregisterHeaders() { registeredHeaderViews.removeAll() // remove the already registered xib // files if the user re-registers again. layoutNeedsUpdating = true } /// Returns the visible dates of the calendar. /// - returns: /// - DateSegmentInfo public func visibleDates()-> DateSegmentInfo { let emptySegment = DateSegmentInfo(indates: [], monthDates: [], outdates: [], indateIndexes: [], monthDateIndexes: [], outdateIndexes: []) if !calendarIsAlreadyLoaded { return emptySegment } let cellAttributes = visibleElements() let indexPaths: [IndexPath] = cellAttributes.map { $0.indexPath }.sorted() return dateSegmentInfoFrom(visible: indexPaths) } /// Returns the visible dates of the calendar. /// - returns: /// - DateSegmentInfo public func visibleDates(_ completionHandler: @escaping (_ dateSegmentInfo: DateSegmentInfo) ->()) { if !calendarIsAlreadyLoaded { delayedExecutionClosure.append { self.visibleDates(completionHandler) } return } let retval = visibleDates() completionHandler(retval) } }
46.762128
178
0.582644
f93b33ae090722ef4649c9c01aae77a38ca29d77
3,308
/** * Problem Link: https://leetcode.com/problems/median-of-two-sorted-arrays/ * * findKthSmallest between two sorted arrays. * * For this problem, we are trying to find the median of the */ class Solution { func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let sum = nums1.count + nums2.count if sum % 2 != 0 { return Double(findKthSmallest(sum / 2, between: nums1, and: nums2)) } else { return Double(findKthSmallest(sum / 2, between: nums1, and: nums2) + findKthSmallest(sum / 2 - 1, between: nums1, and: nums2)) / 2.0 } } private func findKthSmallest(_ k: Int, between nums1: [Int], and nums2: [Int]) -> Int { if nums1.count == 0 { return nums2[k] } if nums2.count == 0 { return nums1[k] } if k == 0 { return min(nums1.first!, nums2.first!) } let mid1 = nums1.count * k / (nums1.count + nums2.count) let mid2 = k - mid1 - 1 if nums1[mid1] > nums2[mid2] { return findKthSmallest(k - mid2 - 1, between: Array(nums1.dropLast(nums1.count - mid1 - 1)), and: Array(nums2.dropFirst(mid2 + 1))) } else { return findKthSmallest(k - mid1 - 1, between: Array(nums1.dropFirst(mid1 + 1)), and: Array(nums2.dropLast(nums2.count - mid2 - 1))) } } } /** * https://leetcode.com/problems/median-of-two-sorted-arrays/ * * */ // Date: Sat Apr 25 12:06:55 PDT 2020 /// Found this great video and it explained everything /// https://www.youtube.com/watch?v=KB9IcSCDQ9k class Solution { func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let len1 = nums1.count let len2 = nums2.count if len1 > len2 { return findMedianSortedArrays(nums2, nums1) } let halfLen = (len1 + len2 + 1) / 2 // take the upper bound var minLen = 0 var maxLen = len1 while minLen <= maxLen { let leftLen1 = minLen + (maxLen - minLen) / 2 let leftLen2 = halfLen - leftLen1 if leftLen1 < maxLen, nums1[leftLen1] < nums2[leftLen2 - 1] { minLen = leftLen1 + 1 } else if leftLen1 > 0, nums1[leftLen1 - 1] > nums2[leftLen2] { maxLen = leftLen1 - 1 } else { // Found the right length in nums1 for left part. var maxLeft = 0 if leftLen1 == 0 { maxLeft = nums2[leftLen2 - 1] } else if leftLen2 == 0 { maxLeft = nums1[leftLen1 - 1] } else { maxLeft = max(nums2[leftLen2 - 1], nums1[leftLen1 - 1]) } if (len1 + len2) % 2 == 1 { return Double(maxLeft) } var minRight = 0 if leftLen1 == len1 { minRight = nums2[leftLen2] } else if leftLen2 == len2 { minRight = nums1[leftLen1] } else { minRight = min(nums1[leftLen1], nums2[leftLen2]) } return Double(maxLeft + minRight) / 2.0 } } return 0 } }
35.191489
144
0.51058
6a4d998034862bbc610ebe84141db76ba7594bf6
869
// // EventViewDataModel.swift // EliteSISSwift // // Created by Daffolap-51 on 19/04/18. // Copyright © 2018 Kunal Das. All rights reserved. // import Foundation struct EventViewDataModel{ var name: String! var color: UIColor! func getDummyData()->[EventViewDataModel]{ var data: [EventViewDataModel] = [] data.append(EventViewDataModel(name: "PTM", color: UIColor(red: 255/255.0, green: 221/255.0, blue: 75/255.0, alpha: 1.0))) data.append(EventViewDataModel(name: "Awards/Seminar", color: UIColor(red: 3/255.0, green: 147/255.0, blue: 247/255.0, alpha: 1.0))) data.append(EventViewDataModel(name: "Student Wellness Fair", color: UIColor(red: 61/255.0, green: 216/255.0, blue: 141/255.0, alpha: 1.0))) data.append(EventViewDataModel(name: "Exams", color: UIColor.darkGray)) return data } }
33.423077
148
0.665132
91541fd7a64f41f290c9567c8d47be792c9cd2a5
9,427
import Foundation import UIKit import Firebase class Message { //MARK: Properties var owner: MessageOwner var type: MessageType var content: Any var timestamp: Int var isRead: Bool var image: UIImage? private var toID: String? private var fromID: String? //MARK: Methods class func downloadAllMessages(forUserID: String, completion: @escaping (Message) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(forUserID).observe(.value, with: { (snapshot) in if snapshot.exists() { let data = snapshot.value as! [String: String] let location = data["location"]! FIRDatabase.database().reference().child("conversations").child(location).observe(.childAdded, with: { (snap) in if snap.exists() { let receivedMessage = snap.value as! [String: Any] let messageType = receivedMessage["type"] as! String var type = MessageType.text switch messageType { case "photo": type = .photo case "location": type = .location default: break } let content = receivedMessage["content"] as! String let fromID = receivedMessage["fromID"] as! String let timestamp = receivedMessage["timestamp"] as! Int if fromID == currentUserID { let message = Message.init(type: type, content: content, owner: .receiver, timestamp: timestamp, isRead: true) completion(message) } else { let message = Message.init(type: type, content: content, owner: .sender, timestamp: timestamp, isRead: true) completion(message) } } }) } }) } } func downloadImage(indexpathRow: Int, completion: @escaping (Bool, Int) -> Swift.Void) { if self.type == .photo { let imageLink = self.content as! String let imageURL = URL.init(string: imageLink) URLSession.shared.dataTask(with: imageURL!, completionHandler: { (data, response, error) in if error == nil { self.image = UIImage.init(data: data!) completion(true, indexpathRow) } }).resume() } } class func markMessagesRead(forUserID: String) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(forUserID).observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.exists() { let data = snapshot.value as! [String: String] let location = data["location"]! FIRDatabase.database().reference().child("conversations").child(location).observeSingleEvent(of: .value, with: { (snap) in if snap.exists() { for item in snap.children { let receivedMessage = (item as! FIRDataSnapshot).value as! [String: Any] let fromID = receivedMessage["fromID"] as! String if fromID != currentUserID { FIRDatabase.database().reference().child("conversations").child(location).child((item as! FIRDataSnapshot).key).child("isRead").setValue(true) } } } }) } }) } } func downloadLastMessage(forLocation: String, completion: @escaping (Void) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("conversations").child(forLocation).observe(.value, with: { (snapshot) in if snapshot.exists() { for snap in snapshot.children { let receivedMessage = (snap as! FIRDataSnapshot).value as! [String: Any] self.content = receivedMessage["content"]! self.timestamp = receivedMessage["timestamp"] as! Int let messageType = receivedMessage["type"] as! String let fromID = receivedMessage["fromID"] as! String self.isRead = receivedMessage["isRead"] as! Bool var type = MessageType.text switch messageType { case "text": type = .text case "photo": type = .photo case "location": type = .location default: break } self.type = type if currentUserID == fromID { self.owner = .receiver } else { self.owner = .sender } completion() } } }) } } class func send(message: Message, toID: String, completion: @escaping (Bool) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { switch message.type { case .location: let values = ["type": "location", "content": message.content, "fromID": currentUserID, "toID": toID, "timestamp": message.timestamp, "isRead": false] Message.uploadMessage(withValues: values, toID: toID, completion: { (status) in completion(status) }) case .photo: let imageData = UIImageJPEGRepresentation((message.content as! UIImage), 0.5) let child = UUID().uuidString FIRStorage.storage().reference().child("messagePics").child(child).put(imageData!, metadata: nil, completion: { (metadata, error) in if error == nil { let path = metadata?.downloadURL()?.absoluteString let values = ["type": "photo", "content": path!, "fromID": currentUserID, "toID": toID, "timestamp": message.timestamp, "isRead": false] as [String : Any] Message.uploadMessage(withValues: values, toID: toID, completion: { (status) in completion(status) }) } }) case .text: let values = ["type": "text", "content": message.content, "fromID": currentUserID, "toID": toID, "timestamp": message.timestamp, "isRead": false] Message.uploadMessage(withValues: values, toID: toID, completion: { (status) in completion(status) }) } } } class func uploadMessage(withValues: [String: Any], toID: String, completion: @escaping (Bool) -> Swift.Void) { if let currentUserID = FIRAuth.auth()?.currentUser?.uid { FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(toID).observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.exists() { let data = snapshot.value as! [String: String] let location = data["location"]! FIRDatabase.database().reference().child("conversations").child(location).childByAutoId().setValue(withValues, withCompletionBlock: { (error, _) in if error == nil { completion(true) } else { completion(false) } }) } else { FIRDatabase.database().reference().child("conversations").childByAutoId().childByAutoId().setValue(withValues, withCompletionBlock: { (error, reference) in let data = ["location": reference.parent!.key] FIRDatabase.database().reference().child("users").child(currentUserID).child("conversations").child(toID).updateChildValues(data) FIRDatabase.database().reference().child("users").child(toID).child("conversations").child(currentUserID).updateChildValues(data) completion(true) }) } }) } } //MARK: Inits init(type: MessageType, content: Any, owner: MessageOwner, timestamp: Int, isRead: Bool) { self.type = type self.content = content self.owner = owner self.timestamp = timestamp self.isRead = isRead } }
50.682796
178
0.497613
b9d46f78374db128261fd1e7885a3f1aa88e85ea
284
import AppKit import Foundation public protocol SpeculidSpecificationsFileProtocol { var assetDirectoryRelativePath: String { get } var sourceImageRelativePath: String { get } var geometry: Geometry? { get } var background: NSColor? { get } var removeAlpha: Bool { get } }
25.818182
52
0.757042
3a4a245e5b9d7bd01a66c6d801bc613834b5323c
6,188
import XCTest @testable import SQLCodable class SQLTableDecoderTests: XCTestCase { struct Strings: SQLCodable { let string: String let ostring: String? } func testStrings() { XCTAssertEqual(try SQLTable(for: Strings.self), SQLTable( columns: [ "string": SQLColumn(type: .text, null: false), "ostring": SQLColumn(type: .text, null: true), ], name: "Strings" )) } struct Floats: SQLCodable { let float: Float let double: Double let ofloat: Float? let odouble: Double? let date: Date let odate: Date? } func testFloats() { XCTAssertEqual(try SQLTable(for: Floats.self), SQLTable( columns: [ "float": SQLColumn(type: .real, null: false), "double": SQLColumn(type: .real, null: false), "ofloat": SQLColumn(type: .real, null: true), "odouble": SQLColumn(type: .real, null: true), "date": SQLColumn(type: .real, null: false), "odate": SQLColumn(type: .real, null: true), ], name: "Floats" )) } struct Bools: SQLCodable { let bool: Bool let optional: Bool? } func testBools() { XCTAssertEqual(try SQLTable(for: Bools.self), SQLTable( columns: [ "bool": SQLColumn(type: .int, null: false), "optional": SQLColumn(type: .int, null: true), ], name: "Bools" )) } struct Integers: SQLCodable { let i: Int let i8: Int8 let i16: Int16 let i32: Int32 let i64: Int64 let u: UInt let u8: UInt8 let u16: UInt16 let u32: UInt32 let u64: UInt64 let oi: Int? let oi8: Int8? let oi16: Int16? let oi32: Int32? let oi64: Int64? let ou: UInt? let ou8: UInt8? let ou16: UInt16? let ou32: UInt32? let ou64: UInt64? } func testIntegers() { XCTAssertEqual(try SQLTable(for: Integers.self), SQLTable( columns: [ "i": SQLColumn(type: .int, null: false), "i8": SQLColumn(type: .int, null: false), "i16": SQLColumn(type: .int, null: false), "i32": SQLColumn(type: .int, null: false), "i64": SQLColumn(type: .int, null: false), "u": SQLColumn(type: .int, null: false), "u8": SQLColumn(type: .int, null: false), "u16": SQLColumn(type: .int, null: false), "u32": SQLColumn(type: .int, null: false), "u64": SQLColumn(type: .int, null: false), "oi": SQLColumn(type: .int, null: true), "oi8": SQLColumn(type: .int, null: true), "oi16": SQLColumn(type: .int, null: true), "oi32": SQLColumn(type: .int, null: true), "oi64": SQLColumn(type: .int, null: true), "ou": SQLColumn(type: .int, null: true), "ou8": SQLColumn(type: .int, null: true), "ou16": SQLColumn(type: .int, null: true), "ou32": SQLColumn(type: .int, null: true), "ou64": SQLColumn(type: .int, null: true), ], name: "Integers" )) } enum IntEnum: Int, Codable { case one, two } enum StringEnum: String, Codable { case abcd, efgh } struct Enums: SQLCodable { let ie: IntEnum let se: StringEnum let oie: IntEnum? let ose: StringEnum? } func testEnums() { XCTAssertThrowsError(try SQLTable(for: Enums.self)) { error in if case .missingPlaceholder(let missing) = error as! SQLError { XCTAssert(missing is StringEnum.Type) } } SQLTable.register(placeholder: StringEnum.abcd) XCTAssertEqual(try SQLTable(for: Enums.self), SQLTable( columns: [ "ie": SQLColumn(type: .int, null: false), "se": SQLColumn(type: .text, null: false), "oie": SQLColumn(type: .int, null: true), "ose": SQLColumn(type: .text, null: true), ], name: "Enums" )) } struct Options: OptionSet, Codable { let rawValue: UInt8 static let a = Options(rawValue: 1 << 0) static let b = Options(rawValue: 1 << 1) } struct OptionSets: SQLCodable { let o: Options let oo: Options? } func testOptionSets() { XCTAssertEqual(try SQLTable(for: OptionSets.self), SQLTable( columns: [ "o": SQLColumn(type: .int, null: false), "oo": SQLColumn(type: .int, null: true), ], name: "OptionSets" )) } struct Arrays: SQLCodable { let astr: [String] let oastr: [String]? let aostr: [String?] let aint: [Int] let oaint: [Int]? let aoint: [Int?] } func testArrays() { XCTAssertEqual(try SQLTable(for: Arrays.self), SQLTable( columns: [ "astr": SQLColumn(type: .text, null: false), "oastr": SQLColumn(type: .text, null: true), "aostr": SQLColumn(type: .text, null: false), "aint": SQLColumn(type: .text, null: false), "oaint": SQLColumn(type: .text, null: true), "aoint": SQLColumn(type: .text, null: false), ], name: "Arrays" )) } struct Inside: Codable { let v: [String] } struct NestedStructs: SQLCodable { let s: Inside let os: Inside? } func testNestedStructs() { XCTAssertEqual(try SQLTable(for: NestedStructs.self), SQLTable( columns: [ "s": SQLColumn(type: .text, null: false), "os": SQLColumn(type: .text, null: true), ], name: "NestedStructs" )) } }
32.568421
75
0.495314
db06bcda25fd08e5d2098304caaab87e34d0df93
196
// // ViewController.swift // DDExtension // // Created by DDKit on 08/08/2018. // Copyright (c) 2018 DDKit. All rights reserved. // class DDExtension: NSObject {} extension UIView { }
14
50
0.658163
e6cd20bdf6f7dd8717197041f673466dfd5f66a1
1,249
// // iKeaDemoUITests.swift // iKeaDemoUITests // // Created by PoCheng Juan on 2018/8/14. // Copyright © 2018年 PoCheng Juan. All rights reserved. // import XCTest class iKeaDemoUITests: 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. } }
33.756757
182
0.663731
f56efca62fb43d6eb868b00f6834f14174a8dba9
1,117
// // KeyCreator.swift // CachingService // // Created by Alexander Cyon on 2017-11-30. // Copyright © 2017 Alexander Cyon. All rights reserved. // import Foundation struct KeyCreator<T> { static var key: Key { return "\(FourLevelTypeUnwrapper<T>.fourLevelUnwrappedType)" } } protocol OptionalType { static var wrappedType: Any.Type { get } } extension Optional: OptionalType { static var wrappedType: Any.Type { return Wrapped.self } } struct FourLevelTypeUnwrapper<T> { static var fourLevelUnwrappedType: Any.Type { guard let optionalTypeLevel1 = T.self as? OptionalType.Type else { return T.self } guard let optionalTypeLevel2 = optionalTypeLevel1.wrappedType as? OptionalType.Type else { return optionalTypeLevel1.wrappedType } guard let optionalTypeLevel3 = optionalTypeLevel2.wrappedType as? OptionalType.Type else { return optionalTypeLevel2.wrappedType } guard let optionalTypeLevel4 = optionalTypeLevel3.wrappedType as? OptionalType.Type else { return optionalTypeLevel3.wrappedType } return optionalTypeLevel4.wrappedType } }
32.852941
138
0.741271
14ea989fbd93a1a31fa7db5362f092f195628eed
4,884
import Foundation import SwiftProtobuf print("Hello, world!") let weight:Float = 1.9828945 let bias:Float = 1.4585879 let coreModel = CoreML_Specification_Model.with { $0.specificationVersion = 4 $0.description_p = CoreML_Specification_ModelDescription.with { $0.input = [CoreML_Specification_FeatureDescription.with { $0.name = "dense_input" $0.type = CoreML_Specification_FeatureType.with { $0.multiArrayType = CoreML_Specification_ArrayFeatureType.with { $0.shape = [1] $0.dataType = CoreML_Specification_ArrayFeatureType.ArrayDataType.double } } }] $0.output = [CoreML_Specification_FeatureDescription.with { $0.name = "output" $0.type = CoreML_Specification_FeatureType.with { $0.multiArrayType = CoreML_Specification_ArrayFeatureType.with { $0.shape = [1] $0.dataType = CoreML_Specification_ArrayFeatureType.ArrayDataType.double } } }] $0.trainingInput = [CoreML_Specification_FeatureDescription.with { $0.name = "dense_input" $0.type = CoreML_Specification_FeatureType.with { $0.multiArrayType = CoreML_Specification_ArrayFeatureType.with { $0.shape = [1] $0.dataType = CoreML_Specification_ArrayFeatureType.ArrayDataType.double } } }, CoreML_Specification_FeatureDescription.with { $0.name = "output_true" $0.type = CoreML_Specification_FeatureType.with { $0.multiArrayType = CoreML_Specification_ArrayFeatureType.with { $0.shape = [1] $0.dataType = CoreML_Specification_ArrayFeatureType.ArrayDataType.double } } }] $0.metadata = CoreML_Specification_Metadata.with { $0.shortDescription = "Trivial linear classifier" $0.author = "Jacopo Mangiavacchi" $0.license = "MIT" $0.userDefined = ["coremltoolsVersion" : "3.1"] } } $0.isUpdatable = true $0.neuralNetwork = CoreML_Specification_NeuralNetwork.with { $0.layers = [CoreML_Specification_NeuralNetworkLayer.with { $0.name = "dense_1" $0.input = ["dense_input"] $0.output = ["output"] $0.isUpdatable = true $0.innerProduct = CoreML_Specification_InnerProductLayerParams.with { $0.inputChannels = 1 $0.outputChannels = 1 $0.hasBias_p = true $0.weights = CoreML_Specification_WeightParams.with { $0.floatValue = [weight] $0.isUpdatable = true } $0.bias = CoreML_Specification_WeightParams.with { $0.floatValue = [bias] $0.isUpdatable = true } } }] $0.updateParams = CoreML_Specification_NetworkUpdateParameters.with { $0.lossLayers = [CoreML_Specification_LossLayer.with { $0.name = "lossLayer" $0.meanSquaredErrorLossLayer = CoreML_Specification_MeanSquaredErrorLossLayer.with { $0.input = "output" $0.target = "output_true" } }] $0.optimizer = CoreML_Specification_Optimizer.with { $0.sgdOptimizer = CoreML_Specification_SGDOptimizer.with { $0.learningRate = CoreML_Specification_DoubleParameter.with { $0.defaultValue = 0.01 $0.range = CoreML_Specification_DoubleRange.with { $0.maxValue = 1.0 } } $0.miniBatchSize = CoreML_Specification_Int64Parameter.with { $0.defaultValue = 5 $0.set = CoreML_Specification_Int64Set.with { $0.values = [5] } } $0.momentum = CoreML_Specification_DoubleParameter.with { $0.defaultValue = 0 $0.range = CoreML_Specification_DoubleRange.with { $0.maxValue = 1.0 } } } } $0.epochs = CoreML_Specification_Int64Parameter.with { $0.defaultValue = 2 $0.set = CoreML_Specification_Int64Set.with { $0.values = [2] } } $0.shuffle = CoreML_Specification_BoolParameter.with { $0.defaultValue = true } } } }
41.042017
100
0.525389
1dd709a42ee5cceb7508ffcd1b986c4e422b644d
621
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "WaffleSpot", dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", .upToNextMinor(from: "3.1.0")), .package(url: "https://github.com/vapor/leaf.git", from: "3.0.0"), .package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0"), ], targets: [ .target(name: "App", dependencies: ["Vapor"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]), ] )
32.684211
91
0.590982
09fbbabc7066c8247743e880b87d35b895cc2a92
5,071
// // Xcore // Copyright © 2019 Xcore // MIT license, see LICENSE file for details // import SwiftUI /// A value that represents either a left or a right value, including an /// associated value in each case. public enum Either<Left, Right> { case left(Left) case right(Right) } extension Either { public static func left(value: Left?) -> Either? { guard let value = value else { return nil } return .left(value) } public static func right(value: Right?) -> Either? { guard let value = value else { return nil } return .right(value) } } extension Either { public var left: Left? { guard case let .left(left) = self else { return nil } return left } public var right: Right? { guard case let .right(right) = self else { return nil } return right } } extension Either { /// Returns a new result, mapping any left value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Either` /// instance when it represents a left value. The following example transforms /// the integer left value of a result into a string: /// /// ```swift /// func getNextInteger() -> Either<Int, String> { /* ... */ } /// /// let integerResult = getNextInteger() /// // integerResult == .left(5) /// let stringResult = integerResult.mapLeft { String($0) } /// // stringResult == .left("5") /// ``` /// /// - Parameter transform: A closure that takes the left value of this /// instance. /// - Returns: A `Either` instance with the result of evaluating `transform` /// as the new left value if this instance represents a left value. public func mapLeft<NewLeft>(_ transform: (Left) -> NewLeft) -> Either<NewLeft, Right> { switch self { case let .left(value): return .left(transform(value)) case let .right(value): return .right(value) } } /// Returns a new result, mapping any right value using the given /// transformation. /// /// Use this method when you need to transform the value of a `Either` /// instance when it represents a right value. The following example transforms /// the integer right value of a result into a string: /// /// ```swift /// func getNextInteger() -> Either<Int, String> { /* ... */ } /// /// let integerResult = getNextInteger() /// // integerResult == .right(5) /// let stringResult = integerResult.mapRight { String($0) } /// // stringResult == .right("5") /// ``` /// /// - Parameter transform: A closure that takes the right value of this /// instance. /// - Returns: A `Either` instance with the result of evaluating `transform` /// as the new right value if this instance represents a right value. public func mapRight<NewRight>(_ transform: (Right) -> NewRight) -> Either<Left, NewRight> { switch self { case let .left(value): return .left(value) case let .right(value): return .right(transform(value)) } } } // MARK: - String extension Either: ExpressibleByStringLiteral where Left == String { public init(stringLiteral value: StringLiteralType) { self = .left(value) } } extension Either: ExpressibleByExtendedGraphemeClusterLiteral where Left == String { public init(extendedGraphemeClusterLiteral value: String) { self = .left(value) } } extension Either: ExpressibleByUnicodeScalarLiteral where Left == String { public init(unicodeScalarLiteral value: String) { self = .left(value) } } // MARK: - Float extension Either: ExpressibleByFloatLiteral where Right == FloatLiteralType { public init(floatLiteral value: FloatLiteralType) { self = .right(value) } } // MARK: - Integer extension Either: ExpressibleByIntegerLiteral where Right == IntegerLiteralType { public init(integerLiteral value: IntegerLiteralType) { self = .right(value) } } // MARK: - Equatable extension Either: Equatable where Left: Equatable, Right: Equatable {} // MARK: - Hashable extension Either: Hashable where Left: Hashable, Right: Hashable {} // MARK: - CustomStringConvertible extension Either: CustomStringConvertible where Left: CustomStringConvertible, Right: CustomStringConvertible { public var description: String { switch self { case let .left(value): return String(describing: value) case let .right(value): return String(describing: value) } } } // MARK: - View extension Either: View where Left: View, Right: View { public var body: some View { switch self { case let .left(leftView): leftView case let .right(rightView): rightView } } }
28.016575
111
0.607375
916222faa9b953f23990c205729999d014e417d1
11,109
// // CompletionQueueTests.swift // GenericConnectionFrameworkTests // // Created by Alan Downs on 2/11/19. // Copyright © 2019 mobileforming LLC. All rights reserved. // import XCTest @testable import GenericConnectionFramework class CompletionQueueTests: XCTestCase { var completionQueue: CompletionQueue! override func setUp() { completionQueue = CompletionQueue() } override func tearDown() { completionQueue = nil } func testKey() { var routable = MockRoutable() routable.path = "/some/arbitrary/path" routable.headers = ["header1": "value1", "header2": "value2"] routable.parameters = ["parameter1": "value1", "parameter2": "value2"] routable.body = ["key1": "value1", "key2": "value2", "key3": "value3"] let routableHash = "/some/arbitrary/path".hashValue &+ HTTPMethod.get.hashValue &+ ["parameter1": "value1", "parameter2": "value2"].hashValue &+ ["key1": "value1", "key2": "value2", "key3": "value3"].hashValue let key = completionQueue.key(for: routable, numAuthRetries: 99, completionType: [String:Any].self) let expectedKey = "\(routableHash &+ 99):Dictionary<String, Any>" XCTAssertEqual(key, expectedKey) var routable1 = MockRoutable() routable1.path = "/some/path/arbitrary" routable1.headers = ["header1": "value1", "header2": "value2"] routable1.parameters = ["parameter1": "value1", "parameter2": "value2"] routable1.body = ["key1": "value1", "key2": "value2", "key3": "value3"] let key1 = completionQueue.key(for: routable, numAuthRetries: 99, completionType: [String:Any].self) let key2 = completionQueue.key(for: routable, numAuthRetries: 99, completionType: [String:Any].self) let key3 = completionQueue.key(for: routable, numAuthRetries: 97, completionType: [String:Any].self) let key4 = completionQueue.key(for: routable1, numAuthRetries: 99, completionType: [String:Any].self) XCTAssertEqual(key1, key2) XCTAssertNotEqual(key1, key3) XCTAssertNotEqual(key1, key4) } // MARK - Codable func testShouldRequestContinueCodable() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, EmptyCodable?, Error?) -> Void = { (_, result, error) in completed += 1 } let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) let secondResult = completionQueue.shouldRequestContinue(forKey: completionQueue.key(for: routable, numAuthRetries: 99, completionType: EmptyCodable.self), completion: completion) XCTAssertFalse(secondResult) XCTAssertEqual(completed, 0) let exp = expectation(description: "") let group = DispatchGroup() for _ in 0...10 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 0) } func testProcessCompletionsCodable() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, EmptyCodable?, Error?) -> Void = { (_, result, error) in completed += 1 } //add in the first let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) //add in 9 more let exp = expectation(description: "") let group = DispatchGroup() for _ in 1...9 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) completionQueue.processCompletions(forRoutable: routable, response: nil, numAuthRetries: 99, result: EmptyCodable(), error: nil) let waitExp = expectation(description: "") DispatchQueue.main.asyncAfter(deadline: .now() + 3) { waitExp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 10) //check new request, queue is empty let result = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(result) } // MARK - Bool func testShouldRequestContinueBool() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, Bool?, Error?) -> Void = { (_, result, error) in completed += 1 } let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) let secondResult = completionQueue.shouldRequestContinue(forKey: completionQueue.key(for: routable, numAuthRetries: 99, completionType: Bool.self), completion: completion) XCTAssertFalse(secondResult) XCTAssertEqual(completed, 0) let exp = expectation(description: "") let group = DispatchGroup() for _ in 0...10 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 0) } func testProcessCompletionsBool() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, Bool?, Error?) -> Void = { (_, result, error) in completed += 1 } //add in the first let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) //add in 9 more let exp = expectation(description: "") let group = DispatchGroup() for _ in 1...9 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) completionQueue.processCompletions(forRoutable: routable, response: nil, numAuthRetries: 99, result: true as Bool?, error: nil) let waitExp = expectation(description: "") DispatchQueue.main.asyncAfter(deadline: .now() + 3) { waitExp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 10) //check new request, queue is empty let result = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(result) } // MARK - Dictionary func testShouldRequestContinueDictionary() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, [String: Any]?, Error?) -> Void = { (_, result, error) in completed += 1 } let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) let secondResult = completionQueue.shouldRequestContinue(forKey: completionQueue.key(for: routable, numAuthRetries: 99, completionType: [String:Any].self), completion: completion) XCTAssertFalse(secondResult) XCTAssertEqual(completed, 0) let exp = expectation(description: "") let group = DispatchGroup() for _ in 0...10 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 0) } func testProcessCompletionsDictionary() { let routable = MockRoutable() var completed = 0 let completion: (ResponseHeader?, [String: Any]?, Error?) -> Void = { (_, result, error) in completed += 1 } //add in the first let firstResult = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(firstResult) XCTAssertEqual(completed, 0) //add in 9 more let exp = expectation(description: "") let group = DispatchGroup() for _ in 1...9 { group.enter() DispatchQueue.global().async { let testResult = self.completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertFalse(testResult) XCTAssertEqual(completed, 0) group.leave() } } group.notify(queue: .main) { exp.fulfill() } waitForExpectations(timeout: 10, handler: nil) completionQueue.processCompletions(forRoutable: routable, response: nil, numAuthRetries: 99, result: ["hello": "goodbye"] as [String: Any]?, error: nil) let waitExp = expectation(description: "") DispatchQueue.main.asyncAfter(deadline: .now() + 5) { waitExp.fulfill() } waitForExpectations(timeout: 10, handler: nil) XCTAssertEqual(completed, 10) //check new request, queue is empty let result = completionQueue.shouldRequestContinue(forRoutable: routable, numAuthRetries: 99, completion: completion) XCTAssertTrue(result) } } struct EmptyCodable: Codable {}
38.306897
187
0.639752
e04d77262d05f52d23fd30850acb84a690f1094e
2,225
/* * -------------------------------------------------------------------------------------------------------------------- * <copyright company="Aspose"> * Copyright (c) 2020 Aspose.Slides for Cloud * </copyright> * <summary> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * </summary> * -------------------------------------------------------------------------------------------------------------------- */ import Foundation /** Save shape task. */ public struct SaveShape: Codable { public enum Format: String, Codable { case jpeg = "Jpeg" case png = "Png" case gif = "Gif" case bmp = "Bmp" case tiff = "Tiff" case svg = "Svg" } /** Format. */ public var format: Format? /** Shape path. */ public var shapePath: String? /** Output file. */ public var output: OutputFile? /** Save options. */ public var options: IShapeExportOptions? public init(format: Format?, shapePath: String?, output: OutputFile?, options: IShapeExportOptions?) { self.format = format self.shapePath = shapePath self.output = output self.options = options } }
35.31746
119
0.605393
b98befa10304bba677674605d93867890785fb96
3,867
// // PivotalAttachment.swift // bugTrap // // Created by Colby L Williams on 11/10/14. // Copyright (c) 2014 bugTrap. All rights reserved. // import Foundation class PivotalAttachment : JsonSerializable { var id: Int? var projectId: Int? var filename = "" var uploaderId = 0 var thumbnailable = false var height = 0 var width = 0 var size = 0 var downloadUrl = "" var contentType = "" var uploaded = false var bigUrl = "" var thumbnailUrl = "" var kind = "" init(id: Int?, projectId: Int?, filename: String, uploaderId: Int, thumbnailable: Bool, height: Int, width: Int, size: Int, downloadUrl: String, contentType: String, uploaded: Bool, bigUrl: String, thumbnailUrl: String, kind: String) { self.id = id self.projectId = projectId self.filename = filename self.uploaderId = uploaderId self.thumbnailable = thumbnailable self.height = height self.width = width self.size = size self.downloadUrl = downloadUrl self.contentType = contentType self.uploaded = uploaded self.bigUrl = bigUrl self.thumbnailUrl = thumbnailUrl self.kind = kind } class func deserialize (json: JSON) -> PivotalAttachment? { var projectId: Int? if let id = json["id"].int { if let projectIdW = json["project_id"].int { projectId = projectIdW } let filename = json["filename"].stringValue let uploaderId = json["uploader_id"].intValue let thumbnailable = json["thumbnailable"].boolValue let height = json["height"].intValue let width = json["width"].intValue let size = json["size"].intValue let downloadUrl = json["download_url"].stringValue let contentType = json["content_type"].stringValue let uploaded = json["uploaded"].boolValue let bigUrl = json["big_url"].stringValue let thumbnailUrl = json["thumbnail_url"].stringValue let kind = json["kind"].stringValue return PivotalAttachment(id: id, projectId: projectId, filename: filename, uploaderId: uploaderId, thumbnailable: thumbnailable, height: height, width: width, size: size, downloadUrl: downloadUrl, contentType: contentType, uploaded: uploaded, bigUrl: bigUrl, thumbnailUrl: thumbnailUrl, kind: kind) } return nil } class func deserializeAll(json: JSON) -> [PivotalAttachment] { var items = [PivotalAttachment]() if let jsonArray = json.array { for item: JSON in jsonArray { if let pivotalAttachment = deserialize(item) { items.append(pivotalAttachment) } } } return items } func serialize () -> NSMutableDictionary { let dict = NSMutableDictionary() dict.setValue(projectId == nil ? nil : Int(projectId!), forKey: PivotalFields.NewAttachmentFields.ProjectId.rawValue) dict.setValue(id == nil ? nil : id!, forKey: PivotalFields.NewAttachmentFields.Id.rawValue) dict.setObject(filename, forKey: PivotalFields.NewAttachmentFields.Filename.rawValue) dict.setObject(uploaderId, forKey: PivotalFields.NewAttachmentFields.UploaderId.rawValue) dict.setObject(thumbnailable, forKey: PivotalFields.NewAttachmentFields.Thumbnailable.rawValue) dict.setObject(height, forKey: PivotalFields.NewAttachmentFields.Height.rawValue) dict.setObject(width, forKey: PivotalFields.NewAttachmentFields.Width.rawValue) dict.setObject(size, forKey: PivotalFields.NewAttachmentFields.Size.rawValue) dict.setObject(downloadUrl, forKey: PivotalFields.NewAttachmentFields.DownloadUrl.rawValue) dict.setObject(contentType, forKey: PivotalFields.NewAttachmentFields.ContentType.rawValue) dict.setObject(uploaded, forKey: PivotalFields.NewAttachmentFields.Uploaded.rawValue) dict.setObject(bigUrl, forKey: PivotalFields.NewAttachmentFields.BigUrl.rawValue) dict.setObject(thumbnailUrl, forKey: PivotalFields.NewAttachmentFields.ThumbnailUrl.rawValue) dict.setObject(kind, forKey: PivotalFields.NewAttachmentFields.Kind.rawValue) return dict } }
28.226277
301
0.744763
56df8956a6f86ea7617ecc79e34b987ca803840e
8,165
// // Maps.swift // kakaoFirebase // // Created by swuad_39 on 09/01/2020. // Copyright © 2020 Digital Media Dept. All rights reserved. // import UIKit import GoogleMaps import CoreLocation import GooglePlaces class Maps:UIViewController, GMSMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate { @IBOutlet weak var GoogleMapController: UIView! var address:String? var googlemapsView: GMSMapView! var resultArray = [String]() let autocompleteController = GMSAutocompleteViewController() var delegate:DiaryWriteViewController! @IBAction func searchBtn(_ sender: UIButton) { autocompleteController.delegate = self NSLog("2") // Specify the place data types to return. let fields: GMSPlaceField = GMSPlaceField(rawValue: UInt(GMSPlaceField.name.rawValue) | UInt(GMSPlaceField.placeID.rawValue))! autocompleteController.placeFields = fields NSLog("3") // Specify a filter. let filter = GMSAutocompleteFilter() filter.type = .address autocompleteController.autocompleteFilter = filter NSLog("4") // Display the autocomplete view controller. present(autocompleteController, animated: true, completion: nil) NSLog("5") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) let location = locationMgr.location!.coordinate let cameraCenter = GMSCameraPosition.camera(withLatitude: location.latitude, longitude: location.longitude, zoom: 16.0) self.googlemapsView = GMSMapView(frame: self.GoogleMapController.frame, camera: cameraCenter) googlemapsView.isMyLocationEnabled = true googlemapsView.settings.myLocationButton = true locationMgr.location?.coordinate //현재위치 // marker.position = CLLocationCoordinate2D(latitude: 37.6281126, longitude: 127.0904568) //self.GoogleMapsView = GMSMapView(frame: self.GoogleMapController.frame) //mapView.isMyLocationEnabled = true //mapView.settings.myLocationButton = true self.view.addSubview(self.googlemapsView) //let mapView = GMSMapView.map(withFrame: .zero, camera: camera) //mapView.settings.myLocationButton = true let mapView = GMSMapView.map(withFrame: self.GoogleMapController.frame, camera: cameraCenter) //마커찍기 let position = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude) let marker2 = GMSMarker(position: position) marker2.title = "서울여자대학교" //marker.iconView = markerView marker2.tracksViewChanges = true marker2.map = googlemapsView //london = marker // self.GoogleMapController.insertSubview(mapView, at: 0) mapView.delegate = self //let marker = GMSMarker() //marker.position = CLLocationCoordinate2D(latitude: 37.6281126, longitude: 127.0904568) } var appDelegate:AppDelegate! var locationMgr:CLLocationManager! var mapView:GMSMapView! @IBOutlet weak var DoneBtnoutlet: UIBarButtonItem! @IBOutlet weak var mainView: UIView! override func viewDidLoad() { super.viewDidLoad() appDelegate = UIApplication.shared.delegate as! AppDelegate locationMgr = appDelegate.locationMgr locationMgr.delegate = self if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { locationMgr.desiredAccuracy = kCLLocationAccuracyBest locationMgr.startUpdatingLocation() } } func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker)-> Bool{ print(marker.title) return true } func locationManger( _manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { let camera = GMSCameraPosition.camera(withLatitude: location.coordinate.latitude, longitude: location.coordinate.longitude, zoom: mapView.camera.zoom) mapView.animate(to: camera) } } @IBAction func DoneBtn(_ sender: UIBarButtonItem) { NSLog("dkddk") NSLog("\(self.address)") self.delegate.form.rowBy(tag: "meetArea")!.value = "\(self.address!)" self.dismiss(animated: true) } } extension Maps: GMSAutocompleteViewControllerDelegate { // Handle the user's selection. func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) { NSLog(place.formattedAddress ?? "") GMSPlacesClient.shared().lookUpPlaceID(place.placeID!) { (result, error) in NSLog("query in") if let error = error { NSLog(error.localizedDescription) return } NSLog("query out") debugPrint(result?.coordinate) //마커찍기 if let coordinate = result?.coordinate { let position = CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude) let marker = GMSMarker(position: position) marker.title = place.name //marker.iconView = markerView marker.tracksViewChanges = true marker.map = self.googlemapsView print("Place name: \(place.name)") print("Place address: \(result?.formattedAddress)") self.address = result?.formattedAddress NSLog("address:\(self.address)") //london = marker let camera = GMSCameraPosition.camera(withLatitude: coordinate.latitude, longitude: coordinate.longitude, zoom: 16.0) self.googlemapsView.animate(to: camera) } self.dismiss(animated: true, completion: nil) // print("Place address: \(place.formattedAddress)") } } func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) { // TODO: handle the error. print("Error: ", error.localizedDescription) } // User canceled the operation. func wasCancelled(_ viewController: GMSAutocompleteViewController) { dismiss(animated: true, completion: nil) } // Turn the network activity indicator on and off again. func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) { UIApplication.shared.isNetworkActivityIndicatorVisible = false } /* func updateMap(){ let camera = GMSCameraPosition.camera(withLatitude: , longitude: place.longitude, zoom: 16.0) self.googlemapsView = GMSMapView(frame: self.GoogleMapController.frame, camera: camera) //self.GoogleMapsView = GMSMapView(frame: self.GoogleMapController.frame) //mapView.isMyLocationEnabled = true //mapView.settings.myLocationButton = true self.view.addSubview(self.googlemapsView) //let mapView = GMSMapView.map(withFrame: .zero, camera: camera) //mapView.settings.myLocationButton = true let mapView = GMSMapView.map(withFrame: self.GoogleMapController.frame, camera: cameraCenter) // self.GoogleMapController.insertSubview(mapView, at: 0) mapView.delegate = self mapView.isMyLocationEnabled = true mapView.settings.myLocationButton = true //let marker = GMSMarker() //marker.position = CLLocationCoordinate2D(latitude: 37.6281126, longitude: 127.0904568) } */ }
36.128319
117
0.637967
3989bf2901ca7786568d1ed41168a00d3d4eca2a
46,508
import Basic import Foundation import TuistSupport import XCTest @testable import TuistCore @testable import TuistCoreTesting @testable import TuistSupport @testable import TuistSupportTesting final class GraphErrorTests: XCTestCase { func test_description_when_unsupportedFileExtension() { let error = GraphError.unsupportedFileExtension("type") let description = "Could't obtain product file extension for product type: type" XCTAssertEqual(error.description, description) } func test_type_when_unsupportedFileExtension() { let error = GraphError.unsupportedFileExtension("type") XCTAssertEqual(error.type, .bug) } } final class GraphTests: TuistUnitTestCase { func test_frameworks() throws { let framework = FrameworkNode.test(path: AbsolutePath("/path/to/framework.framework")) let graph = Graph.test(precompiled: [framework]) XCTAssertTrue(graph.frameworks.contains(framework)) } func test_targetDependencies() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "Dependency", product: .staticLibrary) let project = Project.test(targets: [target, dependency]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(targets: [targetNode.path: [targetNode]]) let dependencies = graph.targetDependencies(path: project.path, name: target.name) XCTAssertEqual(dependencies.first?.target.name, "Dependency") } func test_testTargetsDependingOn() throws { // given let target = Target.test(name: "Main") let dependentTarget = Target.test(name: "Dependency", product: .staticLibrary) let testTarget1 = Target.test(name: "MainTests1", product: .unitTests) let testTarget2 = Target.test(name: "MainTests2", product: .unitTests) let testTarget3 = Target.test(name: "MainTests3", product: .unitTests) let testTargets = [testTarget1, testTarget2, testTarget3] let project = Project.test(targets: [target, dependentTarget] + testTargets) let dependencyNode = TargetNode(project: project, target: dependentTarget, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let testsNodes = testTargets.map { TargetNode(project: project, target: $0, dependencies: [targetNode]) } let targets = testsNodes.reduce(into: [project.path: [targetNode, dependencyNode]]) { $0[project.path]?.append($1) } let graph = Graph.test(projects: [project], targets: targets) // when let testDependencies = graph.testTargetsDependingOn(path: project.path, name: target.name) // then let testDependenciesNames = try XCTUnwrap(testDependencies).map { $0.name } XCTAssertEqual(testDependenciesNames.count, 3) XCTAssertEqual(testDependenciesNames, ["MainTests1", "MainTests2", "MainTests3"]) } func test_linkableDependencies_whenPrecompiled() throws { let target = Target.test(name: "Main") let precompiledNode = FrameworkNode.test(path: AbsolutePath("/test/test.framework")) let project = Project.test(targets: [target]) let targetNode = TargetNode(project: project, target: target, dependencies: [precompiledNode]) let graph = Graph.test(targets: [targetNode.path: [targetNode]]) let got = try graph.linkableDependencies(path: project.path, name: target.name) XCTAssertEqual(got.first, GraphDependencyReference(precompiledNode: precompiledNode)) } func test_linkableDependencies_whenALibraryTarget() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "Dependency", product: .staticLibrary) let project = Project.test(targets: [target]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [ project.path: [dependencyNode, targetNode], ]) let got = try graph.linkableDependencies(path: project.path, name: target.name) XCTAssertEqual(got.first, .product(target: "Dependency", productName: "libDependency.a")) } func test_linkableDependencies_whenAFrameworkTarget() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "Dependency", product: .framework) let staticDependency = Target.test(name: "StaticDependency", product: .staticLibrary) let project = Project.test(targets: [target]) let staticDependencyNode = TargetNode(project: project, target: staticDependency, dependencies: []) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: [staticDependencyNode]) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [project.path: [targetNode, dependencyNode, staticDependencyNode]]) let got = try graph.linkableDependencies(path: project.path, name: target.name) XCTAssertEqual(got.count, 1) XCTAssertEqual(got.first, .product(target: "Dependency", productName: "Dependency.framework")) let frameworkGot = try graph.linkableDependencies(path: project.path, name: dependency.name) XCTAssertEqual(frameworkGot.count, 1) XCTAssertTrue(frameworkGot.contains(.product(target: "StaticDependency", productName: "libStaticDependency.a"))) } func test_linkableDependencies_transitiveDynamicLibrariesOneStaticHop() throws { // Given let staticFramework = Target.test(name: "StaticFramework", product: .staticFramework, dependencies: []) let dynamicFramework = Target.test(name: "DynamicFramework", product: .framework, dependencies: []) let app = Target.test(name: "App", product: .app) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [staticFramework]), (target: staticFramework, dependencies: [dynamicFramework]), (target: dynamicFramework, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: app.name) // Then XCTAssertEqual(result, [GraphDependencyReference.product(target: "DynamicFramework", productName: "DynamicFramework.framework"), GraphDependencyReference.product(target: "StaticFramework", productName: "StaticFramework.framework")]) } func test_linkableDependencies_transitiveDynamicLibrariesThreeHops() throws { // Given let dynamicFramework1 = Target.test(name: "DynamicFramework1", product: .framework, dependencies: []) let dynamicFramework2 = Target.test(name: "DynamicFramework2", product: .framework, dependencies: []) let staticFramework1 = Target.test(name: "StaticFramework1", product: .staticLibrary, dependencies: []) let staticFramework2 = Target.test(name: "StaticFramework2", product: .staticLibrary, dependencies: []) let app = Target.test(name: "App", product: .app) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [dynamicFramework1]), (target: dynamicFramework1, dependencies: [staticFramework1]), (target: staticFramework1, dependencies: [staticFramework2]), (target: staticFramework2, dependencies: [dynamicFramework2]), (target: dynamicFramework2, dependencies: []), ]) // When let appResult = try graph.linkableDependencies(path: projectA.path, name: app.name) let dynamicFramework1Result = try graph.linkableDependencies(path: projectA.path, name: dynamicFramework1.name) // Then XCTAssertEqual(appResult, [ GraphDependencyReference.product(target: "DynamicFramework1", productName: "DynamicFramework1.framework"), ]) XCTAssertEqual(dynamicFramework1Result, [ GraphDependencyReference.product(target: "DynamicFramework2", productName: "DynamicFramework2.framework"), GraphDependencyReference.product(target: "StaticFramework1", productName: "libStaticFramework1.a"), GraphDependencyReference.product(target: "StaticFramework2", productName: "libStaticFramework2.a"), ]) } func test_linkableDependencies_transitiveDynamicLibrariesCheckNoDuplicatesInParentDynamic() throws { // Given let dynamicFramework1 = Target.test(name: "DynamicFramework1", product: .framework, dependencies: []) let dynamicFramework2 = Target.test(name: "DynamicFramework2", product: .framework, dependencies: []) let dynamicFramework3 = Target.test(name: "DynamicFramework3", product: .framework, dependencies: []) let staticFramework1 = Target.test(name: "StaticFramework1", product: .staticLibrary, dependencies: []) let staticFramework2 = Target.test(name: "StaticFramework2", product: .staticLibrary, dependencies: []) let app = Target.test(name: "App", product: .app) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [dynamicFramework1]), (target: dynamicFramework1, dependencies: [dynamicFramework2]), (target: dynamicFramework2, dependencies: [staticFramework1]), (target: staticFramework1, dependencies: [staticFramework2]), (target: staticFramework2, dependencies: [dynamicFramework3]), (target: dynamicFramework3, dependencies: []), ]) // When let dynamicFramework1Result = try graph.linkableDependencies(path: projectA.path, name: dynamicFramework1.name) // Then XCTAssertEqual(dynamicFramework1Result, [GraphDependencyReference.product(target: "DynamicFramework2", productName: "DynamicFramework2.framework")]) } func test_linkableDependencies_transitiveSDKDependenciesStatic() throws { // Given let staticFrameworkA = Target.test(name: "StaticFrameworkA", product: .staticFramework, dependencies: [.sdk(name: "some.framework", status: .optional)]) let staticFrameworkB = Target.test(name: "StaticFrameworkB", product: .staticFramework, dependencies: []) let app = Target.test(name: "App", product: .app) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [staticFrameworkB]), (target: staticFrameworkB, dependencies: [staticFrameworkA]), (target: staticFrameworkA, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: app.name) // Then XCTAssertEqual(result.compactMap(sdkDependency), [ SDKPathAndStatus(name: "some.framework", status: .optional), ]) } func test_linkableDependencies_transitiveSDKDependenciesDynamic() throws { // Given let staticFramework = Target.test(name: "StaticFramework", product: .staticFramework, dependencies: [.sdk(name: "some.framework", status: .optional)]) let dynamicFramework = Target.test(name: "DynamicFramework", product: .framework, dependencies: []) let app = Target.test(name: "App", product: .app) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [dynamicFramework]), (target: dynamicFramework, dependencies: [staticFramework]), (target: staticFramework, dependencies: []), ]) // When let appResult = try graph.linkableDependencies(path: projectA.path, name: app.name) let dynamicResult = try graph.linkableDependencies(path: projectA.path, name: dynamicFramework.name) // Then XCTAssertEqual(appResult.compactMap(sdkDependency), []) XCTAssertEqual(dynamicResult.compactMap(sdkDependency), [SDKPathAndStatus(name: "some.framework", status: .optional)]) } func test_linkableDependencies_transitiveSDKDependenciesNotDuplicated() throws { // Given let staticFramework = Target.test(name: "StaticFramework", product: .staticFramework, dependencies: [.sdk(name: "some.framework", status: .optional)]) let app = Target.test(name: "App", product: .app, dependencies: [.sdk(name: "some.framework", status: .optional)]) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [staticFramework]), (target: staticFramework, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: app.name) // Then XCTAssertEqual(result.compactMap(sdkDependency), [SDKPathAndStatus(name: "some.framework", status: .optional)]) } func test_linkableDependencies_transitiveSDKDependenciesImmediateDependencies() throws { // Given let staticFramework = Target.test(name: "StaticFrameworkA", product: .staticFramework, dependencies: [.sdk(name: "thingone.framework", status: .optional), .sdk(name: "thingtwo.framework", status: .required)]) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: staticFramework, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: staticFramework.name) // Then XCTAssertEqual(result.compactMap(sdkDependency), [SDKPathAndStatus(name: "thingone.framework", status: .optional), SDKPathAndStatus(name: "thingtwo.framework", status: .required)]) } func test_linkableDependencies_NoTransitiveSDKDependenciesForStaticFrameworks() throws { // Given let staticFrameworkA = Target.test(name: "StaticFrameworkA", product: .staticFramework, dependencies: [.sdk(name: "ThingOne.framework", status: .optional)]) let staticFrameworkB = Target.test(name: "StaticFrameworkB", product: .staticFramework, dependencies: [.sdk(name: "ThingTwo.framework", status: .optional)]) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: staticFrameworkA, dependencies: [staticFrameworkB]), (target: staticFrameworkB, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: staticFrameworkA.name) // Then XCTAssertEqual(result.compactMap(sdkDependency), [SDKPathAndStatus(name: "ThingOne.framework", status: .optional)]) } func test_linkableDependencies_when_watchExtension() throws { // Given let frameworkA = Target.test(name: "FrameworkA", product: .framework) let frameworkB = Target.test(name: "FrameworkB", product: .framework) let watchExtension = Target.test(name: "WatchExtension", product: .watch2Extension) let project = Project.test(targets: [watchExtension, frameworkA, frameworkB]) let graph = Graph.create(project: project, dependencies: [ (target: watchExtension, dependencies: [frameworkA]), (target: frameworkA, dependencies: [frameworkB]), (target: frameworkB, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: project.path, name: watchExtension.name) // Then XCTAssertEqual(result, [ .product(target: "FrameworkA", productName: "FrameworkA.framework"), ]) } func test_linkableDependencies_when_watchExtension_staticDependency() throws { // Given let frameworkA = Target.test(name: "FrameworkA", product: .staticFramework) let frameworkB = Target.test(name: "FrameworkB", product: .framework) let watchExtension = Target.test(name: "WatchExtension", product: .watch2Extension) let project = Project.test(targets: [watchExtension, frameworkA, frameworkB]) let graph = Graph.create(project: project, dependencies: [ (target: watchExtension, dependencies: [frameworkA]), (target: frameworkA, dependencies: [frameworkB]), (target: frameworkB, dependencies: []), ]) // When let result = try graph.linkableDependencies(path: project.path, name: watchExtension.name) // Then XCTAssertEqual(result, [ .product(target: "FrameworkA", productName: "FrameworkA.framework"), .product(target: "FrameworkB", productName: "FrameworkB.framework"), ]) } func test_linkableDependencies_whenHostedTestTarget_withCommonStaticProducts() throws { // Given let staticFramework = Target.test(name: "StaticFramework", product: .staticFramework) let app = Target.test(name: "App", product: .app) let tests = Target.test(name: "AppTests", product: .unitTests) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [staticFramework]), (target: staticFramework, dependencies: []), (target: tests, dependencies: [app, staticFramework]), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: tests.name) // Then XCTAssertTrue(result.isEmpty) } func test_linkableDependencies_whenHostedTestTarget_withCommonDynamicProducts() throws { // Given let framework = Target.test(name: "Framework", product: .framework) let app = Target.test(name: "App", product: .app) let tests = Target.test(name: "AppTests", product: .unitTests) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [framework]), (target: framework, dependencies: []), (target: tests, dependencies: [app, framework]), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: tests.name) // Then XCTAssertEqual(result, [ .product(target: "Framework", productName: "Framework.framework"), ]) } func test_linkableDependencies_whenHostedTestTarget_doNotIncludeRedundantDependencies() throws { // Given let framework = Target.test(name: "Framework", product: .framework) let app = Target.test(name: "App", product: .app) let tests = Target.test(name: "AppTests", product: .unitTests) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [framework]), (target: framework, dependencies: []), (target: tests, dependencies: [app]), ]) // When let result = try graph.linkableDependencies(path: projectA.path, name: tests.name) // Then XCTAssertTrue(result.isEmpty) } func test_librariesPublicHeaders() throws { let target = Target.test(name: "Main") let publicHeadersPath = AbsolutePath("/test/public/") let precompiledNode = LibraryNode.test(path: AbsolutePath("/test/test.a"), publicHeaders: publicHeadersPath) let project = Project.test(targets: [target]) let targetNode = TargetNode(project: project, target: target, dependencies: [precompiledNode]) let graph = Graph.test(projects: [project], precompiled: [precompiledNode], targets: [project.path: [targetNode]]) let got = graph.librariesPublicHeadersFolders(path: project.path, name: target.name) XCTAssertEqual(got.first, publicHeadersPath) } func test_embeddableFrameworks_when_targetIsNotApp() throws { // Given let target = Target.test(name: "Main", product: .framework) let dependency = Target.test(name: "Dependency", product: .framework) let project = Project.test(targets: [target]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [ project.path: [targetNode, dependencyNode], ]) system.succeedCommand([], output: "dynamically linked") // When let got = try graph.embeddableFrameworks(path: project.path, name: target.name) // Then XCTAssertNil(got.first) } func test_embeddableFrameworks_when_dependencyIsATarget() throws { // Given let target = Target.test(name: "Main") let dependency = Target.test(name: "Dependency", product: .framework) let project = Project.test(targets: [target]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [project.path: [targetNode, dependencyNode]]) // When let got = try graph.embeddableFrameworks(path: project.path, name: target.name) // Then XCTAssertEqual(got.first, GraphDependencyReference.product(target: "Dependency", productName: "Dependency.framework")) } func test_embeddableFrameworks_when_dependencyIsAFramework() throws { // Given let frameworkPath = AbsolutePath("/test/test.framework") let target = Target.test(name: "Main", platform: .iOS) let frameworkNode = FrameworkNode.test(path: frameworkPath) let project = Project.test(targets: [target]) let targetNode = TargetNode(project: project, target: target, dependencies: [frameworkNode]) let graph = Graph.test(projects: [project], precompiled: [frameworkNode], targets: [project.path: [targetNode]]) // When let got = try graph.embeddableFrameworks(path: project.path, name: target.name) // Then XCTAssertEqual(got.first, GraphDependencyReference(precompiledNode: frameworkNode)) } func test_embeddableFrameworks_when_transitiveXCFrameworks() throws { // Given let app = Target.test(name: "App", platform: .iOS, product: .app) let project = Project.test(targets: [app]) let dNode = XCFrameworkNode.test(path: "/xcframeworks/d.xcframework") let cNode = XCFrameworkNode.test(path: "/xcframeworks/c.xcframework", dependencies: [.xcframework(dNode)]) let appNode = TargetNode.test(target: app, dependencies: [cNode]) let cache = GraphLoaderCache() cache.add(targetNode: appNode) cache.add(precompiledNode: dNode) cache.add(precompiledNode: cNode) let graph = Graph.test(entryNodes: [appNode], projects: [project], precompiled: [cNode, dNode], targets: [project.path: [appNode]]) // When let got = try graph.embeddableFrameworks(path: project.path, name: app.name) // Then XCTAssertEqual(got, [ GraphDependencyReference(precompiledNode: cNode), GraphDependencyReference(precompiledNode: dNode), ]) } func test_embeddableFrameworks_when_dependencyIsATransitiveFramework() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "Dependency", product: .framework) let project = Project.test(targets: [target]) let frameworkPath = AbsolutePath("/test/test.framework") let frameworkNode = FrameworkNode.test(path: frameworkPath) let dependencyNode = TargetNode( project: project, target: dependency, dependencies: [frameworkNode] ) let targetNode = TargetNode( project: project, target: target, dependencies: [dependencyNode] ) let graph = Graph.test(projects: [project], precompiled: [frameworkNode], targets: [project.path: [targetNode, dependencyNode]]) let got = try graph.embeddableFrameworks(path: project.path, name: target.name) XCTAssertEqual(got, [ GraphDependencyReference.product(target: "Dependency", productName: "Dependency.framework"), GraphDependencyReference(precompiledNode: frameworkNode), ]) } func test_embeddableFrameworks_when_precompiledStaticFramework() throws { // Given let target = Target.test(name: "Main") let project = Project.test(targets: [target]) let frameworkNode = FrameworkNode.test(path: "/test/StaticFramework.framework", linking: .static) let targetNode = TargetNode( project: project, target: target, dependencies: [frameworkNode] ) let graph = Graph.test(projects: [project], precompiled: [frameworkNode], targets: [project.path: [targetNode]]) // When let result = try graph.embeddableFrameworks(path: project.path, name: target.name) // Then XCTAssertTrue(result.isEmpty) } func test_embeddableFrameworks_when_watchExtension() throws { // Given let frameworkA = Target.test(name: "FrameworkA", product: .framework) let frameworkB = Target.test(name: "FrameworkB", product: .framework) let watchExtension = Target.test(name: "WatchExtension", product: .watch2Extension) let project = Project.test(targets: [watchExtension, frameworkA, frameworkB]) let graph = Graph.create(project: project, dependencies: [ (target: watchExtension, dependencies: [frameworkA]), (target: frameworkA, dependencies: [frameworkB]), (target: frameworkB, dependencies: []), ]) // When let result = try graph.embeddableFrameworks(path: project.path, name: watchExtension.name) // Then XCTAssertEqual(result, [ .product(target: "FrameworkA", productName: "FrameworkA.framework"), .product(target: "FrameworkB", productName: "FrameworkB.framework"), ]) } func test_embeddableFrameworks_ordered() throws { // Given let dependencyNames = (0 ..< 10).shuffled().map { "Dependency\($0)" } let target = Target.test(name: "Main", product: .app) let project = Project.test(targets: [target]) let dependencyNodes = dependencyNames.map { TargetNode(project: project, target: Target.test(name: $0, product: .framework), dependencies: []) } let targetNode = TargetNode(project: project, target: target, dependencies: dependencyNodes) let targetNodes = dependencyNodes.reduce(into: [project.path: [targetNode]]) { $0[project.path]?.append($1) } let graph = Graph.test(projects: [project], targets: targetNodes) // When let got = try graph.embeddableFrameworks(path: project.path, name: target.name) // Then let expected = dependencyNames.sorted().map { GraphDependencyReference.product(target: $0, productName: "\($0).framework") } XCTAssertEqual(got, expected) } func test_embeddableDependencies_whenHostedTestTarget() throws { // Given let framework = Target.test(name: "Framework", product: .framework) let app = Target.test(name: "App", product: .app) let tests = Target.test(name: "AppTests", product: .unitTests) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [framework]), (target: framework, dependencies: []), (target: tests, dependencies: [app]), ]) // When let result = try graph.embeddableFrameworks(path: projectA.path, name: tests.name) // Then XCTAssertTrue(result.isEmpty) } func test_embeddableDependencies_whenHostedTestTarget_transitiveDepndencies() throws { // Given let framework = Target.test(name: "Framework", product: .framework) let staticFramework = Target.test(name: "StaticFramework", product: .framework) let app = Target.test(name: "App", product: .app) let tests = Target.test(name: "AppTests", product: .unitTests) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: app, dependencies: [staticFramework]), (target: framework, dependencies: []), (target: staticFramework, dependencies: [framework]), (target: tests, dependencies: [app, staticFramework]), ]) // When let result = try graph.embeddableFrameworks(path: projectA.path, name: tests.name) // Then XCTAssertTrue(result.isEmpty) } func test_embeddableDependencies_whenUITest_andAppPrecompiledDepndencies() throws { // Given let precompiledNode = mockDynamicFrameworkNode(at: AbsolutePath("/test/test.framework")) let app = Target.test(name: "App", product: .app) let uiTests = Target.test(name: "AppUITests", product: .uiTests) let project = Project.test(path: "/path/a") let appNode = TargetNode(project: project, target: app, dependencies: [precompiledNode]) let uiTestsNode = TargetNode(project: project, target: uiTests, dependencies: [appNode]) let cache = GraphLoaderCache() cache.add(project: project) cache.add(precompiledNode: precompiledNode) cache.add(targetNode: appNode) cache.add(targetNode: uiTestsNode) let graph = Graph(name: "Graph", entryPath: project.path, cache: cache, entryNodes: [appNode, uiTestsNode]) // When let result = try graph.embeddableFrameworks(path: project.path, name: uiTests.name) // Then XCTAssertTrue(result.isEmpty) } func test_librariesSearchPaths() throws { // Given let target = Target.test(name: "Main") let precompiledNode = LibraryNode.test(path: "/test/test.a", publicHeaders: "/test/public/") let project = Project.test(targets: [target]) let targetNode = TargetNode(project: project, target: target, dependencies: [precompiledNode]) let graph = Graph.test(projects: [project], precompiled: [precompiledNode], targets: [project.path: [targetNode]]) // When let got = graph.librariesSearchPaths(path: project.path, name: target.name) // Then XCTAssertEqual(got, [AbsolutePath("/test")]) } func test_librariesSwiftIncludePaths() throws { // Given let target = Target.test(name: "Main") let precompiledNodeA = LibraryNode.test(path: "/test/test.a", swiftModuleMap: "/test/modules/test.swiftmodulemap") let precompiledNodeB = LibraryNode.test(path: "/test/another.a", swiftModuleMap: nil) let project = Project.test(targets: [target]) let targetNode = TargetNode(project: project, target: target, dependencies: [precompiledNodeA, precompiledNodeB]) let graph = Graph.test(projects: [project], precompiled: [precompiledNodeA, precompiledNodeB], targets: [project.path: [targetNode]]) // When let got = graph.librariesSwiftIncludePaths(path: project.path, name: target.name) // Then XCTAssertEqual(got, [AbsolutePath("/test/modules")]) } func test_resourceBundleDependencies_fromTargetDependency() { // Given let bundle = Target.test(name: "Bundle1", product: .bundle) let app = Target.test(name: "App", product: .bundle) let projectA = Project.test(path: "/path/a") let graph = Graph.create(project: projectA, dependencies: [ (target: bundle, dependencies: []), (target: app, dependencies: [bundle]), ]) // When let result = graph.resourceBundleDependencies(path: projectA.path, name: app.name) // Then XCTAssertEqual(result.map(\.target.name), [ "Bundle1", ]) } func test_resourceBundleDependencies_fromProjectDependency() { // Given let bundle = Target.test(name: "Bundle1", product: .bundle) let projectA = Project.test(path: "/path/a") let app = Target.test(name: "App", product: .app) let projectB = Project.test(path: "/path/b") let graph = Graph.create(projects: [projectA, projectB], dependencies: [ (project: projectA, target: bundle, dependencies: []), (project: projectB, target: app, dependencies: [bundle]), ]) // When let result = graph.resourceBundleDependencies(path: projectB.path, name: app.name) // Then XCTAssertEqual(result.map(\.target.name), [ "Bundle1", ]) } func test_appExtensionDependencies_when_dependencyIsAppExtension() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "AppExtension", product: .appExtension) let project = Project.test(targets: [target]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [ project.path: [targetNode, dependencyNode], ]) let got = graph.appExtensionDependencies(path: project.path, name: target.name) XCTAssertEqual(got.first?.name, "AppExtension") } func test_appExtensionDependencies_when_dependencyIsStickerPackExtension() throws { let target = Target.test(name: "Main") let dependency = Target.test(name: "StickerPackExtension", product: .stickerPackExtension) let project = Project.test(targets: [target]) let dependencyNode = TargetNode(project: project, target: dependency, dependencies: []) let targetNode = TargetNode(project: project, target: target, dependencies: [dependencyNode]) let graph = Graph.test(projects: [project], targets: [ project.path: [targetNode, dependencyNode], ]) let got = graph.appExtensionDependencies(path: project.path, name: target.name) XCTAssertEqual(got.first?.name, "StickerPackExtension") } func test_hostTargetNode_watchApp() { // Given let app = Target.test(name: "App", platform: .iOS, product: .app) let watchApp = Target.test(name: "WatchApp", platform: .watchOS, product: .watch2App) let project = Project.test(path: "/path/a") let graph = Graph.create(project: project, dependencies: [ (target: app, dependencies: [watchApp]), (target: watchApp, dependencies: []), ]) // When let result = graph.hostTargetNodeFor(path: project.path, name: "WatchApp") // Then XCTAssertEqual(result?.target, app) } func test_hostTargetNode_watchAppExtension() { // Given let watchApp = Target.test(name: "WatchApp", platform: .watchOS, product: .watch2App) let watchAppExtension = Target.test(name: "WatchAppExtension", platform: .watchOS, product: .watch2Extension) let project = Project.test(path: "/path/a") let graph = Graph.create(project: project, dependencies: [ (target: watchApp, dependencies: [watchAppExtension]), (target: watchAppExtension, dependencies: []), ]) // When let result = graph.hostTargetNodeFor(path: project.path, name: "WatchAppExtension") // Then XCTAssertEqual(result?.target, watchApp) } func test_encode() { // Given System.shared = System() let project = Project.test() let framework = FrameworkNode.test(path: fixturePath(path: RelativePath("xpm.framework")), architectures: [.x8664, .arm64]) let library = LibraryNode.test(path: fixturePath(path: RelativePath("libStaticLibrary.a")), publicHeaders: fixturePath(path: RelativePath(""))) let target = TargetNode.test(dependencies: [framework, library]) let graph = Graph.test(projects: [project], precompiled: [framework, library], targets: [project.path: [target]]) let expected = """ [ { "product" : "\(target.target.product.rawValue)", "bundle_id" : "\(target.target.bundleId)", "platform" : "\(target.target.platform.rawValue)", "path" : "\(target.path)", "dependencies" : [ "xpm", "libStaticLibrary" ], "name" : "Target", "type" : "source" }, { "path" : "\(library.path)", "architectures" : [ "arm64" ], "product" : "static_library", "name" : "\(library.name)", "type" : "precompiled" }, { "path" : "\(framework.path)", "architectures" : [ "x86_64", "arm64" ], "product" : "framework", "name" : "\(framework.name)", "type" : "precompiled" } ] """ // Then XCTAssertEncodableEqualToJson(graph, expected) } // MARK: - Helpers private func mockDynamicFrameworkNode(at path: AbsolutePath) -> FrameworkNode { let precompiledNode = FrameworkNode.test() let binaryPath = path.appending(component: path.basenameWithoutExt) system.succeedCommand("/usr/bin/file", binaryPath.pathString, output: "dynamically linked") return precompiledNode } private func sdkDependency(from dependency: GraphDependencyReference) -> SDKPathAndStatus? { switch dependency { case let .sdk(path, status): return SDKPathAndStatus(name: path.basename, status: status) default: return nil } } } private struct SDKPathAndStatus: Equatable { var name: String var status: SDKStatus }
45.506849
156
0.550099
8960c4fffb809e67905343896753a09470aca21c
938
// // Careem_Test_ImdbTests.swift // Careem-Test-ImdbTests // // Created by Ali Akhtar on 20/05/2019. // Copyright © 2019 Ali Akhtar. All rights reserved. // import XCTest @testable import Careem_Test_Imdb class Careem_Test_ImdbTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
26.8
111
0.664179
e88bea460a3dcaa99871884a87d4ac7c095b0720
5,000
// // Protocols.swift // SwiftySockets // // Created by Marc Rousavy on 30/08/2017. // Copyright © 2017 mrousavy. All rights reserved. // import Foundation /// /// Representing an error while reading from a Socket stream /// /// - ConnectionClosed: The socket connection was closed /// by one of the endpoints or unexpectedly /// - Timeouted: The read process timeouted /// - NoResponse: No response was received /// public enum SocketReadError: Error { case ConnectionClosed case Timeouted case NoResponse } /// /// Representing an error while writing to a Socket stream /// /// - ConnectionClosed: The socket connection was closed /// by one of the endpoints or unexpectedly /// - Timeouted: The write process timeouted /// - NoListener: No one is listening on the other end /// - NoData: There was no data to write /// public enum SocketWriteError: Error { case ConnectionClosed case Timeouted case NoListener case NoData } /// /// A protocol to buffered-read on a network connection /// public protocol NetReader { /// /// Reads a string from the connection. /// /// - Returns: The read string, or nil if none /// func readString() throws -> String? /// /// Reads all available data into an Data object. /// /// - Parameter data: Data object to contain read data. /// /// - Returns: Integer representing the number of bytes read. /// func read(into data: inout Data) throws -> Int /// /// Reads all available data into an NSMutableData object. /// /// - Parameter data: NSMutableData object to contain read data. /// /// - Returns: Integer representing the number of bytes read. /// func read(into data: NSMutableData) throws -> Int } /// /// A protocol to buffered-write onto a network connection /// public protocol NetWriter { /// /// Writes a string to the connection /// /// - Parameter data: String data to be written. /// /// - Throws: Throws when the write process could not /// be completed because of a connection error /// @discardableResult func write(from data: String) throws -> Int /// /// Writes data from Data object. /// /// - Parameter data: Data object containing the data to be written. /// @discardableResult func write(from data: Data) throws -> Int /// /// Writes data from NSData object. /// /// - Parameter data: NSData object containing the data to be written. /// @discardableResult func write(from data: NSData) throws -> Int } /// /// A protocol to buffered-write and read onto a network connection with SSL en/decryption /// public protocol SSLServiceDelegate { /// /// Initialize SSL Service /// /// - Parameter asServer: True for initializing a server, otherwise a client. /// init(asServer: Bool) throws /// /// Deinitialize SSL Service /// func deinitialize() /// /// Connection accepted callback /// /// - Parameter socket: The associated Socket instance. /// func onAccept(socket: SwiftySocket) throws /// /// Connection established callback /// /// - Parameter socket: The associated Socket instance. /// func onConnect(socket: SwiftySocket) throws /// /// Low level writer /// /// - Parameters: /// - buffer: Buffer pointer. /// - bufSize: Size of the buffer. /// /// - Returns the number of bytes written. /// func send(buffer: UnsafeRawPointer, bufSize: Int) throws -> Int /// /// Low level reader /// /// - Parameters: /// - buffer: Buffer pointer. /// - bufSize: Size of the buffer. /// /// - Returns the number of bytes read. /// func receive(buffer: UnsafeMutableRawPointer, bufSize: Int) throws -> Int #if os(Linux) /// /// Add a protocol to the list of supported ALPN protocol names. E.g. 'http/1.1' and 'h2'. /// /// - Parameters: /// - proto: The protocol name to be added (e.g. 'h2'). /// func addSupportedAlpnProtocol(proto: String) /// /// The negotiated ALPN protocol that has been agreed upon during the handshaking phase. /// Will be nil if ALPN hasn't been used or requestsed protocol is not available. /// var negotiatedAlpnProtocol: String? { get } #endif } /// /// SSL Service Error /// public enum SSLError: Error { /// Retry needed case retryNeeded /// Failure with error code and reason case fail(Int, String) /// The error code itself public var code: Int { switch self { case .retryNeeded: return -1 case .fail(let (code, _)): return Int(code) } } /// Error description public var description: String { switch self { case .retryNeeded: return "Retry operation" case .fail(let (_, reason)): return reason } } }
23.809524
94
0.6152
6a97271f42539ea5538124aab379e52e49ccf3ca
1,745
// // WLSignatureViewModel.swift // ZUserKit // // Created by three stone 王 on 2019/3/17. // Copyright © 2019 three stone 王. All rights reserved. // import Foundation import RxCocoa import RxSwift import WLReqKit import WLBaseViewModel import WLToolsKit class WLSignatureViewModel: WLBaseViewModel { var input: WLInput var output: WLOutput struct WLInput { let orignal: Driver<String> let updated:Driver<String> let completTaps:Signal<Void> } struct WLOutput { let completeEnabled: Driver<Bool> let completing: Driver<Void> let completed: Driver<WLUserResult> } init(_ input: WLInput) { self.input = input let ou = Driver.combineLatest(input.orignal, input.updated) let completEnabled = ou.flatMapLatest { return Driver.just($0.0 != $0.1 && !$0.1.isEmpty && !$0.1.wl_isEmpty) } let completing: Driver<Void> = input.completTaps.flatMap { Driver.just($0) } let completed: Driver<WLUserResult> = input.completTaps .withLatestFrom(input.updated) .flatMapLatest({ return onUserDictResp(WLUserApi.updateUserInfo(WLUserInfoType.signature.updateKey, value: $0)) .mapObject(type: WLUserBean.self) .map { WLUserResult.updateUserInfoSucc($0, msg: WLUserInfoType.signature.title + "修改成功")} .asDriver(onErrorRecover: { return Driver.just(WLUserResult.failed(($0 as! WLBaseError).description.0)) }) }) self.output = WLOutput(completeEnabled: completEnabled, completing: completing, completed: completed) } }
29.083333
129
0.620057
897a313ffcddb6c16ce87b3d5bb9f3c871b6ca4b
458
// // EmptyMovieCell.swift // MovieDemo // // Created by Oscar Vernis on 25/09/20. // Copyright © 2020 Oscar Vernis. All rights reserved. // import UIKit class EmptyMovieCell: UICollectionViewCell { @IBOutlet weak var messageLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(message: NSAttributedString) { messageLabel.attributedText = message } }
19.913043
55
0.679039
e5e99d505e8443c4deb8e0c28d439fca0f374422
1,709
// // CustomTableViewCellOne.swift // UserApplication // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import UIKit import ConstructorAutocomplete class CustomTableViewCellOne: UITableViewCell, CIOAutocompleteCell { @IBOutlet weak var imageViewIcon: UIImageView! @IBOutlet weak var labelText: UILabel! var randomImage: UIImage { var imageNames = ["icon_clock", "icon_error_yellow", "icon_help", "icon_sign_error", "icon_star"] let name = imageNames[Int(arc4random()) % imageNames.count] return UIImage(named: name)! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setup(result: CIOAutocompleteResult, searchTerm: String, highlighter: CIOHighlighter) { if let group = result.group{ let groupString = NSMutableAttributedString() groupString.append(NSAttributedString(string: " in ", attributes: highlighter.attributesProvider.defaultSubstringAttributes())) groupString.append(NSAttributedString(string: group.displayName, attributes: highlighter.attributesProvider.highlightedSubstringAttributes())) self.labelText.attributedText = groupString self.imageViewIcon.image = nil }else{ self.labelText.attributedText = highlighter.highlight(searchTerm: searchTerm, itemTitle: result.result.value) self.imageViewIcon.image = self.randomImage } } }
34.18
154
0.690462
1c719d5e174089aa4ccaa6916e64edc08284a000
239
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b {<a}}{ { class P{ extension{init{ ({{ {{ var _=[[{ class case,
15.933333
87
0.707113
ed07d1036d85ad3a06fce654c14bb2ccdd1cb0e1
145,298
//===----------------------------------------------------------------------===// // // This source file is part of the AWSSDKSwift open source project // // Copyright (c) 2017-2020 the AWSSDKSwift project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of AWSSDKSwift project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/swift-aws/aws-sdk-swift/blob/main/CodeGenerator/Sources/CodeGenerator/main.swift. DO NOT EDIT. import AWSSDKSwiftCore import Foundation extension ElasticsearchService { // MARK: Enums public enum DeploymentStatus: String, CustomStringConvertible, Codable { case pendingUpdate = "PENDING_UPDATE" case inProgress = "IN_PROGRESS" case completed = "COMPLETED" case notEligible = "NOT_ELIGIBLE" case eligible = "ELIGIBLE" public var description: String { return self.rawValue } } public enum DescribePackagesFilterName: String, CustomStringConvertible, Codable { case packageid = "PackageID" case packagename = "PackageName" case packagestatus = "PackageStatus" public var description: String { return self.rawValue } } public enum DomainPackageStatus: String, CustomStringConvertible, Codable { case associating = "ASSOCIATING" case associationFailed = "ASSOCIATION_FAILED" case active = "ACTIVE" case dissociating = "DISSOCIATING" case dissociationFailed = "DISSOCIATION_FAILED" public var description: String { return self.rawValue } } public enum ESPartitionInstanceType: String, CustomStringConvertible, Codable { case m3MediumElasticsearch = "m3.medium.elasticsearch" case m3LargeElasticsearch = "m3.large.elasticsearch" case m3XlargeElasticsearch = "m3.xlarge.elasticsearch" case m32XlargeElasticsearch = "m3.2xlarge.elasticsearch" case m4LargeElasticsearch = "m4.large.elasticsearch" case m4XlargeElasticsearch = "m4.xlarge.elasticsearch" case m42XlargeElasticsearch = "m4.2xlarge.elasticsearch" case m44XlargeElasticsearch = "m4.4xlarge.elasticsearch" case m410XlargeElasticsearch = "m4.10xlarge.elasticsearch" case m5LargeElasticsearch = "m5.large.elasticsearch" case m5XlargeElasticsearch = "m5.xlarge.elasticsearch" case m52XlargeElasticsearch = "m5.2xlarge.elasticsearch" case m54XlargeElasticsearch = "m5.4xlarge.elasticsearch" case m512XlargeElasticsearch = "m5.12xlarge.elasticsearch" case r5LargeElasticsearch = "r5.large.elasticsearch" case r5XlargeElasticsearch = "r5.xlarge.elasticsearch" case r52XlargeElasticsearch = "r5.2xlarge.elasticsearch" case r54XlargeElasticsearch = "r5.4xlarge.elasticsearch" case r512XlargeElasticsearch = "r5.12xlarge.elasticsearch" case c5LargeElasticsearch = "c5.large.elasticsearch" case c5XlargeElasticsearch = "c5.xlarge.elasticsearch" case c52XlargeElasticsearch = "c5.2xlarge.elasticsearch" case c54XlargeElasticsearch = "c5.4xlarge.elasticsearch" case c59XlargeElasticsearch = "c5.9xlarge.elasticsearch" case c518XlargeElasticsearch = "c5.18xlarge.elasticsearch" case ultrawarm1MediumElasticsearch = "ultrawarm1.medium.elasticsearch" case ultrawarm1LargeElasticsearch = "ultrawarm1.large.elasticsearch" case t2MicroElasticsearch = "t2.micro.elasticsearch" case t2SmallElasticsearch = "t2.small.elasticsearch" case t2MediumElasticsearch = "t2.medium.elasticsearch" case r3LargeElasticsearch = "r3.large.elasticsearch" case r3XlargeElasticsearch = "r3.xlarge.elasticsearch" case r32XlargeElasticsearch = "r3.2xlarge.elasticsearch" case r34XlargeElasticsearch = "r3.4xlarge.elasticsearch" case r38XlargeElasticsearch = "r3.8xlarge.elasticsearch" case i2XlargeElasticsearch = "i2.xlarge.elasticsearch" case i22XlargeElasticsearch = "i2.2xlarge.elasticsearch" case d2XlargeElasticsearch = "d2.xlarge.elasticsearch" case d22XlargeElasticsearch = "d2.2xlarge.elasticsearch" case d24XlargeElasticsearch = "d2.4xlarge.elasticsearch" case d28XlargeElasticsearch = "d2.8xlarge.elasticsearch" case c4LargeElasticsearch = "c4.large.elasticsearch" case c4XlargeElasticsearch = "c4.xlarge.elasticsearch" case c42XlargeElasticsearch = "c4.2xlarge.elasticsearch" case c44XlargeElasticsearch = "c4.4xlarge.elasticsearch" case c48XlargeElasticsearch = "c4.8xlarge.elasticsearch" case r4LargeElasticsearch = "r4.large.elasticsearch" case r4XlargeElasticsearch = "r4.xlarge.elasticsearch" case r42XlargeElasticsearch = "r4.2xlarge.elasticsearch" case r44XlargeElasticsearch = "r4.4xlarge.elasticsearch" case r48XlargeElasticsearch = "r4.8xlarge.elasticsearch" case r416XlargeElasticsearch = "r4.16xlarge.elasticsearch" case i3LargeElasticsearch = "i3.large.elasticsearch" case i3XlargeElasticsearch = "i3.xlarge.elasticsearch" case i32XlargeElasticsearch = "i3.2xlarge.elasticsearch" case i34XlargeElasticsearch = "i3.4xlarge.elasticsearch" case i38XlargeElasticsearch = "i3.8xlarge.elasticsearch" case i316XlargeElasticsearch = "i3.16xlarge.elasticsearch" public var description: String { return self.rawValue } } public enum ESWarmPartitionInstanceType: String, CustomStringConvertible, Codable { case ultrawarm1MediumElasticsearch = "ultrawarm1.medium.elasticsearch" case ultrawarm1LargeElasticsearch = "ultrawarm1.large.elasticsearch" public var description: String { return self.rawValue } } public enum InboundCrossClusterSearchConnectionStatusCode: String, CustomStringConvertible, Codable { case pendingAcceptance = "PENDING_ACCEPTANCE" case approved = "APPROVED" case rejecting = "REJECTING" case rejected = "REJECTED" case deleting = "DELETING" case deleted = "DELETED" public var description: String { return self.rawValue } } public enum LogType: String, CustomStringConvertible, Codable { case indexSlowLogs = "INDEX_SLOW_LOGS" case searchSlowLogs = "SEARCH_SLOW_LOGS" case esApplicationLogs = "ES_APPLICATION_LOGS" public var description: String { return self.rawValue } } public enum OptionState: String, CustomStringConvertible, Codable { case requiresindexdocuments = "RequiresIndexDocuments" case processing = "Processing" case active = "Active" public var description: String { return self.rawValue } } public enum OutboundCrossClusterSearchConnectionStatusCode: String, CustomStringConvertible, Codable { case pendingAcceptance = "PENDING_ACCEPTANCE" case validating = "VALIDATING" case validationFailed = "VALIDATION_FAILED" case provisioning = "PROVISIONING" case active = "ACTIVE" case rejected = "REJECTED" case deleting = "DELETING" case deleted = "DELETED" public var description: String { return self.rawValue } } public enum PackageStatus: String, CustomStringConvertible, Codable { case copying = "COPYING" case copyFailed = "COPY_FAILED" case validating = "VALIDATING" case validationFailed = "VALIDATION_FAILED" case available = "AVAILABLE" case deleting = "DELETING" case deleted = "DELETED" case deleteFailed = "DELETE_FAILED" public var description: String { return self.rawValue } } public enum PackageType: String, CustomStringConvertible, Codable { case txtDictionary = "TXT-DICTIONARY" public var description: String { return self.rawValue } } public enum ReservedElasticsearchInstancePaymentOption: String, CustomStringConvertible, Codable { case allUpfront = "ALL_UPFRONT" case partialUpfront = "PARTIAL_UPFRONT" case noUpfront = "NO_UPFRONT" public var description: String { return self.rawValue } } public enum TLSSecurityPolicy: String, CustomStringConvertible, Codable { case policyMinTls10201907 = "Policy-Min-TLS-1-0-2019-07" case policyMinTls12201907 = "Policy-Min-TLS-1-2-2019-07" public var description: String { return self.rawValue } } public enum UpgradeStatus: String, CustomStringConvertible, Codable { case inProgress = "IN_PROGRESS" case succeeded = "SUCCEEDED" case succeededWithIssues = "SUCCEEDED_WITH_ISSUES" case failed = "FAILED" public var description: String { return self.rawValue } } public enum UpgradeStep: String, CustomStringConvertible, Codable { case preUpgradeCheck = "PRE_UPGRADE_CHECK" case snapshot = "SNAPSHOT" case upgrade = "UPGRADE" public var description: String { return self.rawValue } } public enum VolumeType: String, CustomStringConvertible, Codable { case standard = "standard" case gp2 = "gp2" case io1 = "io1" public var description: String { return self.rawValue } } // MARK: Shapes public struct AcceptInboundCrossClusterSearchConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "crossClusterSearchConnectionId", location: .uri(locationName: "ConnectionId")) ] /// The id of the inbound connection that you want to accept. public let crossClusterSearchConnectionId: String public init(crossClusterSearchConnectionId: String) { self.crossClusterSearchConnectionId = crossClusterSearchConnectionId } private enum CodingKeys: CodingKey {} } public struct AcceptInboundCrossClusterSearchConnectionResponse: AWSDecodableShape { /// Specifies the InboundCrossClusterSearchConnection of accepted inbound connection. public let crossClusterSearchConnection: InboundCrossClusterSearchConnection? public init(crossClusterSearchConnection: InboundCrossClusterSearchConnection? = nil) { self.crossClusterSearchConnection = crossClusterSearchConnection } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnection = "CrossClusterSearchConnection" } } public struct AccessPoliciesStatus: AWSDecodableShape { /// The access policy configured for the Elasticsearch domain. Access policies may be resource-based, IP-based, or IAM-based. See Configuring Access Policiesfor more information. public let options: String /// The status of the access policy for the Elasticsearch domain. See OptionStatus for the status information that's included. public let status: OptionStatus public init(options: String, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AddTagsRequest: AWSEncodableShape { /// Specify the ARN for which you want to add the tags. public let arn: String /// List of Tag that need to be added for the Elasticsearch domain. public let tagList: [Tag] public init(arn: String, tagList: [Tag]) { self.arn = arn self.tagList = tagList } public func validate(name: String) throws { try self.tagList.forEach { try $0.validate(name: "\(name).tagList[]") } } private enum CodingKeys: String, CodingKey { case arn = "ARN" case tagList = "TagList" } } public struct AdditionalLimit: AWSDecodableShape { /// Name of Additional Limit is specific to a given InstanceType and for each of it's InstanceRole etc. Attributes and their details: MaximumNumberOfDataNodesSupported This attribute will be present in Master node only to specify how much data nodes upto which given ESPartitionInstanceType can support as master node. MaximumNumberOfDataNodesWithoutMasterNode This attribute will be present in Data node only to specify how much data nodes of given ESPartitionInstanceType upto which you don't need any master nodes to govern them. public let limitName: String? /// Value for given AdditionalLimit$LimitName . public let limitValues: [String]? public init(limitName: String? = nil, limitValues: [String]? = nil) { self.limitName = limitName self.limitValues = limitValues } private enum CodingKeys: String, CodingKey { case limitName = "LimitName" case limitValues = "LimitValues" } } public struct AdvancedOptionsStatus: AWSDecodableShape { /// Specifies the status of advanced options for the specified Elasticsearch domain. public let options: [String: String] /// Specifies the status of OptionStatus for advanced options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: [String: String], status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AdvancedSecurityOptions: AWSDecodableShape { /// True if advanced security is enabled. public let enabled: Bool? /// True if the internal user database is enabled. public let internalUserDatabaseEnabled: Bool? public init(enabled: Bool? = nil, internalUserDatabaseEnabled: Bool? = nil) { self.enabled = enabled self.internalUserDatabaseEnabled = internalUserDatabaseEnabled } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case internalUserDatabaseEnabled = "InternalUserDatabaseEnabled" } } public struct AdvancedSecurityOptionsInput: AWSEncodableShape { /// True if advanced security is enabled. public let enabled: Bool? /// True if the internal user database is enabled. public let internalUserDatabaseEnabled: Bool? /// Credentials for the master user: username and password, ARN, or both. public let masterUserOptions: MasterUserOptions? public init(enabled: Bool? = nil, internalUserDatabaseEnabled: Bool? = nil, masterUserOptions: MasterUserOptions? = nil) { self.enabled = enabled self.internalUserDatabaseEnabled = internalUserDatabaseEnabled self.masterUserOptions = masterUserOptions } public func validate(name: String) throws { try self.masterUserOptions?.validate(name: "\(name).masterUserOptions") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case internalUserDatabaseEnabled = "InternalUserDatabaseEnabled" case masterUserOptions = "MasterUserOptions" } } public struct AdvancedSecurityOptionsStatus: AWSDecodableShape { /// Specifies advanced security options for the specified Elasticsearch domain. public let options: AdvancedSecurityOptions /// Status of the advanced security options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: AdvancedSecurityOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct AssociatePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")), AWSMemberEncoding(label: "packageID", location: .uri(locationName: "PackageID")) ] /// Name of the domain that you want to associate the package with. public let domainName: String /// Internal ID of the package that you want to associate with a domain. Use DescribePackages to find this value. public let packageID: String public init(domainName: String, packageID: String) { self.domainName = domainName self.packageID = packageID } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct AssociatePackageResponse: AWSDecodableShape { /// DomainPackageDetails public let domainPackageDetails: DomainPackageDetails? public init(domainPackageDetails: DomainPackageDetails? = nil) { self.domainPackageDetails = domainPackageDetails } private enum CodingKeys: String, CodingKey { case domainPackageDetails = "DomainPackageDetails" } } public struct CancelElasticsearchServiceSoftwareUpdateRequest: AWSEncodableShape { /// The name of the domain that you want to stop the latest service software update on. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" } } public struct CancelElasticsearchServiceSoftwareUpdateResponse: AWSDecodableShape { /// The current status of the Elasticsearch service software update. public let serviceSoftwareOptions: ServiceSoftwareOptions? public init(serviceSoftwareOptions: ServiceSoftwareOptions? = nil) { self.serviceSoftwareOptions = serviceSoftwareOptions } private enum CodingKeys: String, CodingKey { case serviceSoftwareOptions = "ServiceSoftwareOptions" } } public struct CognitoOptions: AWSEncodableShape & AWSDecodableShape { /// Specifies the option to enable Cognito for Kibana authentication. public let enabled: Bool? /// Specifies the Cognito identity pool ID for Kibana authentication. public let identityPoolId: String? /// Specifies the role ARN that provides Elasticsearch permissions for accessing Cognito resources. public let roleArn: String? /// Specifies the Cognito user pool ID for Kibana authentication. public let userPoolId: String? public init(enabled: Bool? = nil, identityPoolId: String? = nil, roleArn: String? = nil, userPoolId: String? = nil) { self.enabled = enabled self.identityPoolId = identityPoolId self.roleArn = roleArn self.userPoolId = userPoolId } public func validate(name: String) throws { try validate(self.identityPoolId, name: "identityPoolId", parent: name, max: 55) try validate(self.identityPoolId, name: "identityPoolId", parent: name, min: 1) try validate(self.identityPoolId, name: "identityPoolId", parent: name, pattern: "[\\w-]+:[0-9a-f-]+") try validate(self.roleArn, name: "roleArn", parent: name, max: 2048) try validate(self.roleArn, name: "roleArn", parent: name, min: 20) try validate(self.userPoolId, name: "userPoolId", parent: name, max: 55) try validate(self.userPoolId, name: "userPoolId", parent: name, min: 1) try validate(self.userPoolId, name: "userPoolId", parent: name, pattern: "[\\w-]+_[0-9a-zA-Z]+") } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case identityPoolId = "IdentityPoolId" case roleArn = "RoleArn" case userPoolId = "UserPoolId" } } public struct CognitoOptionsStatus: AWSDecodableShape { /// Specifies the Cognito options for the specified Elasticsearch domain. public let options: CognitoOptions /// Specifies the status of the Cognito options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: CognitoOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct CompatibleVersionsMap: AWSDecodableShape { /// The current version of Elasticsearch on which a domain is. public let sourceVersion: String? public let targetVersions: [String]? public init(sourceVersion: String? = nil, targetVersions: [String]? = nil) { self.sourceVersion = sourceVersion self.targetVersions = targetVersions } private enum CodingKeys: String, CodingKey { case sourceVersion = "SourceVersion" case targetVersions = "TargetVersions" } } public struct CreateElasticsearchDomainRequest: AWSEncodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// Option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true. See Configuration Advanced Options for more information. public let advancedOptions: [String: String]? /// Specifies advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptionsInput? /// Options to specify the Cognito user and identity pools for Kibana authentication. For more information, see Amazon Cognito Authentication for Kibana. public let cognitoOptions: CognitoOptions? /// Options to specify configuration that will be applied to the domain endpoint. public let domainEndpointOptions: DomainEndpointOptions? /// The name of the Elasticsearch domain that you are creating. Domain names are unique across the domains owned by an account within an AWS region. Domain names must start with a lowercase letter and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). public let domainName: String /// Options to enable, disable and specify the type and size of EBS storage volumes. public let eBSOptions: EBSOptions? /// Configuration options for an Elasticsearch domain. Specifies the instance type and number of instances in the domain cluster. public let elasticsearchClusterConfig: ElasticsearchClusterConfig? /// String of format X.Y to specify version for the Elasticsearch domain eg. "1.5" or "2.3". For more information, see Creating Elasticsearch Domains in the Amazon Elasticsearch Service Developer Guide. public let elasticsearchVersion: String? /// Specifies the Encryption At Rest Options. public let encryptionAtRestOptions: EncryptionAtRestOptions? /// Map of LogType and LogPublishingOption, each containing options to publish a given type of Elasticsearch log. public let logPublishingOptions: [LogType: LogPublishingOption]? /// Specifies the NodeToNodeEncryptionOptions. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? /// Option to set time, in UTC format, of the daily automated snapshot. Default value is 0 hours. public let snapshotOptions: SnapshotOptions? /// Options to specify the subnets and security groups for VPC endpoint. For more information, see Creating a VPC in VPC Endpoints for Amazon Elasticsearch Service Domains public let vPCOptions: VPCOptions? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptionsInput? = nil, cognitoOptions: CognitoOptions? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainName: String, eBSOptions: EBSOptions? = nil, elasticsearchClusterConfig: ElasticsearchClusterConfig? = nil, elasticsearchVersion: String? = nil, encryptionAtRestOptions: EncryptionAtRestOptions? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? = nil, snapshotOptions: SnapshotOptions? = nil, vPCOptions: VPCOptions? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.domainName = domainName self.eBSOptions = eBSOptions self.elasticsearchClusterConfig = elasticsearchClusterConfig self.elasticsearchVersion = elasticsearchVersion self.encryptionAtRestOptions = encryptionAtRestOptions self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.snapshotOptions = snapshotOptions self.vPCOptions = vPCOptions } public func validate(name: String) throws { try self.advancedSecurityOptions?.validate(name: "\(name).advancedSecurityOptions") try self.cognitoOptions?.validate(name: "\(name).cognitoOptions") try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try self.encryptionAtRestOptions?.validate(name: "\(name).encryptionAtRestOptions") } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case domainName = "DomainName" case eBSOptions = "EBSOptions" case elasticsearchClusterConfig = "ElasticsearchClusterConfig" case elasticsearchVersion = "ElasticsearchVersion" case encryptionAtRestOptions = "EncryptionAtRestOptions" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case snapshotOptions = "SnapshotOptions" case vPCOptions = "VPCOptions" } } public struct CreateElasticsearchDomainResponse: AWSDecodableShape { /// The status of the newly created Elasticsearch domain. public let domainStatus: ElasticsearchDomainStatus? public init(domainStatus: ElasticsearchDomainStatus? = nil) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct CreateOutboundCrossClusterSearchConnectionRequest: AWSEncodableShape { /// Specifies the connection alias that will be used by the customer for this connection. public let connectionAlias: String /// Specifies the DomainInformation for the destination Elasticsearch domain. public let destinationDomainInfo: DomainInformation /// Specifies the DomainInformation for the source Elasticsearch domain. public let sourceDomainInfo: DomainInformation public init(connectionAlias: String, destinationDomainInfo: DomainInformation, sourceDomainInfo: DomainInformation) { self.connectionAlias = connectionAlias self.destinationDomainInfo = destinationDomainInfo self.sourceDomainInfo = sourceDomainInfo } public func validate(name: String) throws { try validate(self.connectionAlias, name: "connectionAlias", parent: name, max: 20) try self.destinationDomainInfo.validate(name: "\(name).destinationDomainInfo") try self.sourceDomainInfo.validate(name: "\(name).sourceDomainInfo") } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case destinationDomainInfo = "DestinationDomainInfo" case sourceDomainInfo = "SourceDomainInfo" } } public struct CreateOutboundCrossClusterSearchConnectionResponse: AWSDecodableShape { /// Specifies the connection alias provided during the create connection request. public let connectionAlias: String? /// Specifies the OutboundCrossClusterSearchConnectionStatus for the newly created connection. public let connectionStatus: OutboundCrossClusterSearchConnectionStatus? /// Unique id for the created outbound connection, which is used for subsequent operations on connection. public let crossClusterSearchConnectionId: String? /// Specifies the DomainInformation for the destination Elasticsearch domain. public let destinationDomainInfo: DomainInformation? /// Specifies the DomainInformation for the source Elasticsearch domain. public let sourceDomainInfo: DomainInformation? public init(connectionAlias: String? = nil, connectionStatus: OutboundCrossClusterSearchConnectionStatus? = nil, crossClusterSearchConnectionId: String? = nil, destinationDomainInfo: DomainInformation? = nil, sourceDomainInfo: DomainInformation? = nil) { self.connectionAlias = connectionAlias self.connectionStatus = connectionStatus self.crossClusterSearchConnectionId = crossClusterSearchConnectionId self.destinationDomainInfo = destinationDomainInfo self.sourceDomainInfo = sourceDomainInfo } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case connectionStatus = "ConnectionStatus" case crossClusterSearchConnectionId = "CrossClusterSearchConnectionId" case destinationDomainInfo = "DestinationDomainInfo" case sourceDomainInfo = "SourceDomainInfo" } } public struct CreatePackageRequest: AWSEncodableShape { /// Description of the package. public let packageDescription: String? /// Unique identifier for the package. public let packageName: String /// The customer S3 location PackageSource for importing the package. public let packageSource: PackageSource /// Type of package. Currently supports only TXT-DICTIONARY. public let packageType: PackageType public init(packageDescription: String? = nil, packageName: String, packageSource: PackageSource, packageType: PackageType) { self.packageDescription = packageDescription self.packageName = packageName self.packageSource = packageSource self.packageType = packageType } public func validate(name: String) throws { try validate(self.packageDescription, name: "packageDescription", parent: name, max: 1024) try validate(self.packageName, name: "packageName", parent: name, max: 28) try validate(self.packageName, name: "packageName", parent: name, min: 3) try validate(self.packageName, name: "packageName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try self.packageSource.validate(name: "\(name).packageSource") } private enum CodingKeys: String, CodingKey { case packageDescription = "PackageDescription" case packageName = "PackageName" case packageSource = "PackageSource" case packageType = "PackageType" } } public struct CreatePackageResponse: AWSDecodableShape { /// Information about the package PackageDetails. public let packageDetails: PackageDetails? public init(packageDetails: PackageDetails? = nil) { self.packageDetails = packageDetails } private enum CodingKeys: String, CodingKey { case packageDetails = "PackageDetails" } } public struct DeleteElasticsearchDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")) ] /// The name of the Elasticsearch domain that you want to permanently delete. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct DeleteElasticsearchDomainResponse: AWSDecodableShape { /// The status of the Elasticsearch domain being deleted. public let domainStatus: ElasticsearchDomainStatus? public init(domainStatus: ElasticsearchDomainStatus? = nil) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct DeleteInboundCrossClusterSearchConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "crossClusterSearchConnectionId", location: .uri(locationName: "ConnectionId")) ] /// The id of the inbound connection that you want to permanently delete. public let crossClusterSearchConnectionId: String public init(crossClusterSearchConnectionId: String) { self.crossClusterSearchConnectionId = crossClusterSearchConnectionId } private enum CodingKeys: CodingKey {} } public struct DeleteInboundCrossClusterSearchConnectionResponse: AWSDecodableShape { /// Specifies the InboundCrossClusterSearchConnection of deleted inbound connection. public let crossClusterSearchConnection: InboundCrossClusterSearchConnection? public init(crossClusterSearchConnection: InboundCrossClusterSearchConnection? = nil) { self.crossClusterSearchConnection = crossClusterSearchConnection } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnection = "CrossClusterSearchConnection" } } public struct DeleteOutboundCrossClusterSearchConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "crossClusterSearchConnectionId", location: .uri(locationName: "ConnectionId")) ] /// The id of the outbound connection that you want to permanently delete. public let crossClusterSearchConnectionId: String public init(crossClusterSearchConnectionId: String) { self.crossClusterSearchConnectionId = crossClusterSearchConnectionId } private enum CodingKeys: CodingKey {} } public struct DeleteOutboundCrossClusterSearchConnectionResponse: AWSDecodableShape { /// Specifies the OutboundCrossClusterSearchConnection of deleted outbound connection. public let crossClusterSearchConnection: OutboundCrossClusterSearchConnection? public init(crossClusterSearchConnection: OutboundCrossClusterSearchConnection? = nil) { self.crossClusterSearchConnection = crossClusterSearchConnection } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnection = "CrossClusterSearchConnection" } } public struct DeletePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "packageID", location: .uri(locationName: "PackageID")) ] /// Internal ID of the package that you want to delete. Use DescribePackages to find this value. public let packageID: String public init(packageID: String) { self.packageID = packageID } private enum CodingKeys: CodingKey {} } public struct DeletePackageResponse: AWSDecodableShape { /// PackageDetails public let packageDetails: PackageDetails? public init(packageDetails: PackageDetails? = nil) { self.packageDetails = packageDetails } private enum CodingKeys: String, CodingKey { case packageDetails = "PackageDetails" } } public struct DescribeElasticsearchDomainConfigRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")) ] /// The Elasticsearch domain that you want to get information about. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeElasticsearchDomainConfigResponse: AWSDecodableShape { /// The configuration information of the domain requested in the DescribeElasticsearchDomainConfig request. public let domainConfig: ElasticsearchDomainConfig public init(domainConfig: ElasticsearchDomainConfig) { self.domainConfig = domainConfig } private enum CodingKeys: String, CodingKey { case domainConfig = "DomainConfig" } } public struct DescribeElasticsearchDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")) ] /// The name of the Elasticsearch domain for which you want information. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeElasticsearchDomainResponse: AWSDecodableShape { /// The current status of the Elasticsearch domain. public let domainStatus: ElasticsearchDomainStatus public init(domainStatus: ElasticsearchDomainStatus) { self.domainStatus = domainStatus } private enum CodingKeys: String, CodingKey { case domainStatus = "DomainStatus" } } public struct DescribeElasticsearchDomainsRequest: AWSEncodableShape { /// The Elasticsearch domains for which you want information. public let domainNames: [String] public init(domainNames: [String]) { self.domainNames = domainNames } public func validate(name: String) throws { try self.domainNames.forEach { try validate($0, name: "domainNames[]", parent: name, max: 28) try validate($0, name: "domainNames[]", parent: name, min: 3) try validate($0, name: "domainNames[]", parent: name, pattern: "[a-z][a-z0-9\\-]+") } } private enum CodingKeys: String, CodingKey { case domainNames = "DomainNames" } } public struct DescribeElasticsearchDomainsResponse: AWSDecodableShape { /// The status of the domains requested in the DescribeElasticsearchDomains request. public let domainStatusList: [ElasticsearchDomainStatus] public init(domainStatusList: [ElasticsearchDomainStatus]) { self.domainStatusList = domainStatusList } private enum CodingKeys: String, CodingKey { case domainStatusList = "DomainStatusList" } } public struct DescribeElasticsearchInstanceTypeLimitsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring(locationName: "domainName")), AWSMemberEncoding(label: "elasticsearchVersion", location: .uri(locationName: "ElasticsearchVersion")), AWSMemberEncoding(label: "instanceType", location: .uri(locationName: "InstanceType")) ] /// DomainName represents the name of the Domain that we are trying to modify. This should be present only if we are querying for Elasticsearch Limits for existing domain. public let domainName: String? /// Version of Elasticsearch for which Limits are needed. public let elasticsearchVersion: String /// The instance type for an Elasticsearch cluster for which Elasticsearch Limits are needed. public let instanceType: ESPartitionInstanceType public init(domainName: String? = nil, elasticsearchVersion: String, instanceType: ESPartitionInstanceType) { self.domainName = domainName self.elasticsearchVersion = elasticsearchVersion self.instanceType = instanceType } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct DescribeElasticsearchInstanceTypeLimitsResponse: AWSDecodableShape { public let limitsByRole: [String: Limits]? public init(limitsByRole: [String: Limits]? = nil) { self.limitsByRole = limitsByRole } private enum CodingKeys: String, CodingKey { case limitsByRole = "LimitsByRole" } } public struct DescribeInboundCrossClusterSearchConnectionsRequest: AWSEncodableShape { /// A list of filters used to match properties for inbound cross-cluster search connection. Available Filter names for this operation are: cross-cluster-search-connection-id source-domain-info.domain-name source-domain-info.owner-id source-domain-info.region destination-domain-info.domain-name public let filters: [Filter]? /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken is sent in case the earlier API call results contain the NextToken. It is used for pagination. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeInboundCrossClusterSearchConnectionsResponse: AWSDecodableShape { /// Consists of list of InboundCrossClusterSearchConnection matching the specified filter criteria. public let crossClusterSearchConnections: [InboundCrossClusterSearchConnection]? /// If more results are available and NextToken is present, make the next request to the same API with the received NextToken to paginate the remaining results. public let nextToken: String? public init(crossClusterSearchConnections: [InboundCrossClusterSearchConnection]? = nil, nextToken: String? = nil) { self.crossClusterSearchConnections = crossClusterSearchConnections self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnections = "CrossClusterSearchConnections" case nextToken = "NextToken" } } public struct DescribeOutboundCrossClusterSearchConnectionsRequest: AWSEncodableShape { /// A list of filters used to match properties for outbound cross-cluster search connection. Available Filter names for this operation are: cross-cluster-search-connection-id destination-domain-info.domain-name destination-domain-info.owner-id destination-domain-info.region source-domain-info.domain-name public let filters: [Filter]? /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken is sent in case the earlier API call results contain the NextToken. It is used for pagination. public let nextToken: String? public init(filters: [Filter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribeOutboundCrossClusterSearchConnectionsResponse: AWSDecodableShape { /// Consists of list of OutboundCrossClusterSearchConnection matching the specified filter criteria. public let crossClusterSearchConnections: [OutboundCrossClusterSearchConnection]? /// If more results are available and NextToken is present, make the next request to the same API with the received NextToken to paginate the remaining results. public let nextToken: String? public init(crossClusterSearchConnections: [OutboundCrossClusterSearchConnection]? = nil, nextToken: String? = nil) { self.crossClusterSearchConnections = crossClusterSearchConnections self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnections = "CrossClusterSearchConnections" case nextToken = "NextToken" } } public struct DescribePackagesFilter: AWSEncodableShape { /// Any field from PackageDetails. public let name: DescribePackagesFilterName? /// A list of values for the specified field. public let value: [String]? public init(name: DescribePackagesFilterName? = nil, value: [String]? = nil) { self.name = name self.value = value } public func validate(name: String) throws { try self.value?.forEach { try validate($0, name: "value[]", parent: name, pattern: "^[0-9a-zA-Z\\*\\.\\\\/\\?-]*$") } } private enum CodingKeys: String, CodingKey { case name = "Name" case value = "Value" } } public struct DescribePackagesRequest: AWSEncodableShape { /// Only returns packages that match the DescribePackagesFilterList values. public let filters: [DescribePackagesFilter]? /// Limits results to a maximum number of packages. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? public init(filters: [DescribePackagesFilter]? = nil, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: String, CodingKey { case filters = "Filters" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct DescribePackagesResponse: AWSDecodableShape { public let nextToken: String? /// List of PackageDetails objects. public let packageDetailsList: [PackageDetails]? public init(nextToken: String? = nil, packageDetailsList: [PackageDetails]? = nil) { self.nextToken = nextToken self.packageDetailsList = packageDetailsList } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case packageDetailsList = "PackageDetailsList" } } public struct DescribeReservedElasticsearchInstanceOfferingsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "reservedElasticsearchInstanceOfferingId", location: .querystring(locationName: "offeringId")) ] /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken should be sent in case if earlier API call produced result containing NextToken. It is used for pagination. public let nextToken: String? /// The offering identifier filter value. Use this parameter to show only the available offering that matches the specified reservation identifier. public let reservedElasticsearchInstanceOfferingId: String? public init(maxResults: Int? = nil, nextToken: String? = nil, reservedElasticsearchInstanceOfferingId: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.reservedElasticsearchInstanceOfferingId = reservedElasticsearchInstanceOfferingId } public func validate(name: String) throws { try validate(self.maxResults, name: "maxResults", parent: name, max: 100) try validate(self.reservedElasticsearchInstanceOfferingId, name: "reservedElasticsearchInstanceOfferingId", parent: name, pattern: "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}") } private enum CodingKeys: CodingKey {} } public struct DescribeReservedElasticsearchInstanceOfferingsResponse: AWSDecodableShape { /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// List of reserved Elasticsearch instance offerings public let reservedElasticsearchInstanceOfferings: [ReservedElasticsearchInstanceOffering]? public init(nextToken: String? = nil, reservedElasticsearchInstanceOfferings: [ReservedElasticsearchInstanceOffering]? = nil) { self.nextToken = nextToken self.reservedElasticsearchInstanceOfferings = reservedElasticsearchInstanceOfferings } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case reservedElasticsearchInstanceOfferings = "ReservedElasticsearchInstanceOfferings" } } public struct DescribeReservedElasticsearchInstancesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "reservedElasticsearchInstanceId", location: .querystring(locationName: "reservationId")) ] /// Set this value to limit the number of results returned. If not specified, defaults to 100. public let maxResults: Int? /// NextToken should be sent in case if earlier API call produced result containing NextToken. It is used for pagination. public let nextToken: String? /// The reserved instance identifier filter value. Use this parameter to show only the reservation that matches the specified reserved Elasticsearch instance ID. public let reservedElasticsearchInstanceId: String? public init(maxResults: Int? = nil, nextToken: String? = nil, reservedElasticsearchInstanceId: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken self.reservedElasticsearchInstanceId = reservedElasticsearchInstanceId } public func validate(name: String) throws { try validate(self.maxResults, name: "maxResults", parent: name, max: 100) try validate(self.reservedElasticsearchInstanceId, name: "reservedElasticsearchInstanceId", parent: name, pattern: "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}") } private enum CodingKeys: CodingKey {} } public struct DescribeReservedElasticsearchInstancesResponse: AWSDecodableShape { /// Provides an identifier to allow retrieval of paginated results. public let nextToken: String? /// List of reserved Elasticsearch instances. public let reservedElasticsearchInstances: [ReservedElasticsearchInstance]? public init(nextToken: String? = nil, reservedElasticsearchInstances: [ReservedElasticsearchInstance]? = nil) { self.nextToken = nextToken self.reservedElasticsearchInstances = reservedElasticsearchInstances } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case reservedElasticsearchInstances = "ReservedElasticsearchInstances" } } public struct DissociatePackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")), AWSMemberEncoding(label: "packageID", location: .uri(locationName: "PackageID")) ] /// Name of the domain that you want to associate the package with. public let domainName: String /// Internal ID of the package that you want to associate with a domain. Use DescribePackages to find this value. public let packageID: String public init(domainName: String, packageID: String) { self.domainName = domainName self.packageID = packageID } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct DissociatePackageResponse: AWSDecodableShape { /// DomainPackageDetails public let domainPackageDetails: DomainPackageDetails? public init(domainPackageDetails: DomainPackageDetails? = nil) { self.domainPackageDetails = domainPackageDetails } private enum CodingKeys: String, CodingKey { case domainPackageDetails = "DomainPackageDetails" } } public struct DomainEndpointOptions: AWSEncodableShape & AWSDecodableShape { /// Specify if only HTTPS endpoint should be enabled for the Elasticsearch domain. public let enforceHTTPS: Bool? /// Specify the TLS security policy that needs to be applied to the HTTPS endpoint of Elasticsearch domain. It can be one of the following values: Policy-Min-TLS-1-0-2019-07: TLS security policy which supports TLSv1.0 and higher. Policy-Min-TLS-1-2-2019-07: TLS security policy which supports only TLSv1.2 public let tLSSecurityPolicy: TLSSecurityPolicy? public init(enforceHTTPS: Bool? = nil, tLSSecurityPolicy: TLSSecurityPolicy? = nil) { self.enforceHTTPS = enforceHTTPS self.tLSSecurityPolicy = tLSSecurityPolicy } private enum CodingKeys: String, CodingKey { case enforceHTTPS = "EnforceHTTPS" case tLSSecurityPolicy = "TLSSecurityPolicy" } } public struct DomainEndpointOptionsStatus: AWSDecodableShape { /// Options to configure endpoint for the Elasticsearch domain. public let options: DomainEndpointOptions /// The status of the endpoint options for the Elasticsearch domain. See OptionStatus for the status information that's included. public let status: OptionStatus public init(options: DomainEndpointOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct DomainInfo: AWSDecodableShape { /// Specifies the DomainName. public let domainName: String? public init(domainName: String? = nil) { self.domainName = domainName } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" } } public struct DomainInformation: AWSEncodableShape & AWSDecodableShape { public let domainName: String public let ownerId: String? public let region: String? public init(domainName: String, ownerId: String? = nil, region: String? = nil) { self.domainName = domainName self.ownerId = ownerId self.region = region } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try validate(self.ownerId, name: "ownerId", parent: name, max: 12) try validate(self.ownerId, name: "ownerId", parent: name, min: 12) } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case ownerId = "OwnerId" case region = "Region" } } public struct DomainPackageDetails: AWSDecodableShape { /// Name of the domain you've associated a package with. public let domainName: String? /// State of the association. Values are ASSOCIATING/ASSOCIATION_FAILED/ACTIVE/DISSOCIATING/DISSOCIATION_FAILED. public let domainPackageStatus: DomainPackageStatus? /// Additional information if the package is in an error state. Null otherwise. public let errorDetails: ErrorDetails? /// Timestamp of the most-recent update to the association status. public let lastUpdated: TimeStamp? /// Internal ID of the package. public let packageID: String? /// User specified name of the package. public let packageName: String? /// Currently supports only TXT-DICTIONARY. public let packageType: PackageType? /// The relative path on Amazon ES nodes, which can be used as synonym_path when the package is synonym file. public let referencePath: String? public init(domainName: String? = nil, domainPackageStatus: DomainPackageStatus? = nil, errorDetails: ErrorDetails? = nil, lastUpdated: TimeStamp? = nil, packageID: String? = nil, packageName: String? = nil, packageType: PackageType? = nil, referencePath: String? = nil) { self.domainName = domainName self.domainPackageStatus = domainPackageStatus self.errorDetails = errorDetails self.lastUpdated = lastUpdated self.packageID = packageID self.packageName = packageName self.packageType = packageType self.referencePath = referencePath } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case domainPackageStatus = "DomainPackageStatus" case errorDetails = "ErrorDetails" case lastUpdated = "LastUpdated" case packageID = "PackageID" case packageName = "PackageName" case packageType = "PackageType" case referencePath = "ReferencePath" } } public struct EBSOptions: AWSEncodableShape & AWSDecodableShape { /// Specifies whether EBS-based storage is enabled. public let eBSEnabled: Bool? /// Specifies the IOPD for a Provisioned IOPS EBS volume (SSD). public let iops: Int? /// Integer to specify the size of an EBS volume. public let volumeSize: Int? /// Specifies the volume type for EBS-based storage. public let volumeType: VolumeType? public init(eBSEnabled: Bool? = nil, iops: Int? = nil, volumeSize: Int? = nil, volumeType: VolumeType? = nil) { self.eBSEnabled = eBSEnabled self.iops = iops self.volumeSize = volumeSize self.volumeType = volumeType } private enum CodingKeys: String, CodingKey { case eBSEnabled = "EBSEnabled" case iops = "Iops" case volumeSize = "VolumeSize" case volumeType = "VolumeType" } } public struct EBSOptionsStatus: AWSDecodableShape { /// Specifies the EBS options for the specified Elasticsearch domain. public let options: EBSOptions /// Specifies the status of the EBS options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: EBSOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ElasticsearchClusterConfig: AWSEncodableShape & AWSDecodableShape { /// Total number of dedicated master nodes, active and on standby, for the cluster. public let dedicatedMasterCount: Int? /// A boolean value to indicate whether a dedicated master node is enabled. See About Dedicated Master Nodes for more information. public let dedicatedMasterEnabled: Bool? /// The instance type for a dedicated master node. public let dedicatedMasterType: ESPartitionInstanceType? /// The number of instances in the specified domain cluster. public let instanceCount: Int? /// The instance type for an Elasticsearch cluster. UltraWarm instance types are not supported for data instances. public let instanceType: ESPartitionInstanceType? /// The number of warm nodes in the cluster. public let warmCount: Int? /// True to enable warm storage. public let warmEnabled: Bool? /// The instance type for the Elasticsearch cluster's warm nodes. public let warmType: ESWarmPartitionInstanceType? /// Specifies the zone awareness configuration for a domain when zone awareness is enabled. public let zoneAwarenessConfig: ZoneAwarenessConfig? /// A boolean value to indicate whether zone awareness is enabled. See About Zone Awareness for more information. public let zoneAwarenessEnabled: Bool? public init(dedicatedMasterCount: Int? = nil, dedicatedMasterEnabled: Bool? = nil, dedicatedMasterType: ESPartitionInstanceType? = nil, instanceCount: Int? = nil, instanceType: ESPartitionInstanceType? = nil, warmCount: Int? = nil, warmEnabled: Bool? = nil, warmType: ESWarmPartitionInstanceType? = nil, zoneAwarenessConfig: ZoneAwarenessConfig? = nil, zoneAwarenessEnabled: Bool? = nil) { self.dedicatedMasterCount = dedicatedMasterCount self.dedicatedMasterEnabled = dedicatedMasterEnabled self.dedicatedMasterType = dedicatedMasterType self.instanceCount = instanceCount self.instanceType = instanceType self.warmCount = warmCount self.warmEnabled = warmEnabled self.warmType = warmType self.zoneAwarenessConfig = zoneAwarenessConfig self.zoneAwarenessEnabled = zoneAwarenessEnabled } private enum CodingKeys: String, CodingKey { case dedicatedMasterCount = "DedicatedMasterCount" case dedicatedMasterEnabled = "DedicatedMasterEnabled" case dedicatedMasterType = "DedicatedMasterType" case instanceCount = "InstanceCount" case instanceType = "InstanceType" case warmCount = "WarmCount" case warmEnabled = "WarmEnabled" case warmType = "WarmType" case zoneAwarenessConfig = "ZoneAwarenessConfig" case zoneAwarenessEnabled = "ZoneAwarenessEnabled" } } public struct ElasticsearchClusterConfigStatus: AWSDecodableShape { /// Specifies the cluster configuration for the specified Elasticsearch domain. public let options: ElasticsearchClusterConfig /// Specifies the status of the configuration for the specified Elasticsearch domain. public let status: OptionStatus public init(options: ElasticsearchClusterConfig, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ElasticsearchDomainConfig: AWSDecodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: AccessPoliciesStatus? /// Specifies the AdvancedOptions for the domain. See Configuring Advanced Options for more information. public let advancedOptions: AdvancedOptionsStatus? /// Specifies AdvancedSecurityOptions for the domain. public let advancedSecurityOptions: AdvancedSecurityOptionsStatus? /// The CognitoOptions for the specified domain. For more information, see Amazon Cognito Authentication for Kibana. public let cognitoOptions: CognitoOptionsStatus? /// Specifies the DomainEndpointOptions for the Elasticsearch domain. public let domainEndpointOptions: DomainEndpointOptionsStatus? /// Specifies the EBSOptions for the Elasticsearch domain. public let eBSOptions: EBSOptionsStatus? /// Specifies the ElasticsearchClusterConfig for the Elasticsearch domain. public let elasticsearchClusterConfig: ElasticsearchClusterConfigStatus? /// String of format X.Y to specify version for the Elasticsearch domain. public let elasticsearchVersion: ElasticsearchVersionStatus? /// Specifies the EncryptionAtRestOptions for the Elasticsearch domain. public let encryptionAtRestOptions: EncryptionAtRestOptionsStatus? /// Log publishing options for the given domain. public let logPublishingOptions: LogPublishingOptionsStatus? /// Specifies the NodeToNodeEncryptionOptions for the Elasticsearch domain. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptionsStatus? /// Specifies the SnapshotOptions for the Elasticsearch domain. public let snapshotOptions: SnapshotOptionsStatus? /// The VPCOptions for the specified domain. For more information, see VPC Endpoints for Amazon Elasticsearch Service Domains. public let vPCOptions: VPCDerivedInfoStatus? public init(accessPolicies: AccessPoliciesStatus? = nil, advancedOptions: AdvancedOptionsStatus? = nil, advancedSecurityOptions: AdvancedSecurityOptionsStatus? = nil, cognitoOptions: CognitoOptionsStatus? = nil, domainEndpointOptions: DomainEndpointOptionsStatus? = nil, eBSOptions: EBSOptionsStatus? = nil, elasticsearchClusterConfig: ElasticsearchClusterConfigStatus? = nil, elasticsearchVersion: ElasticsearchVersionStatus? = nil, encryptionAtRestOptions: EncryptionAtRestOptionsStatus? = nil, logPublishingOptions: LogPublishingOptionsStatus? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptionsStatus? = nil, snapshotOptions: SnapshotOptionsStatus? = nil, vPCOptions: VPCDerivedInfoStatus? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.eBSOptions = eBSOptions self.elasticsearchClusterConfig = elasticsearchClusterConfig self.elasticsearchVersion = elasticsearchVersion self.encryptionAtRestOptions = encryptionAtRestOptions self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.snapshotOptions = snapshotOptions self.vPCOptions = vPCOptions } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case eBSOptions = "EBSOptions" case elasticsearchClusterConfig = "ElasticsearchClusterConfig" case elasticsearchVersion = "ElasticsearchVersion" case encryptionAtRestOptions = "EncryptionAtRestOptions" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case snapshotOptions = "SnapshotOptions" case vPCOptions = "VPCOptions" } } public struct ElasticsearchDomainStatus: AWSDecodableShape { /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// Specifies the status of the AdvancedOptions public let advancedOptions: [String: String]? /// The current status of the Elasticsearch domain's advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptions? /// The Amazon resource name (ARN) of an Elasticsearch domain. See Identifiers for IAM Entities in Using AWS Identity and Access Management for more information. public let arn: String /// The CognitoOptions for the specified domain. For more information, see Amazon Cognito Authentication for Kibana. public let cognitoOptions: CognitoOptions? /// The domain creation status. True if the creation of an Elasticsearch domain is complete. False if domain creation is still in progress. public let created: Bool? /// The domain deletion status. True if a delete request has been received for the domain but resource cleanup is still in progress. False if the domain has not been deleted. Once domain deletion is complete, the status of the domain is no longer returned. public let deleted: Bool? /// The current status of the Elasticsearch domain's endpoint options. public let domainEndpointOptions: DomainEndpointOptions? /// The unique identifier for the specified Elasticsearch domain. public let domainId: String /// The name of an Elasticsearch domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen). public let domainName: String /// The EBSOptions for the specified domain. See Configuring EBS-based Storage for more information. public let eBSOptions: EBSOptions? /// The type and number of instances in the domain cluster. public let elasticsearchClusterConfig: ElasticsearchClusterConfig public let elasticsearchVersion: String? /// Specifies the status of the EncryptionAtRestOptions. public let encryptionAtRestOptions: EncryptionAtRestOptions? /// The Elasticsearch domain endpoint that you use to submit index and search requests. public let endpoint: String? /// Map containing the Elasticsearch domain endpoints used to submit index and search requests. Example key, value: 'vpc','vpc-endpoint-h2dsd34efgyghrtguk5gt6j2foh4.us-east-1.es.amazonaws.com'. public let endpoints: [String: String]? /// Log publishing options for the given domain. public let logPublishingOptions: [LogType: LogPublishingOption]? /// Specifies the status of the NodeToNodeEncryptionOptions. public let nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? /// The status of the Elasticsearch domain configuration. True if Amazon Elasticsearch Service is processing configuration changes. False if the configuration is active. public let processing: Bool? /// The current status of the Elasticsearch domain's service software. public let serviceSoftwareOptions: ServiceSoftwareOptions? /// Specifies the status of the SnapshotOptions public let snapshotOptions: SnapshotOptions? /// The status of an Elasticsearch domain version upgrade. True if Amazon Elasticsearch Service is undergoing a version upgrade. False if the configuration is active. public let upgradeProcessing: Bool? /// The VPCOptions for the specified domain. For more information, see VPC Endpoints for Amazon Elasticsearch Service Domains. public let vPCOptions: VPCDerivedInfo? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptions? = nil, arn: String, cognitoOptions: CognitoOptions? = nil, created: Bool? = nil, deleted: Bool? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainId: String, domainName: String, eBSOptions: EBSOptions? = nil, elasticsearchClusterConfig: ElasticsearchClusterConfig, elasticsearchVersion: String? = nil, encryptionAtRestOptions: EncryptionAtRestOptions? = nil, endpoint: String? = nil, endpoints: [String: String]? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, nodeToNodeEncryptionOptions: NodeToNodeEncryptionOptions? = nil, processing: Bool? = nil, serviceSoftwareOptions: ServiceSoftwareOptions? = nil, snapshotOptions: SnapshotOptions? = nil, upgradeProcessing: Bool? = nil, vPCOptions: VPCDerivedInfo? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.arn = arn self.cognitoOptions = cognitoOptions self.created = created self.deleted = deleted self.domainEndpointOptions = domainEndpointOptions self.domainId = domainId self.domainName = domainName self.eBSOptions = eBSOptions self.elasticsearchClusterConfig = elasticsearchClusterConfig self.elasticsearchVersion = elasticsearchVersion self.encryptionAtRestOptions = encryptionAtRestOptions self.endpoint = endpoint self.endpoints = endpoints self.logPublishingOptions = logPublishingOptions self.nodeToNodeEncryptionOptions = nodeToNodeEncryptionOptions self.processing = processing self.serviceSoftwareOptions = serviceSoftwareOptions self.snapshotOptions = snapshotOptions self.upgradeProcessing = upgradeProcessing self.vPCOptions = vPCOptions } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case arn = "ARN" case cognitoOptions = "CognitoOptions" case created = "Created" case deleted = "Deleted" case domainEndpointOptions = "DomainEndpointOptions" case domainId = "DomainId" case domainName = "DomainName" case eBSOptions = "EBSOptions" case elasticsearchClusterConfig = "ElasticsearchClusterConfig" case elasticsearchVersion = "ElasticsearchVersion" case encryptionAtRestOptions = "EncryptionAtRestOptions" case endpoint = "Endpoint" case endpoints = "Endpoints" case logPublishingOptions = "LogPublishingOptions" case nodeToNodeEncryptionOptions = "NodeToNodeEncryptionOptions" case processing = "Processing" case serviceSoftwareOptions = "ServiceSoftwareOptions" case snapshotOptions = "SnapshotOptions" case upgradeProcessing = "UpgradeProcessing" case vPCOptions = "VPCOptions" } } public struct ElasticsearchVersionStatus: AWSDecodableShape { /// Specifies the Elasticsearch version for the specified Elasticsearch domain. public let options: String /// Specifies the status of the Elasticsearch version options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: String, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct EncryptionAtRestOptions: AWSEncodableShape & AWSDecodableShape { /// Specifies the option to enable Encryption At Rest. public let enabled: Bool? /// Specifies the KMS Key ID for Encryption At Rest options. public let kmsKeyId: String? public init(enabled: Bool? = nil, kmsKeyId: String? = nil) { self.enabled = enabled self.kmsKeyId = kmsKeyId } public func validate(name: String) throws { try validate(self.kmsKeyId, name: "kmsKeyId", parent: name, max: 500) try validate(self.kmsKeyId, name: "kmsKeyId", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" case kmsKeyId = "KmsKeyId" } } public struct EncryptionAtRestOptionsStatus: AWSDecodableShape { /// Specifies the Encryption At Rest options for the specified Elasticsearch domain. public let options: EncryptionAtRestOptions /// Specifies the status of the Encryption At Rest options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: EncryptionAtRestOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct ErrorDetails: AWSDecodableShape { public let errorMessage: String? public let errorType: String? public init(errorMessage: String? = nil, errorType: String? = nil) { self.errorMessage = errorMessage self.errorType = errorType } private enum CodingKeys: String, CodingKey { case errorMessage = "ErrorMessage" case errorType = "ErrorType" } } public struct Filter: AWSEncodableShape { /// Specifies the name of the filter. public let name: String? /// Contains one or more values for the filter. public let values: [String]? public init(name: String? = nil, values: [String]? = nil) { self.name = name self.values = values } public func validate(name: String) throws { try validate(self.name, name: "name", parent: name, min: 1) try self.values?.forEach { try validate($0, name: "values[]", parent: name, min: 1) } try validate(self.values, name: "values", parent: name, min: 1) } private enum CodingKeys: String, CodingKey { case name = "Name" case values = "Values" } } public struct GetCompatibleElasticsearchVersionsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring(locationName: "domainName")) ] public let domainName: String? public init(domainName: String? = nil) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct GetCompatibleElasticsearchVersionsResponse: AWSDecodableShape { /// A map of compatible Elasticsearch versions returned as part of the GetCompatibleElasticsearchVersions operation. public let compatibleElasticsearchVersions: [CompatibleVersionsMap]? public init(compatibleElasticsearchVersions: [CompatibleVersionsMap]? = nil) { self.compatibleElasticsearchVersions = compatibleElasticsearchVersions } private enum CodingKeys: String, CodingKey { case compatibleElasticsearchVersions = "CompatibleElasticsearchVersions" } } public struct GetUpgradeHistoryRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] public let domainName: String public let maxResults: Int? public let nextToken: String? public init(domainName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct GetUpgradeHistoryResponse: AWSDecodableShape { /// Pagination token that needs to be supplied to the next call to get the next page of results public let nextToken: String? /// A list of UpgradeHistory objects corresponding to each Upgrade or Upgrade Eligibility Check performed on a domain returned as part of GetUpgradeHistoryResponse object. public let upgradeHistories: [UpgradeHistory]? public init(nextToken: String? = nil, upgradeHistories: [UpgradeHistory]? = nil) { self.nextToken = nextToken self.upgradeHistories = upgradeHistories } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case upgradeHistories = "UpgradeHistories" } } public struct GetUpgradeStatusRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")) ] public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: CodingKey {} } public struct GetUpgradeStatusResponse: AWSDecodableShape { /// One of 4 statuses that a step can go through returned as part of the GetUpgradeStatusResponse object. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let stepStatus: UpgradeStatus? /// A string that describes the update briefly public let upgradeName: String? /// Represents one of 3 steps that an Upgrade or Upgrade Eligibility Check does through: PreUpgradeCheck Snapshot Upgrade public let upgradeStep: UpgradeStep? public init(stepStatus: UpgradeStatus? = nil, upgradeName: String? = nil, upgradeStep: UpgradeStep? = nil) { self.stepStatus = stepStatus self.upgradeName = upgradeName self.upgradeStep = upgradeStep } private enum CodingKeys: String, CodingKey { case stepStatus = "StepStatus" case upgradeName = "UpgradeName" case upgradeStep = "UpgradeStep" } } public struct InboundCrossClusterSearchConnection: AWSDecodableShape { /// Specifies the InboundCrossClusterSearchConnectionStatus for the outbound connection. public let connectionStatus: InboundCrossClusterSearchConnectionStatus? /// Specifies the connection id for the inbound cross-cluster search connection. public let crossClusterSearchConnectionId: String? /// Specifies the DomainInformation for the destination Elasticsearch domain. public let destinationDomainInfo: DomainInformation? /// Specifies the DomainInformation for the source Elasticsearch domain. public let sourceDomainInfo: DomainInformation? public init(connectionStatus: InboundCrossClusterSearchConnectionStatus? = nil, crossClusterSearchConnectionId: String? = nil, destinationDomainInfo: DomainInformation? = nil, sourceDomainInfo: DomainInformation? = nil) { self.connectionStatus = connectionStatus self.crossClusterSearchConnectionId = crossClusterSearchConnectionId self.destinationDomainInfo = destinationDomainInfo self.sourceDomainInfo = sourceDomainInfo } private enum CodingKeys: String, CodingKey { case connectionStatus = "ConnectionStatus" case crossClusterSearchConnectionId = "CrossClusterSearchConnectionId" case destinationDomainInfo = "DestinationDomainInfo" case sourceDomainInfo = "SourceDomainInfo" } } public struct InboundCrossClusterSearchConnectionStatus: AWSDecodableShape { /// Specifies verbose information for the inbound connection status. public let message: String? /// The state code for inbound connection. This can be one of the following: PENDING_ACCEPTANCE: Inbound connection is not yet accepted by destination domain owner. APPROVED: Inbound connection is pending acceptance by destination domain owner. REJECTING: Inbound connection rejection is in process. REJECTED: Inbound connection is rejected. DELETING: Inbound connection deletion is in progress. DELETED: Inbound connection is deleted and cannot be used further. public let statusCode: InboundCrossClusterSearchConnectionStatusCode? public init(message: String? = nil, statusCode: InboundCrossClusterSearchConnectionStatusCode? = nil) { self.message = message self.statusCode = statusCode } private enum CodingKeys: String, CodingKey { case message = "Message" case statusCode = "StatusCode" } } public struct InstanceCountLimits: AWSDecodableShape { public let maximumInstanceCount: Int? public let minimumInstanceCount: Int? public init(maximumInstanceCount: Int? = nil, minimumInstanceCount: Int? = nil) { self.maximumInstanceCount = maximumInstanceCount self.minimumInstanceCount = minimumInstanceCount } private enum CodingKeys: String, CodingKey { case maximumInstanceCount = "MaximumInstanceCount" case minimumInstanceCount = "MinimumInstanceCount" } } public struct InstanceLimits: AWSDecodableShape { public let instanceCountLimits: InstanceCountLimits? public init(instanceCountLimits: InstanceCountLimits? = nil) { self.instanceCountLimits = instanceCountLimits } private enum CodingKeys: String, CodingKey { case instanceCountLimits = "InstanceCountLimits" } } public struct Limits: AWSDecodableShape { /// List of additional limits that are specific to a given InstanceType and for each of it's InstanceRole . public let additionalLimits: [AdditionalLimit]? public let instanceLimits: InstanceLimits? /// StorageType represents the list of storage related types and attributes that are available for given InstanceType. public let storageTypes: [StorageType]? public init(additionalLimits: [AdditionalLimit]? = nil, instanceLimits: InstanceLimits? = nil, storageTypes: [StorageType]? = nil) { self.additionalLimits = additionalLimits self.instanceLimits = instanceLimits self.storageTypes = storageTypes } private enum CodingKeys: String, CodingKey { case additionalLimits = "AdditionalLimits" case instanceLimits = "InstanceLimits" case storageTypes = "StorageTypes" } } public struct ListDomainNamesResponse: AWSDecodableShape { /// List of Elasticsearch domain names. public let domainNames: [DomainInfo]? public init(domainNames: [DomainInfo]? = nil) { self.domainNames = domainNames } private enum CodingKeys: String, CodingKey { case domainNames = "DomainNames" } } public struct ListDomainsForPackageRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")), AWSMemberEncoding(label: "packageID", location: .uri(locationName: "PackageID")) ] /// Limits results to a maximum number of domains. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? /// The package for which to list domains. public let packageID: String public init(maxResults: Int? = nil, nextToken: String? = nil, packageID: String) { self.maxResults = maxResults self.nextToken = nextToken self.packageID = packageID } public func validate(name: String) throws { try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListDomainsForPackageResponse: AWSDecodableShape { /// List of DomainPackageDetails objects. public let domainPackageDetailsList: [DomainPackageDetails]? public let nextToken: String? public init(domainPackageDetailsList: [DomainPackageDetails]? = nil, nextToken: String? = nil) { self.domainPackageDetailsList = domainPackageDetailsList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case domainPackageDetailsList = "DomainPackageDetailsList" case nextToken = "NextToken" } } public struct ListElasticsearchInstanceTypesRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .querystring(locationName: "domainName")), AWSMemberEncoding(label: "elasticsearchVersion", location: .uri(locationName: "ElasticsearchVersion")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// DomainName represents the name of the Domain that we are trying to modify. This should be present only if we are querying for list of available Elasticsearch instance types when modifying existing domain. public let domainName: String? /// Version of Elasticsearch for which list of supported elasticsearch instance types are needed. public let elasticsearchVersion: String /// Set this value to limit the number of results returned. Value provided must be greater than 30 else it wont be honored. public let maxResults: Int? /// NextToken should be sent in case if earlier API call produced result containing NextToken. It is used for pagination. public let nextToken: String? public init(domainName: String? = nil, elasticsearchVersion: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.elasticsearchVersion = elasticsearchVersion self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListElasticsearchInstanceTypesResponse: AWSDecodableShape { /// List of instance types supported by Amazon Elasticsearch service for given ElasticsearchVersion public let elasticsearchInstanceTypes: [ESPartitionInstanceType]? /// In case if there are more results available NextToken would be present, make further request to the same API with received NextToken to paginate remaining results. public let nextToken: String? public init(elasticsearchInstanceTypes: [ESPartitionInstanceType]? = nil, nextToken: String? = nil) { self.elasticsearchInstanceTypes = elasticsearchInstanceTypes self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case elasticsearchInstanceTypes = "ElasticsearchInstanceTypes" case nextToken = "NextToken" } } public struct ListElasticsearchVersionsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// Set this value to limit the number of results returned. Value provided must be greater than 10 else it wont be honored. public let maxResults: Int? public let nextToken: String? public init(maxResults: Int? = nil, nextToken: String? = nil) { self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListElasticsearchVersionsResponse: AWSDecodableShape { public let elasticsearchVersions: [String]? public let nextToken: String? public init(elasticsearchVersions: [String]? = nil, nextToken: String? = nil) { self.elasticsearchVersions = elasticsearchVersions self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case elasticsearchVersions = "ElasticsearchVersions" case nextToken = "NextToken" } } public struct ListPackagesForDomainRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")), AWSMemberEncoding(label: "maxResults", location: .querystring(locationName: "maxResults")), AWSMemberEncoding(label: "nextToken", location: .querystring(locationName: "nextToken")) ] /// The name of the domain for which you want to list associated packages. public let domainName: String /// Limits results to a maximum number of packages. public let maxResults: Int? /// Used for pagination. Only necessary if a previous API call includes a non-null NextToken value. If provided, returns results for the next page. public let nextToken: String? public init(domainName: String, maxResults: Int? = nil, nextToken: String? = nil) { self.domainName = domainName self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") try validate(self.maxResults, name: "maxResults", parent: name, max: 100) } private enum CodingKeys: CodingKey {} } public struct ListPackagesForDomainResponse: AWSDecodableShape { /// List of DomainPackageDetails objects. public let domainPackageDetailsList: [DomainPackageDetails]? /// Pagination token that needs to be supplied to the next call to get the next page of results. public let nextToken: String? public init(domainPackageDetailsList: [DomainPackageDetails]? = nil, nextToken: String? = nil) { self.domainPackageDetailsList = domainPackageDetailsList self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case domainPackageDetailsList = "DomainPackageDetailsList" case nextToken = "NextToken" } } public struct ListTagsRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "arn", location: .querystring(locationName: "arn")) ] /// Specify the ARN for the Elasticsearch domain to which the tags are attached that you want to view. public let arn: String public init(arn: String) { self.arn = arn } private enum CodingKeys: CodingKey {} } public struct ListTagsResponse: AWSDecodableShape { /// List of Tag for the requested Elasticsearch domain. public let tagList: [Tag]? public init(tagList: [Tag]? = nil) { self.tagList = tagList } private enum CodingKeys: String, CodingKey { case tagList = "TagList" } } public struct LogPublishingOption: AWSEncodableShape & AWSDecodableShape { public let cloudWatchLogsLogGroupArn: String? /// Specifies whether given log publishing option is enabled or not. public let enabled: Bool? public init(cloudWatchLogsLogGroupArn: String? = nil, enabled: Bool? = nil) { self.cloudWatchLogsLogGroupArn = cloudWatchLogsLogGroupArn self.enabled = enabled } private enum CodingKeys: String, CodingKey { case cloudWatchLogsLogGroupArn = "CloudWatchLogsLogGroupArn" case enabled = "Enabled" } } public struct LogPublishingOptionsStatus: AWSDecodableShape { /// The log publishing options configured for the Elasticsearch domain. public let options: [LogType: LogPublishingOption]? /// The status of the log publishing options for the Elasticsearch domain. See OptionStatus for the status information that's included. public let status: OptionStatus? public init(options: [LogType: LogPublishingOption]? = nil, status: OptionStatus? = nil) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct MasterUserOptions: AWSEncodableShape { /// ARN for the master user (if IAM is enabled). public let masterUserARN: String? /// The master user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. public let masterUserName: String? /// The master user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. public let masterUserPassword: String? public init(masterUserARN: String? = nil, masterUserName: String? = nil, masterUserPassword: String? = nil) { self.masterUserARN = masterUserARN self.masterUserName = masterUserName self.masterUserPassword = masterUserPassword } public func validate(name: String) throws { try validate(self.masterUserName, name: "masterUserName", parent: name, min: 1) try validate(self.masterUserPassword, name: "masterUserPassword", parent: name, min: 8) } private enum CodingKeys: String, CodingKey { case masterUserARN = "MasterUserARN" case masterUserName = "MasterUserName" case masterUserPassword = "MasterUserPassword" } } public struct NodeToNodeEncryptionOptions: AWSEncodableShape & AWSDecodableShape { /// Specify true to enable node-to-node encryption. public let enabled: Bool? public init(enabled: Bool? = nil) { self.enabled = enabled } private enum CodingKeys: String, CodingKey { case enabled = "Enabled" } } public struct NodeToNodeEncryptionOptionsStatus: AWSDecodableShape { /// Specifies the node-to-node encryption options for the specified Elasticsearch domain. public let options: NodeToNodeEncryptionOptions /// Specifies the status of the node-to-node encryption options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: NodeToNodeEncryptionOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct OptionStatus: AWSDecodableShape { /// Timestamp which tells the creation date for the entity. public let creationDate: TimeStamp /// Indicates whether the Elasticsearch domain is being deleted. public let pendingDeletion: Bool? /// Provides the OptionState for the Elasticsearch domain. public let state: OptionState /// Timestamp which tells the last updated time for the entity. public let updateDate: TimeStamp /// Specifies the latest version for the entity. public let updateVersion: Int? public init(creationDate: TimeStamp, pendingDeletion: Bool? = nil, state: OptionState, updateDate: TimeStamp, updateVersion: Int? = nil) { self.creationDate = creationDate self.pendingDeletion = pendingDeletion self.state = state self.updateDate = updateDate self.updateVersion = updateVersion } private enum CodingKeys: String, CodingKey { case creationDate = "CreationDate" case pendingDeletion = "PendingDeletion" case state = "State" case updateDate = "UpdateDate" case updateVersion = "UpdateVersion" } } public struct OutboundCrossClusterSearchConnection: AWSDecodableShape { /// Specifies the connection alias for the outbound cross-cluster search connection. public let connectionAlias: String? /// Specifies the OutboundCrossClusterSearchConnectionStatus for the outbound connection. public let connectionStatus: OutboundCrossClusterSearchConnectionStatus? /// Specifies the connection id for the outbound cross-cluster search connection. public let crossClusterSearchConnectionId: String? /// Specifies the DomainInformation for the destination Elasticsearch domain. public let destinationDomainInfo: DomainInformation? /// Specifies the DomainInformation for the source Elasticsearch domain. public let sourceDomainInfo: DomainInformation? public init(connectionAlias: String? = nil, connectionStatus: OutboundCrossClusterSearchConnectionStatus? = nil, crossClusterSearchConnectionId: String? = nil, destinationDomainInfo: DomainInformation? = nil, sourceDomainInfo: DomainInformation? = nil) { self.connectionAlias = connectionAlias self.connectionStatus = connectionStatus self.crossClusterSearchConnectionId = crossClusterSearchConnectionId self.destinationDomainInfo = destinationDomainInfo self.sourceDomainInfo = sourceDomainInfo } private enum CodingKeys: String, CodingKey { case connectionAlias = "ConnectionAlias" case connectionStatus = "ConnectionStatus" case crossClusterSearchConnectionId = "CrossClusterSearchConnectionId" case destinationDomainInfo = "DestinationDomainInfo" case sourceDomainInfo = "SourceDomainInfo" } } public struct OutboundCrossClusterSearchConnectionStatus: AWSDecodableShape { /// Specifies verbose information for the outbound connection status. public let message: String? /// The state code for outbound connection. This can be one of the following: VALIDATING: The outbound connection request is being validated. VALIDATION_FAILED: Validation failed for the connection request. PENDING_ACCEPTANCE: Outbound connection request is validated and is not yet accepted by destination domain owner. PROVISIONING: Outbound connection request is in process. ACTIVE: Outbound connection is active and ready to use. REJECTED: Outbound connection request is rejected by destination domain owner. DELETING: Outbound connection deletion is in progress. DELETED: Outbound connection is deleted and cannot be used further. public let statusCode: OutboundCrossClusterSearchConnectionStatusCode? public init(message: String? = nil, statusCode: OutboundCrossClusterSearchConnectionStatusCode? = nil) { self.message = message self.statusCode = statusCode } private enum CodingKeys: String, CodingKey { case message = "Message" case statusCode = "StatusCode" } } public struct PackageDetails: AWSDecodableShape { /// Timestamp which tells creation date of the package. public let createdAt: TimeStamp? /// Additional information if the package is in an error state. Null otherwise. public let errorDetails: ErrorDetails? /// User-specified description of the package. public let packageDescription: String? /// Internal ID of the package. public let packageID: String? /// User specified name of the package. public let packageName: String? /// Current state of the package. Values are COPYING/COPY_FAILED/AVAILABLE/DELETING/DELETE_FAILED public let packageStatus: PackageStatus? /// Currently supports only TXT-DICTIONARY. public let packageType: PackageType? public init(createdAt: TimeStamp? = nil, errorDetails: ErrorDetails? = nil, packageDescription: String? = nil, packageID: String? = nil, packageName: String? = nil, packageStatus: PackageStatus? = nil, packageType: PackageType? = nil) { self.createdAt = createdAt self.errorDetails = errorDetails self.packageDescription = packageDescription self.packageID = packageID self.packageName = packageName self.packageStatus = packageStatus self.packageType = packageType } private enum CodingKeys: String, CodingKey { case createdAt = "CreatedAt" case errorDetails = "ErrorDetails" case packageDescription = "PackageDescription" case packageID = "PackageID" case packageName = "PackageName" case packageStatus = "PackageStatus" case packageType = "PackageType" } } public struct PackageSource: AWSEncodableShape { /// Name of the bucket containing the package. public let s3BucketName: String? /// Key (file name) of the package. public let s3Key: String? public init(s3BucketName: String? = nil, s3Key: String? = nil) { self.s3BucketName = s3BucketName self.s3Key = s3Key } public func validate(name: String) throws { try validate(self.s3BucketName, name: "s3BucketName", parent: name, max: 63) try validate(self.s3BucketName, name: "s3BucketName", parent: name, min: 3) } private enum CodingKeys: String, CodingKey { case s3BucketName = "S3BucketName" case s3Key = "S3Key" } } public struct PurchaseReservedElasticsearchInstanceOfferingRequest: AWSEncodableShape { /// The number of Elasticsearch instances to reserve. public let instanceCount: Int? /// A customer-specified identifier to track this reservation. public let reservationName: String /// The ID of the reserved Elasticsearch instance offering to purchase. public let reservedElasticsearchInstanceOfferingId: String public init(instanceCount: Int? = nil, reservationName: String, reservedElasticsearchInstanceOfferingId: String) { self.instanceCount = instanceCount self.reservationName = reservationName self.reservedElasticsearchInstanceOfferingId = reservedElasticsearchInstanceOfferingId } public func validate(name: String) throws { try validate(self.instanceCount, name: "instanceCount", parent: name, min: 1) try validate(self.reservationName, name: "reservationName", parent: name, max: 64) try validate(self.reservationName, name: "reservationName", parent: name, min: 5) try validate(self.reservedElasticsearchInstanceOfferingId, name: "reservedElasticsearchInstanceOfferingId", parent: name, pattern: "\\p{XDigit}{8}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{4}-\\p{XDigit}{12}") } private enum CodingKeys: String, CodingKey { case instanceCount = "InstanceCount" case reservationName = "ReservationName" case reservedElasticsearchInstanceOfferingId = "ReservedElasticsearchInstanceOfferingId" } } public struct PurchaseReservedElasticsearchInstanceOfferingResponse: AWSDecodableShape { /// The customer-specified identifier used to track this reservation. public let reservationName: String? /// Details of the reserved Elasticsearch instance which was purchased. public let reservedElasticsearchInstanceId: String? public init(reservationName: String? = nil, reservedElasticsearchInstanceId: String? = nil) { self.reservationName = reservationName self.reservedElasticsearchInstanceId = reservedElasticsearchInstanceId } private enum CodingKeys: String, CodingKey { case reservationName = "ReservationName" case reservedElasticsearchInstanceId = "ReservedElasticsearchInstanceId" } } public struct RecurringCharge: AWSDecodableShape { /// The monetary amount of the recurring charge. public let recurringChargeAmount: Double? /// The frequency of the recurring charge. public let recurringChargeFrequency: String? public init(recurringChargeAmount: Double? = nil, recurringChargeFrequency: String? = nil) { self.recurringChargeAmount = recurringChargeAmount self.recurringChargeFrequency = recurringChargeFrequency } private enum CodingKeys: String, CodingKey { case recurringChargeAmount = "RecurringChargeAmount" case recurringChargeFrequency = "RecurringChargeFrequency" } } public struct RejectInboundCrossClusterSearchConnectionRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "crossClusterSearchConnectionId", location: .uri(locationName: "ConnectionId")) ] /// The id of the inbound connection that you want to reject. public let crossClusterSearchConnectionId: String public init(crossClusterSearchConnectionId: String) { self.crossClusterSearchConnectionId = crossClusterSearchConnectionId } private enum CodingKeys: CodingKey {} } public struct RejectInboundCrossClusterSearchConnectionResponse: AWSDecodableShape { /// Specifies the InboundCrossClusterSearchConnection of rejected inbound connection. public let crossClusterSearchConnection: InboundCrossClusterSearchConnection? public init(crossClusterSearchConnection: InboundCrossClusterSearchConnection? = nil) { self.crossClusterSearchConnection = crossClusterSearchConnection } private enum CodingKeys: String, CodingKey { case crossClusterSearchConnection = "CrossClusterSearchConnection" } } public struct RemoveTagsRequest: AWSEncodableShape { /// Specifies the ARN for the Elasticsearch domain from which you want to delete the specified tags. public let arn: String /// Specifies the TagKey list which you want to remove from the Elasticsearch domain. public let tagKeys: [String] public init(arn: String, tagKeys: [String]) { self.arn = arn self.tagKeys = tagKeys } private enum CodingKeys: String, CodingKey { case arn = "ARN" case tagKeys = "TagKeys" } } public struct ReservedElasticsearchInstance: AWSDecodableShape { /// The currency code for the reserved Elasticsearch instance offering. public let currencyCode: String? /// The duration, in seconds, for which the Elasticsearch instance is reserved. public let duration: Int? /// The number of Elasticsearch instances that have been reserved. public let elasticsearchInstanceCount: Int? /// The Elasticsearch instance type offered by the reserved instance offering. public let elasticsearchInstanceType: ESPartitionInstanceType? /// The upfront fixed charge you will paid to purchase the specific reserved Elasticsearch instance offering. public let fixedPrice: Double? /// The payment option as defined in the reserved Elasticsearch instance offering. public let paymentOption: ReservedElasticsearchInstancePaymentOption? /// The charge to your account regardless of whether you are creating any domains using the instance offering. public let recurringCharges: [RecurringCharge]? /// The customer-specified identifier to track this reservation. public let reservationName: String? /// The unique identifier for the reservation. public let reservedElasticsearchInstanceId: String? /// The offering identifier. public let reservedElasticsearchInstanceOfferingId: String? /// The time the reservation started. public let startTime: TimeStamp? /// The state of the reserved Elasticsearch instance. public let state: String? /// The rate you are charged for each hour for the domain that is using this reserved instance. public let usagePrice: Double? public init(currencyCode: String? = nil, duration: Int? = nil, elasticsearchInstanceCount: Int? = nil, elasticsearchInstanceType: ESPartitionInstanceType? = nil, fixedPrice: Double? = nil, paymentOption: ReservedElasticsearchInstancePaymentOption? = nil, recurringCharges: [RecurringCharge]? = nil, reservationName: String? = nil, reservedElasticsearchInstanceId: String? = nil, reservedElasticsearchInstanceOfferingId: String? = nil, startTime: TimeStamp? = nil, state: String? = nil, usagePrice: Double? = nil) { self.currencyCode = currencyCode self.duration = duration self.elasticsearchInstanceCount = elasticsearchInstanceCount self.elasticsearchInstanceType = elasticsearchInstanceType self.fixedPrice = fixedPrice self.paymentOption = paymentOption self.recurringCharges = recurringCharges self.reservationName = reservationName self.reservedElasticsearchInstanceId = reservedElasticsearchInstanceId self.reservedElasticsearchInstanceOfferingId = reservedElasticsearchInstanceOfferingId self.startTime = startTime self.state = state self.usagePrice = usagePrice } private enum CodingKeys: String, CodingKey { case currencyCode = "CurrencyCode" case duration = "Duration" case elasticsearchInstanceCount = "ElasticsearchInstanceCount" case elasticsearchInstanceType = "ElasticsearchInstanceType" case fixedPrice = "FixedPrice" case paymentOption = "PaymentOption" case recurringCharges = "RecurringCharges" case reservationName = "ReservationName" case reservedElasticsearchInstanceId = "ReservedElasticsearchInstanceId" case reservedElasticsearchInstanceOfferingId = "ReservedElasticsearchInstanceOfferingId" case startTime = "StartTime" case state = "State" case usagePrice = "UsagePrice" } } public struct ReservedElasticsearchInstanceOffering: AWSDecodableShape { /// The currency code for the reserved Elasticsearch instance offering. public let currencyCode: String? /// The duration, in seconds, for which the offering will reserve the Elasticsearch instance. public let duration: Int? /// The Elasticsearch instance type offered by the reserved instance offering. public let elasticsearchInstanceType: ESPartitionInstanceType? /// The upfront fixed charge you will pay to purchase the specific reserved Elasticsearch instance offering. public let fixedPrice: Double? /// Payment option for the reserved Elasticsearch instance offering public let paymentOption: ReservedElasticsearchInstancePaymentOption? /// The charge to your account regardless of whether you are creating any domains using the instance offering. public let recurringCharges: [RecurringCharge]? /// The Elasticsearch reserved instance offering identifier. public let reservedElasticsearchInstanceOfferingId: String? /// The rate you are charged for each hour the domain that is using the offering is running. public let usagePrice: Double? public init(currencyCode: String? = nil, duration: Int? = nil, elasticsearchInstanceType: ESPartitionInstanceType? = nil, fixedPrice: Double? = nil, paymentOption: ReservedElasticsearchInstancePaymentOption? = nil, recurringCharges: [RecurringCharge]? = nil, reservedElasticsearchInstanceOfferingId: String? = nil, usagePrice: Double? = nil) { self.currencyCode = currencyCode self.duration = duration self.elasticsearchInstanceType = elasticsearchInstanceType self.fixedPrice = fixedPrice self.paymentOption = paymentOption self.recurringCharges = recurringCharges self.reservedElasticsearchInstanceOfferingId = reservedElasticsearchInstanceOfferingId self.usagePrice = usagePrice } private enum CodingKeys: String, CodingKey { case currencyCode = "CurrencyCode" case duration = "Duration" case elasticsearchInstanceType = "ElasticsearchInstanceType" case fixedPrice = "FixedPrice" case paymentOption = "PaymentOption" case recurringCharges = "RecurringCharges" case reservedElasticsearchInstanceOfferingId = "ReservedElasticsearchInstanceOfferingId" case usagePrice = "UsagePrice" } } public struct ServiceSoftwareOptions: AWSDecodableShape { /// Timestamp, in Epoch time, until which you can manually request a service software update. After this date, we automatically update your service software. public let automatedUpdateDate: TimeStamp? /// True if you are able to cancel your service software version update. False if you are not able to cancel your service software version. public let cancellable: Bool? /// The current service software version that is present on the domain. public let currentVersion: String? /// The description of the UpdateStatus. public let description: String? /// The new service software version if one is available. public let newVersion: String? /// True if a service software is never automatically updated. False if a service software is automatically updated after AutomatedUpdateDate. public let optionalDeployment: Bool? /// True if you are able to update you service software version. False if you are not able to update your service software version. public let updateAvailable: Bool? /// The status of your service software update. This field can take the following values: ELIGIBLE, PENDING_UPDATE, IN_PROGRESS, COMPLETED, and NOT_ELIGIBLE. public let updateStatus: DeploymentStatus? public init(automatedUpdateDate: TimeStamp? = nil, cancellable: Bool? = nil, currentVersion: String? = nil, description: String? = nil, newVersion: String? = nil, optionalDeployment: Bool? = nil, updateAvailable: Bool? = nil, updateStatus: DeploymentStatus? = nil) { self.automatedUpdateDate = automatedUpdateDate self.cancellable = cancellable self.currentVersion = currentVersion self.description = description self.newVersion = newVersion self.optionalDeployment = optionalDeployment self.updateAvailable = updateAvailable self.updateStatus = updateStatus } private enum CodingKeys: String, CodingKey { case automatedUpdateDate = "AutomatedUpdateDate" case cancellable = "Cancellable" case currentVersion = "CurrentVersion" case description = "Description" case newVersion = "NewVersion" case optionalDeployment = "OptionalDeployment" case updateAvailable = "UpdateAvailable" case updateStatus = "UpdateStatus" } } public struct SnapshotOptions: AWSEncodableShape & AWSDecodableShape { /// Specifies the time, in UTC format, when the service takes a daily automated snapshot of the specified Elasticsearch domain. Default value is 0 hours. public let automatedSnapshotStartHour: Int? public init(automatedSnapshotStartHour: Int? = nil) { self.automatedSnapshotStartHour = automatedSnapshotStartHour } private enum CodingKeys: String, CodingKey { case automatedSnapshotStartHour = "AutomatedSnapshotStartHour" } } public struct SnapshotOptionsStatus: AWSDecodableShape { /// Specifies the daily snapshot options specified for the Elasticsearch domain. public let options: SnapshotOptions /// Specifies the status of a daily automated snapshot. public let status: OptionStatus public init(options: SnapshotOptions, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct StartElasticsearchServiceSoftwareUpdateRequest: AWSEncodableShape { /// The name of the domain that you want to update to the latest service software. public let domainName: String public init(domainName: String) { self.domainName = domainName } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" } } public struct StartElasticsearchServiceSoftwareUpdateResponse: AWSDecodableShape { /// The current status of the Elasticsearch service software update. public let serviceSoftwareOptions: ServiceSoftwareOptions? public init(serviceSoftwareOptions: ServiceSoftwareOptions? = nil) { self.serviceSoftwareOptions = serviceSoftwareOptions } private enum CodingKeys: String, CodingKey { case serviceSoftwareOptions = "ServiceSoftwareOptions" } } public struct StorageType: AWSDecodableShape { public let storageSubTypeName: String? /// List of limits that are applicable for given storage type. public let storageTypeLimits: [StorageTypeLimit]? public let storageTypeName: String? public init(storageSubTypeName: String? = nil, storageTypeLimits: [StorageTypeLimit]? = nil, storageTypeName: String? = nil) { self.storageSubTypeName = storageSubTypeName self.storageTypeLimits = storageTypeLimits self.storageTypeName = storageTypeName } private enum CodingKeys: String, CodingKey { case storageSubTypeName = "StorageSubTypeName" case storageTypeLimits = "StorageTypeLimits" case storageTypeName = "StorageTypeName" } } public struct StorageTypeLimit: AWSDecodableShape { /// Name of storage limits that are applicable for given storage type. If StorageType is ebs, following storage options are applicable MinimumVolumeSize Minimum amount of volume size that is applicable for given storage type.It can be empty if it is not applicable. MaximumVolumeSize Maximum amount of volume size that is applicable for given storage type.It can be empty if it is not applicable. MaximumIops Maximum amount of Iops that is applicable for given storage type.It can be empty if it is not applicable. MinimumIops Minimum amount of Iops that is applicable for given storage type.It can be empty if it is not applicable. public let limitName: String? /// Values for the StorageTypeLimit$LimitName . public let limitValues: [String]? public init(limitName: String? = nil, limitValues: [String]? = nil) { self.limitName = limitName self.limitValues = limitValues } private enum CodingKeys: String, CodingKey { case limitName = "LimitName" case limitValues = "LimitValues" } } public struct Tag: AWSEncodableShape & AWSDecodableShape { /// Specifies the TagKey, the name of the tag. Tag keys must be unique for the Elasticsearch domain to which they are attached. public let key: String /// Specifies the TagValue, the value assigned to the corresponding tag key. Tag values can be null and do not have to be unique in a tag set. For example, you can have a key value pair in a tag set of project : Trinity and cost-center : Trinity public let value: String public init(key: String, value: String) { self.key = key self.value = value } public func validate(name: String) throws { try validate(self.key, name: "key", parent: name, max: 128) try validate(self.key, name: "key", parent: name, min: 1) try validate(self.value, name: "value", parent: name, max: 256) try validate(self.value, name: "value", parent: name, min: 0) } private enum CodingKeys: String, CodingKey { case key = "Key" case value = "Value" } } public struct UpdateElasticsearchDomainConfigRequest: AWSEncodableShape { public static var _encoding = [ AWSMemberEncoding(label: "domainName", location: .uri(locationName: "DomainName")) ] /// IAM access policy as a JSON-formatted string. public let accessPolicies: String? /// Modifies the advanced option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true. See Configuration Advanced Options for more information. public let advancedOptions: [String: String]? /// Specifies advanced security options. public let advancedSecurityOptions: AdvancedSecurityOptionsInput? /// Options to specify the Cognito user and identity pools for Kibana authentication. For more information, see Amazon Cognito Authentication for Kibana. public let cognitoOptions: CognitoOptions? /// Options to specify configuration that will be applied to the domain endpoint. public let domainEndpointOptions: DomainEndpointOptions? /// The name of the Elasticsearch domain that you are updating. public let domainName: String /// Specify the type and size of the EBS volume that you want to use. public let eBSOptions: EBSOptions? /// The type and number of instances to instantiate for the domain cluster. public let elasticsearchClusterConfig: ElasticsearchClusterConfig? /// Map of LogType and LogPublishingOption, each containing options to publish a given type of Elasticsearch log. public let logPublishingOptions: [LogType: LogPublishingOption]? /// Option to set the time, in UTC format, for the daily automated snapshot. Default value is 0 hours. public let snapshotOptions: SnapshotOptions? /// Options to specify the subnets and security groups for VPC endpoint. For more information, see Creating a VPC in VPC Endpoints for Amazon Elasticsearch Service Domains public let vPCOptions: VPCOptions? public init(accessPolicies: String? = nil, advancedOptions: [String: String]? = nil, advancedSecurityOptions: AdvancedSecurityOptionsInput? = nil, cognitoOptions: CognitoOptions? = nil, domainEndpointOptions: DomainEndpointOptions? = nil, domainName: String, eBSOptions: EBSOptions? = nil, elasticsearchClusterConfig: ElasticsearchClusterConfig? = nil, logPublishingOptions: [LogType: LogPublishingOption]? = nil, snapshotOptions: SnapshotOptions? = nil, vPCOptions: VPCOptions? = nil) { self.accessPolicies = accessPolicies self.advancedOptions = advancedOptions self.advancedSecurityOptions = advancedSecurityOptions self.cognitoOptions = cognitoOptions self.domainEndpointOptions = domainEndpointOptions self.domainName = domainName self.eBSOptions = eBSOptions self.elasticsearchClusterConfig = elasticsearchClusterConfig self.logPublishingOptions = logPublishingOptions self.snapshotOptions = snapshotOptions self.vPCOptions = vPCOptions } public func validate(name: String) throws { try self.advancedSecurityOptions?.validate(name: "\(name).advancedSecurityOptions") try self.cognitoOptions?.validate(name: "\(name).cognitoOptions") try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: String, CodingKey { case accessPolicies = "AccessPolicies" case advancedOptions = "AdvancedOptions" case advancedSecurityOptions = "AdvancedSecurityOptions" case cognitoOptions = "CognitoOptions" case domainEndpointOptions = "DomainEndpointOptions" case eBSOptions = "EBSOptions" case elasticsearchClusterConfig = "ElasticsearchClusterConfig" case logPublishingOptions = "LogPublishingOptions" case snapshotOptions = "SnapshotOptions" case vPCOptions = "VPCOptions" } } public struct UpdateElasticsearchDomainConfigResponse: AWSDecodableShape { /// The status of the updated Elasticsearch domain. public let domainConfig: ElasticsearchDomainConfig public init(domainConfig: ElasticsearchDomainConfig) { self.domainConfig = domainConfig } private enum CodingKeys: String, CodingKey { case domainConfig = "DomainConfig" } } public struct UpgradeElasticsearchDomainRequest: AWSEncodableShape { public let domainName: String /// This flag, when set to True, indicates that an Upgrade Eligibility Check needs to be performed. This will not actually perform the Upgrade. public let performCheckOnly: Bool? /// The version of Elasticsearch that you intend to upgrade the domain to. public let targetVersion: String public init(domainName: String, performCheckOnly: Bool? = nil, targetVersion: String) { self.domainName = domainName self.performCheckOnly = performCheckOnly self.targetVersion = targetVersion } public func validate(name: String) throws { try validate(self.domainName, name: "domainName", parent: name, max: 28) try validate(self.domainName, name: "domainName", parent: name, min: 3) try validate(self.domainName, name: "domainName", parent: name, pattern: "[a-z][a-z0-9\\-]+") } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case performCheckOnly = "PerformCheckOnly" case targetVersion = "TargetVersion" } } public struct UpgradeElasticsearchDomainResponse: AWSDecodableShape { public let domainName: String? /// This flag, when set to True, indicates that an Upgrade Eligibility Check needs to be performed. This will not actually perform the Upgrade. public let performCheckOnly: Bool? /// The version of Elasticsearch that you intend to upgrade the domain to. public let targetVersion: String? public init(domainName: String? = nil, performCheckOnly: Bool? = nil, targetVersion: String? = nil) { self.domainName = domainName self.performCheckOnly = performCheckOnly self.targetVersion = targetVersion } private enum CodingKeys: String, CodingKey { case domainName = "DomainName" case performCheckOnly = "PerformCheckOnly" case targetVersion = "TargetVersion" } } public struct UpgradeHistory: AWSDecodableShape { /// UTC Timestamp at which the Upgrade API call was made in "yyyy-MM-ddTHH:mm:ssZ" format. public let startTimestamp: TimeStamp? /// A list of UpgradeStepItem s representing information about each step performed as pard of a specific Upgrade or Upgrade Eligibility Check. public let stepsList: [UpgradeStepItem]? /// A string that describes the update briefly public let upgradeName: String? /// The overall status of the update. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let upgradeStatus: UpgradeStatus? public init(startTimestamp: TimeStamp? = nil, stepsList: [UpgradeStepItem]? = nil, upgradeName: String? = nil, upgradeStatus: UpgradeStatus? = nil) { self.startTimestamp = startTimestamp self.stepsList = stepsList self.upgradeName = upgradeName self.upgradeStatus = upgradeStatus } private enum CodingKeys: String, CodingKey { case startTimestamp = "StartTimestamp" case stepsList = "StepsList" case upgradeName = "UpgradeName" case upgradeStatus = "UpgradeStatus" } } public struct UpgradeStepItem: AWSDecodableShape { /// A list of strings containing detailed information about the errors encountered in a particular step. public let issues: [String]? /// The Floating point value representing progress percentage of a particular step. public let progressPercent: Double? /// Represents one of 3 steps that an Upgrade or Upgrade Eligibility Check does through: PreUpgradeCheck Snapshot Upgrade public let upgradeStep: UpgradeStep? /// The status of a particular step during an upgrade. The status can take one of the following values: In Progress Succeeded Succeeded with Issues Failed public let upgradeStepStatus: UpgradeStatus? public init(issues: [String]? = nil, progressPercent: Double? = nil, upgradeStep: UpgradeStep? = nil, upgradeStepStatus: UpgradeStatus? = nil) { self.issues = issues self.progressPercent = progressPercent self.upgradeStep = upgradeStep self.upgradeStepStatus = upgradeStepStatus } private enum CodingKeys: String, CodingKey { case issues = "Issues" case progressPercent = "ProgressPercent" case upgradeStep = "UpgradeStep" case upgradeStepStatus = "UpgradeStepStatus" } } public struct VPCDerivedInfo: AWSDecodableShape { /// The availability zones for the Elasticsearch domain. Exists only if the domain was created with VPCOptions. public let availabilityZones: [String]? /// Specifies the security groups for VPC endpoint. public let securityGroupIds: [String]? /// Specifies the subnets for VPC endpoint. public let subnetIds: [String]? /// The VPC Id for the Elasticsearch domain. Exists only if the domain was created with VPCOptions. public let vPCId: String? public init(availabilityZones: [String]? = nil, securityGroupIds: [String]? = nil, subnetIds: [String]? = nil, vPCId: String? = nil) { self.availabilityZones = availabilityZones self.securityGroupIds = securityGroupIds self.subnetIds = subnetIds self.vPCId = vPCId } private enum CodingKeys: String, CodingKey { case availabilityZones = "AvailabilityZones" case securityGroupIds = "SecurityGroupIds" case subnetIds = "SubnetIds" case vPCId = "VPCId" } } public struct VPCDerivedInfoStatus: AWSDecodableShape { /// Specifies the VPC options for the specified Elasticsearch domain. public let options: VPCDerivedInfo /// Specifies the status of the VPC options for the specified Elasticsearch domain. public let status: OptionStatus public init(options: VPCDerivedInfo, status: OptionStatus) { self.options = options self.status = status } private enum CodingKeys: String, CodingKey { case options = "Options" case status = "Status" } } public struct VPCOptions: AWSEncodableShape { /// Specifies the security groups for VPC endpoint. public let securityGroupIds: [String]? /// Specifies the subnets for VPC endpoint. public let subnetIds: [String]? public init(securityGroupIds: [String]? = nil, subnetIds: [String]? = nil) { self.securityGroupIds = securityGroupIds self.subnetIds = subnetIds } private enum CodingKeys: String, CodingKey { case securityGroupIds = "SecurityGroupIds" case subnetIds = "SubnetIds" } } public struct ZoneAwarenessConfig: AWSEncodableShape & AWSDecodableShape { /// An integer value to indicate the number of availability zones for a domain when zone awareness is enabled. This should be equal to number of subnets if VPC endpoints is enabled public let availabilityZoneCount: Int? public init(availabilityZoneCount: Int? = nil) { self.availabilityZoneCount = availabilityZoneCount } private enum CodingKeys: String, CodingKey { case availabilityZoneCount = "AvailabilityZoneCount" } } }
47.037229
894
0.677793
e923c1a65006f25d3e3a8d527c247db6e58b3b11
1,959
import CurrencyKit import RxSwift import RxRelay protocol IMarketListFetcher { func fetchSingle(currencyCode: String) -> Single<[MarketModule.Item]> var refetchObservable: Observable<()> { get } } class MarketListService { private let currencyKit: ICurrencyKit private let fetcher: IMarketListFetcher private var disposeBag = DisposeBag() private var fetchDisposeBag = DisposeBag() private let stateRelay = PublishRelay<State>() private(set) var state: State = .loading { didSet { stateRelay.accept(state) } } private(set) var items = [MarketModule.Item]() init(currencyKit: ICurrencyKit, fetcher: IMarketListFetcher) { self.currencyKit = currencyKit self.fetcher = fetcher subscribe(disposeBag, fetcher.refetchObservable) { [weak self] in self?.items = [] self?.fetch() } fetch() } private func fetch() { fetchDisposeBag = DisposeBag() state = .loading fetcher.fetchSingle(currencyCode: currency.code) .subscribe(onSuccess: { [weak self] items in self?.items = items self?.state = .loaded }, onError: { [weak self] error in self?.state = .failed(error: error) }) .disposed(by: fetchDisposeBag) } } extension MarketListService { var currency: Currency { //todo: refactor to use current currency and handle changing currencyKit.currencies.first { $0.code == "USD" } ?? currencyKit.currencies[0] } var stateObservable: Observable<State> { stateRelay.asObservable() } func refresh() { fetch() } func refetch() { items = [] fetch() } } extension MarketListService { enum State { case loaded case loading case failed(error: Error) } }
22.77907
86
0.591628
23c5bfdd0c1206f0e865be6c89d1368afe7686ff
7,468
/* Copyright 2021 natinusala 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 GLFW import Glad import Skia import CRippleUI import RippleCore /// GLFW as a platform. class GLFWPlatform: Platform { required init() throws { // Set error callback glfwSetErrorCallback {code, error in Logger.error("GLFW error \(code): \(error.str ?? "unknown")") } // Init GLFW if glfwInit() != GLFW_TRUE { throw GLFWError.initFailed } } func poll() { glfwPollEvents() } func createWindow(title: String, mode: WindowMode, backend: GraphicsBackend) throws -> NativeWindow { return try GLFWWindow(title: title, mode: mode, backend: backend) } } class GLFWWindow: NativeWindow { let handle: OpaquePointer? var dimensions: ObservedValue<Dimensions> /// Current graphics context. var context: GraphicsContext var skContext: OpaquePointer { return self.context.skContext } var canvas: Canvas { return self.context.canvas } init(title: String, mode: WindowMode, backend: GraphicsBackend) throws { // Setup hints glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE) if enableSRGB { glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE) } glfwWindowHint(GLFW_STENCIL_BITS, 0) glfwWindowHint(GLFW_ALPHA_BITS, 0) glfwWindowHint(GLFW_DEPTH_BITS, 0) // Reset mode specific values glfwWindowHint(GLFW_RED_BITS, GLFW_DONT_CARE) glfwWindowHint(GLFW_GREEN_BITS, GLFW_DONT_CARE) glfwWindowHint(GLFW_BLUE_BITS, GLFW_DONT_CARE) glfwWindowHint(GLFW_REFRESH_RATE, GLFW_DONT_CARE) // Get monitor and mode let monitor = glfwGetPrimaryMonitor() if monitor == nil { throw GLFWError.noPrimaryMonitor } guard let videoMode = glfwGetVideoMode(monitor) else { throw GLFWError.noVideoMode } // Create the new window switch mode { // Windowed mode case let .windowed(width, height): self.handle = glfwCreateWindow( Int32(width), Int32(height), title, nil, nil ) // Borderless mode case .borderlessWindow: glfwWindowHint(GLFW_RED_BITS, videoMode.pointee.redBits) glfwWindowHint(GLFW_GREEN_BITS, videoMode.pointee.greenBits) glfwWindowHint(GLFW_BLUE_BITS, videoMode.pointee.blueBits) glfwWindowHint(GLFW_REFRESH_RATE, videoMode.pointee.refreshRate) self.handle = glfwCreateWindow( videoMode.pointee.width, videoMode.pointee.height, title, monitor, nil ) // Fullscreen mode case .fullscreen: self.handle = glfwCreateWindow( videoMode.pointee.width, videoMode.pointee.height, title, monitor, nil ) } if self.handle == nil { throw GLFWError.cannotCreateWindow } // Initialize graphics API glfwMakeContextCurrent(handle) switch backend { case .gl: gladLoadGLLoaderFromGLFW() if debugGraphicsBackend { glEnable(GLenum(GL_DEBUG_OUTPUT)) glDebugMessageCallback( { _, type, id, severity, _, message, _ in onGlDebugMessage(severity: severity, type: type, id: id, message: message) }, nil ) } } // Enable sRGB if requested if enableSRGB { switch backend { case .gl: glEnable(UInt32(GL_FRAMEBUFFER_SRGB)) } } var actualWindowWidth: Int32 = 0 var actualWindowHeight: Int32 = 0 glfwGetWindowSize(handle, &actualWindowWidth, &actualWindowHeight) self.dimensions = ObservedValue<Dimensions>(value: (width: Float(actualWindowWidth), height: Float(actualWindowHeight))) // Initialize context self.context = try GraphicsContext( width: self.dimensions.value.width, height: self.dimensions.value.height, backend: backend ) // Finalize init glfwSwapInterval(1) // Set the `GLFWWindow` pointer as GLFW window userdata let unretainedSelf = Unmanaged.passUnretained(self) glfwSetWindowUserPointer(self.handle, unretainedSelf.toOpaque()) // Setup resize callback glfwSetWindowSizeCallback(self.handle) { window, width, height in guard let window = window else { fatalError("GLFW window size callback called with `nil`") } onWindowResized(window: window, width: width, height: height) } } var shouldClose: Bool { return glfwWindowShouldClose(self.handle) == 1 } func swapBuffers() { gr_direct_context_flush(self.skContext) glfwSwapBuffers(self.handle) } /// Called whenever this window is resized. func onResized(width: Float, height: Float) { // Set new dimensions self.dimensions.set((width: width, height: height)) // Create a new context with new dimensions do { self.context = try GraphicsContext( width: width, height: height, backend: self.context.backend ) } catch { Logger.error("Cannot create new graphics context: \(error)") exit(-1) } } } enum GLFWError: Error { case initFailed case noPrimaryMonitor case noVideoMode case cannotCreateWindow } /// Called when any GLFW window is resized. `GLFWWindow` reference can be retrieved /// from the window user pointer. private func onWindowResized(window: OpaquePointer, width: Int32, height: Int32) { let unmanagedWindow = Unmanaged<GLFWWindow>.fromOpaque(UnsafeRawPointer(glfwGetWindowUserPointer(window))) let glfwWindow = unmanagedWindow.takeUnretainedValue() glfwWindow.onResized(width: Float(width), height: Float(height)) } private func onGlDebugMessage(severity: GLenum, type: GLenum, id: GLuint, message: UnsafePointer<CChar>?) { Logger.debug(debugGraphicsBackend, "OpenGL \(severity) \(id): \(message.str ?? "unspecified")") }
31.778723
128
0.601366
bf088339a5f38b74fbe18bd779a6e270352ab7dc
2,305
// // SceneDelegate.swift // TextField // // Created by Giovanni Vicentin Moratto on 02/11/21. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.490566
147
0.7141
bbbd8d6b152adec55dd48619675715aba0941125
1,246
// // Solution.swift // Problem 243 // // Created by sebastien FOCK CHOW THO on 2020-01-23. // Copyright © 2020 sebastien FOCK CHOW THO. All rights reserved. // import Foundation extension Array where Element == Int { func minimumSumForKPartitions(k: Int) -> Int { guard count > 0 else { fatalError("empty array") } let candidates = split(partitionsSize: k, base: []) let sums = candidates.map{ $0.map{ $0.reduce(0) { $0 + $1 } } } let maxValues = sums.map{ $0.reduce(0) { $1 > $0 ? $1 : $0 } } let sorted = maxValues.sorted{ $0 < $1 } return sorted.first! } func split(partitionsSize k: Int, base: [[Int]]) -> [[[Int]]] { var result: [[[Int]]] = [] if k > 1 { for i in 0..<count-k { var copy = base copy.append(Array(self[0...i])) result.append(contentsOf: Array(self[i+1...count-1]).split(partitionsSize: k-1, base: copy)) } } else { var copy = base copy.append(self) result.append(copy) } return result } }
25.958333
108
0.477528
754d2e70942d43eaeb4203c2e66e15f70a0b92d3
329
// // SwapRequestInfoProtocol.swift // iRevatureTrainingRoomRequests // // Created by admin on 2/19/20. // Copyright © 2020 revature. All rights reserved. // import Foundation protocol SwapRequestsProtocol { func getSwapRequestsInfo() -> SwapRequest? func setSwapRequestsInfo(RequestObject:SwapRequest) -> Bool? }
20.5625
64
0.744681
0a7b72ece0aad5339b88b9fd792fb5483fd0868f
613
/// representing keys on a standard american keyboard /// which means: Key.Y will represent the Key that gives the letter z on german keyboards /// prefix N for number keys, e.g. N0 --> 0 /// prefix L for letter keys, e.g. B --> B public enum Key: CaseIterable { case ArrowUp, ArrowRight, ArrowDown, ArrowLeft case Return, Enter, Backspace, Delete, Space, Escape case LeftShift, LeftCtrl, LeftAlt case N0, N1, N2, N3, N4, N5, N6, N7, N8, N9 case A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z case F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12 }
34.055556
89
0.618271
28aee19d85d5bb8b7474c375e8bbd66cbfe3b297
2,175
// // AppDelegate.swift // StyledSegmented // // Created by Tobioka on 2017/11/11. // Copyright © 2017年 tnantoka. 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 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.276596
285
0.756322
64bce93bb60da16de31379cf95241317e67701ea
3,209
// RUN: %target-typecheck-verify-swift struct S { init(i: Int) { } struct Inner { init(i: Int) { } } } enum E { case X case Y(Int) init(i: Int) { self = .Y(i) } enum Inner { case X case Y(Int) } } class C { init(i: Int) { } // expected-note 4{{selected non-required initializer 'init(i:)'}} required init(d: Double) { } class Inner { init(i: Int) { } } static func makeCBad() -> C { return self.init(i: 0) // expected-error@-1 {{constructing an object of class type 'C' with a metatype value must use a 'required' initializer}} } static func makeCGood() -> C { return self.init(d: 0) } static func makeSelfBad() -> Self { return self.init(i: 0) // expected-error@-1 {{constructing an object of class type 'Self' with a metatype value must use a 'required' initializer}} } static func makeSelfGood() -> Self { return self.init(d: 0) } static func makeSelfImplicitBaseBad() -> Self { return .init(i: 0) // expected-error@-1 {{constructing an object of class type 'Self' with a metatype value must use a 'required' initializer}} } static func makeSelfImplicitBaseGood() -> Self { return .init(d: 0) } } final class D { init(i: Int) { } } // -------------------------------------------------------------------------- // Construction from Type values // -------------------------------------------------------------------------- func getMetatype<T>(_ m : T.Type) -> T.Type { return m } // Construction from a struct Type value func constructStructMetatypeValue() { _ = getMetatype(S.self).init(i: 5) _ = getMetatype(S.self)(i: 5) // expected-error{{initializing from a metatype value must reference 'init' explicitly}} {{26-26=.init}} _ = getMetatype(S.self) } // Construction from a struct Type value func constructEnumMetatypeValue() { _ = getMetatype(E.self).init(i: 5) } // Construction from a class Type value. func constructClassMetatypeValue() { // Only permitted with a @required constructor. _ = getMetatype(C.self).init(d: 1.5) // okay _ = getMetatype(C.self).init(i: 5) // expected-error{{constructing an object of class type 'C' with a metatype value must use a 'required' initializer}} _ = getMetatype(D.self).init(i: 5) } // -------------------------------------------------------------------------- // Construction via archetypes // -------------------------------------------------------------------------- protocol P { init() } func constructArchetypeValue<T: P>(_ t: T, tm: T.Type) { var t = t var t1 = T() t = t1 t1 = t var t2 = tm.init() t = t2 t2 = t } // -------------------------------------------------------------------------- // Construction via existentials. // -------------------------------------------------------------------------- protocol P2 { init(int: Int) } func constructExistentialValue(_ pm: P.Type) { _ = pm.init() _ = P() // expected-error{{type 'any P' cannot be instantiated}} } typealias P1_and_P2 = P & P2 func constructExistentialCompositionValue(_ pm: (P & P2).Type) { _ = pm.init(int: 5) _ = P1_and_P2(int: 5) // expected-error{{type 'any P1_and_P2' (aka 'any P & P2') cannot be instantiated}} }
25.879032
154
0.553443
5dc8db9e84f640d597b44bf73d9f589d87df45e0
1,848
// // ExtensionParserTest.swift // phpmon-tests // // Created by Nico Verbruggen on 13/02/2021. // Copyright © 2021 Nico Verbruggen. All rights reserved. // import XCTest class ExtensionParserTest: XCTestCase { static var phpIniFileUrl: URL { return Bundle(for: Self.self).url(forResource: "php", withExtension: "ini")! } func testCanLoadExtension() throws { let extensions = PhpExtension.load(from: Self.phpIniFileUrl) XCTAssertGreaterThan(extensions.count, 0) } func testExtensionNameIsCorrect() throws { let extensions = PhpExtension.load(from: Self.phpIniFileUrl) XCTAssertEqual(extensions.first!.name, "xdebug") XCTAssertEqual(extensions.last!.name, "imagick") } func testExtensionStatusIsCorrect() throws { let extensions = PhpExtension.load(from: Self.phpIniFileUrl) XCTAssertEqual(extensions.first!.enabled, true) XCTAssertEqual(extensions.last!.enabled, false) } func testToggleWorksAsExpected() throws { let destination = Utility.copyToTemporaryFile(resourceName: "php", fileExtension: "ini")! let extensions = PhpExtension.load(from: destination) XCTAssertEqual(extensions.count, 2) // Try to disable it! let xdebug = extensions.first! XCTAssertEqual(xdebug.enabled, true) xdebug.toggle() XCTAssertEqual(xdebug.enabled, false) // Check if the file contains the appropriate data let file = try! String(contentsOf: destination, encoding: .utf8) XCTAssertTrue(file.contains("; zend_extension=\"xdebug.so\"")) // Make sure if we load the data again, it's disabled XCTAssertEqual(PhpExtension.load(from: destination).first!.enabled, false) } }
32.421053
97
0.65855
1dbf61b4d27c57a37a5b1e4e0c756f11a357bbbd
4,490
// // NewShiftCardModule.swift // AptoSDK // // Created by Ivan Oliver Martínez on 08/03/2018. // import UIKit import AptoSDK class NewCardModule: UIModule { private let initialDataPoints: DataPointList private let cardProductId: String private weak var workflowModule: WorkflowModule? // swiftlint:disable implicitly_unwrapped_optional var contextConfiguration: ContextConfiguration! var projectConfiguration: ProjectConfiguration { return contextConfiguration.projectConfiguration } var cardProduct: CardProduct! // swiftlint:enable implicitly_unwrapped_optional private let cardMetadata: String? public init(serviceLocator: ServiceLocatorProtocol, initialDataPoints: DataPointList, cardProductId: String, cardMetadata: String?) { self.initialDataPoints = initialDataPoints self.cardProductId = cardProductId self.cardMetadata = cardMetadata super.init(serviceLocator: serviceLocator) } override func initialize(completion: @escaping Result<UIViewController, NSError>.Callback) { self.loadConfigurationFromServer { [weak self] result in switch result { case .failure(let error): completion(.failure(error)) case .success: self?.startNewApplication(completion: completion) } } } // MARK: - Configuration HandlingApplication fileprivate func loadConfigurationFromServer(_ completion:@escaping Result<Void, NSError>.Callback) { showLoadingView() platform.fetchContextConfiguration { [weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.hideLoadingView() completion(.failure(error)) case .success (let contextConfiguration): self.contextConfiguration = contextConfiguration self.platform.fetchCardProduct(cardProductId: self.cardProductId) { [weak self] result in guard let self = self else { return } self.hideLoadingView() switch result { case .failure(let error): completion(.failure(error)) case .success(let cardProduct): self.cardProduct = cardProduct completion(.success(Void())) } } } } } private func startNewApplication(completion: @escaping Result<UIViewController, NSError>.Callback) { showLoadingView() platform.applyToCard(cardProduct: cardProduct) { [weak self] result in guard let self = self else { return } self.hideLoadingView() switch result { case .failure(let error): completion(.failure(error)) case .success(let application): let workflowModule = self.workflowModuleFor(application: application) self.workflowModule = workflowModule self.addChild(module: workflowModule, completion: completion) } } } private func workflowModuleFor(application: CardApplication) -> WorkflowModule { let moduleFactory = WorkflowModuleFactoryImpl(serviceLocator: serviceLocator, workflowObject: application, cardMetadata: cardMetadata) let workflowModule = WorkflowModule(serviceLocator: serviceLocator, workflowObject: application, workflowObjectStatusRequester: self, workflowModuleFactory: moduleFactory) workflowModule.onClose = { module in self.close() } return workflowModule } } // MARK: - WorkflowObjectStatusRequester protocol extension NewCardModule: WorkflowObjectStatusRequester { func getStatusOf(workflowObject: WorkflowObject, completion: @escaping (Result<WorkflowObject, NSError>.Callback)) { guard let application = workflowObject as? CardApplication else { completion(.failure(ServiceError(code: ServiceError.ErrorCodes.internalIncosistencyError))) return } showLoadingView() platform.fetchCardApplicationStatus(application.id) { [weak self] result in guard let self = self else { return } self.hideLoadingView() switch result { case .failure(let error): self.show(error: error) case .success(let application): if application.status == .approved { self.finish(result: self.workflowModule?.lastResult) return } completion(.success(application)) } } } } extension CardProduct: WorkflowObject { public var workflowObjectId: String { return self.id } public var nextAction: WorkflowAction { return self.disclaimerAction } }
33.507463
138
0.706013
2826fa60f250a258813f26329eb903a46214ad6a
13,103
#if canImport(UIKit) import UIKit import AuthenticationServices import SafariServices class PayPalTokenizationViewModel: PaymentMethodTokenizationViewModel, ExternalPaymentMethodTokenizationViewModelProtocol { var willPresentExternalView: (() -> Void)? var didPresentExternalView: (() -> Void)? var willDismissExternalView: (() -> Void)? var didDismissExternalView: (() -> Void)? private var session: Any! override lazy var title: String = { return "PayPal" }() override lazy var buttonTitle: String? = { switch config.type { case .payPal: return nil default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonImage: UIImage? = { switch config.type { case .payPal: return UIImage(named: "paypal3", in: Bundle.primerResources, compatibleWith: nil) default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonColor: UIColor? = { switch config.type { case .payPal: return UIColor(red: 0.745, green: 0.894, blue: 0.996, alpha: 1) default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonTitleColor: UIColor? = { switch config.type { case .payPal: return nil default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonBorderWidth: CGFloat = { switch config.type { case .payPal: return 0.0 default: assert(true, "Shouldn't end up in here") return 0.0 } }() override lazy var buttonBorderColor: UIColor? = { switch config.type { case .payPal: return nil default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonTintColor: UIColor? = { switch config.type { case .payPal: return nil default: assert(true, "Shouldn't end up in here") return nil } }() override lazy var buttonFont: UIFont? = { return UIFont.systemFont(ofSize: 17.0, weight: .medium) }() override lazy var buttonCornerRadius: CGFloat? = { return 4.0 }() deinit { log(logLevel: .debug, message: "🧨 deinit: \(self) \(Unmanaged.passUnretained(self).toOpaque())") } override func validate() throws { let state: AppStateProtocol = DependencyContainer.resolve() // let settings: PrimerSettingsProtocol = DependencyContainer.resolve() guard let decodedClientToken = state.decodedClientToken, decodedClientToken.isValid else { let err = PaymentException.missingClientToken _ = ErrorHandler.shared.handle(error: err) throw err } guard decodedClientToken.pciUrl != nil else { let err = PrimerError.tokenizationPreRequestFailed _ = ErrorHandler.shared.handle(error: err) throw err } guard config.id != nil else { let err = PaymentException.missingConfigurationId _ = ErrorHandler.shared.handle(error: err) throw err } guard decodedClientToken.coreUrl != nil else { let err = PrimerError.invalidValue(key: "coreUrl") _ = ErrorHandler.shared.handle(error: err) throw err } } @objc override func startTokenizationFlow() { super.startTokenizationFlow() do { try validate() } catch { DispatchQueue.main.async { Primer.shared.delegate?.checkoutFailed?(with: error) self.handleFailedTokenizationFlow(error: error) } return } firstly { self.tokenize() } .done { paymentMethod in self.paymentMethod = paymentMethod if Primer.shared.flow.internalSessionFlow.vaulted { Primer.shared.delegate?.tokenAddedToVault?(paymentMethod) } Primer.shared.delegate?.onTokenizeSuccess?(paymentMethod, resumeHandler: self) Primer.shared.delegate?.onTokenizeSuccess?(paymentMethod, { [unowned self] err in if let err = err { self.handleFailedTokenizationFlow(error: err) } else { self.handleSuccessfulTokenizationFlow() } }) } .catch { err in Primer.shared.delegate?.checkoutFailed?(with: err) self.handleFailedTokenizationFlow(error: err) } } func tokenize() -> Promise <PaymentMethodToken> { return Promise { seal in firstly { self.fetchOAuthURL() } .then { url -> Promise<URL> in self.willPresentExternalView?() return self.createOAuthSession(url) } .then { url -> Promise<PaymentInstrument> in return self.generatePaypalPaymentInstrument() } .then { instrument -> Promise<PaymentMethodToken> in return self.tokenize(instrument: instrument) } .done { token in seal.fulfill(token) } .catch { err in seal.reject(err) } } } private func fetchOAuthURL() -> Promise<URL> { return Promise { seal in let paypalService: PayPalServiceProtocol = DependencyContainer.resolve() switch Primer.shared.flow.internalSessionFlow.uxMode { case .CHECKOUT: paypalService.startOrderSession { result in switch result { case .success(let urlStr): guard let url = URL(string: urlStr) else { seal.reject(PrimerError.failedToLoadSession) return } seal.fulfill(url) case .failure(let err): seal.reject(err) } } case .VAULT: paypalService.startBillingAgreementSession { result in switch result { case .success(let urlStr): guard let url = URL(string: urlStr) else { seal.reject(PrimerError.failedToLoadSession) return } seal.fulfill(url) case .failure(let err): seal.reject(err) } } } } } private func createOAuthSession(_ url: URL) -> Promise<URL> { return Promise { seal in let settings: PrimerSettingsProtocol = DependencyContainer.resolve() guard let urlScheme = settings.urlScheme else { seal.reject(PrimerError.missingURLScheme) return } if #available(iOS 13, *) { session = ASWebAuthenticationSession( url: url, callbackURLScheme: urlScheme, completionHandler: { (url, error) in if let error = error { seal.reject(error) } else if let url = url { seal.fulfill(url) } } ) (session as! ASWebAuthenticationSession).presentationContextProvider = self (session as! ASWebAuthenticationSession).start() } else if #available(iOS 11, *) { session = SFAuthenticationSession( url: url, callbackURLScheme: urlScheme, completionHandler: { (url, err) in if let err = err { seal.reject(err) } else if let url = url { seal.fulfill(url) } } ) (session as! SFAuthenticationSession).start() } didPresentExternalView?() } } private func generatePaypalPaymentInstrument() -> Promise<PaymentInstrument> { return Promise { seal in generatePaypalPaymentInstrument { result in switch result { case .success(let paymentInstrument): seal.fulfill(paymentInstrument) case .failure(let err): seal.reject(err) } } } } private func generatePaypalPaymentInstrument(_ completion: @escaping (Result<PaymentInstrument, Error>) -> Void) { switch Primer.shared.flow.internalSessionFlow.uxMode { case .CHECKOUT: let orderId: AppStateProtocol = DependencyContainer.resolve() guard let orderId = orderId.orderId else { completion(.failure(PrimerError.orderIdMissing)) return } let paymentInstrument = PaymentInstrument(paypalOrderId: orderId) completion(.success(paymentInstrument)) case .VAULT: let state: AppStateProtocol = DependencyContainer.resolve() guard let confirmedBillingAgreement = state.confirmedBillingAgreement else { generateBillingAgreementConfirmation { [weak self] err in if let err = err { completion(.failure(err)) } else { self?.generatePaypalPaymentInstrument(completion) } } return } let paymentInstrument = PaymentInstrument( paypalBillingAgreementId: confirmedBillingAgreement.billingAgreementId, shippingAddress: confirmedBillingAgreement.shippingAddress, externalPayerInfo: confirmedBillingAgreement.externalPayerInfo ) completion(.success(paymentInstrument)) } } private func generateBillingAgreementConfirmation(_ completion: @escaping (Error?) -> Void) { let paypalService: PayPalServiceProtocol = DependencyContainer.resolve() paypalService.confirmBillingAgreement({ result in switch result { case .failure(let error): log(logLevel: .error, title: "ERROR!", message: error.localizedDescription, prefix: nil, suffix: nil, bundle: nil, file: #file, className: String(describing: Self.self), function: #function, line: #line) completion(PrimerError.payPalSessionFailed) case .success: completion(nil) } }) } private func tokenize(instrument: PaymentInstrument) -> Promise<PaymentMethodToken> { return Promise { seal in let state: AppStateProtocol = DependencyContainer.resolve() let request = PaymentMethodTokenizationRequest(paymentInstrument: instrument, state: state) let tokenizationService: TokenizationServiceProtocol = DependencyContainer.resolve() tokenizationService.tokenize(request: request) { [weak self] result in switch result { case .failure(let err): seal.reject(err) case .success(let token): seal.fulfill(token) } } } } } extension PayPalTokenizationViewModel { override func handle(error: Error) { self.completion?(nil, error) self.completion = nil } override func handle(newClientToken clientToken: String) { try? ClientTokenService.storeClientToken(clientToken) } override func handleSuccess() { self.completion?(self.paymentMethod, nil) self.completion = nil } } @available(iOS 11.0, *) extension PayPalTokenizationViewModel: ASWebAuthenticationPresentationContextProviding { @available(iOS 12.0, *) func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return UIApplication.shared.keyWindow ?? ASPresentationAnchor() } } #endif
33.945596
219
0.526444
7905a0ef3be7c252a149af093e3a5960143b3654
2,042
// // TextGuideStyle.swift // KrakenDemoApp // // Created by Christian Slanzi on 12.03.22. // import Foundation import SwiftUI struct Header1: ViewModifier { func body(content: Content) -> some View { content .font(.system(.largeTitle, design: .serif)) .foregroundColor(Color.theme.primaryText) } } struct Header2: ViewModifier { func body(content: Content) -> some View { content .font(.title) .foregroundColor(Color.theme.primaryText) } } struct Header3: ViewModifier { func body(content: Content) -> some View { content .font(.headline) .foregroundColor(Color.theme.primaryText) } } struct FootNote: ViewModifier { func body(content: Content) -> some View { content .font(.footnote) .foregroundColor(Color.theme.primaryText) } } struct BodyStyle: ViewModifier { func body(content: Content) -> some View { content .font(.body) .foregroundColor(Color.theme.primaryText) } } struct GrayBodyStyle: ViewModifier { func body(content: Content) -> some View { content .font(.body) .foregroundColor(Color.theme.secondaryText) } } struct TextStyleGuide: View { var body: some View { VStack { Text("title style") .modifier(Header1()) Text("Header 2") .modifier(Header2()) Text("Header 3") .modifier(Header3()) Text("Body style") .modifier(BodyStyle()) Text("Gray Body style") .modifier(GrayBodyStyle()) Text("Header 2") .modifier(FootNote()) } } } struct TextStyleGuide_Previews: PreviewProvider { static var previews: some View { TextStyleGuide() } }
20.836735
55
0.526934
3392a6b7ce3046c5ebf4d737088c90b25df0cefa
2,164
// // AppDelegate.swift // CustomKeyBoard // // Created by 夜猫子 on 2017/4/25. // Copyright © 2017年 夜猫子. 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 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.042553
285
0.755083
213a96e9f9e504cd11928488bb91022d753e9404
1,200
// // MovieService.swift // Movies // // Created by Yurii Sameliuk on 06/02/2021. // import Foundation protocol MovieService { func fetchMovies(from endpoint: MovieListEndpoint, completion: @escaping (Result<MovieResponse, MovieError>) -> ()) func fetchMovie(id: Int, completion: @escaping (Result<MovieModel, MovieError>) -> ()) } enum MovieListEndpoint: String, CaseIterable, Identifiable { var id: String { rawValue } case popular var description: String { switch self { case .popular: return "Popular" } } } enum MovieError: Error, CustomNSError { case apiError case invalidEndpoint case invalidResponse case noData case serializationError var localizedDescription: String { switch self { case .apiError: return "Failed to fetch data" case .invalidEndpoint: return "Invalid endpoint" case .invalidResponse: return "Invalid response" case .noData: return "No data" case .serializationError: return "Failed to decode data" } } var errorUserInfo: [String : Any] { [NSLocalizedDescriptionKey: localizedDescription] } }
24
119
0.655
e5a6f94b2e20ef2e1792bb4fb149381a4a9879e0
963
/* See LICENSE folder for this sample’s licensing information. Abstract: Description about what the file includes goes here. */ import UIKit import HealthKit class WorkoutStartView: UIViewController { let healthStore = HKHealthStore() override func viewDidLoad() { super.viewDidLoad() title = "SpeedySloth" navigationController?.navigationBar.prefersLargeTitles = true let typesToShare: Set = [ HKQuantityType.workoutType() ] let typesToRead: Set = [ HKQuantityType.quantityType(forIdentifier: .heartRate)!, HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!, HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning)! ] healthStore.requestAuthorization(toShare: typesToShare, read: typesToRead) { (success, error) in // Handle error } } }
25.342105
104
0.640706
23c498a070132c2b210c93ef4ea6bf026bb8ae2d
79
typealias NnAm_AppletAttribute = [UInt8] typealias NnAm_AppletMessage = UInt32
26.333333
40
0.848101